Receiving Events
A few things to consider at the receiving side when forwarding events with Data Connectors.

Request Contents

Both the header and body of the incoming request contain information of interest that can be extracted and, depending on the configuration, used to verify the content and origin of the request.
If a signature secret is set in the configuration, the following header will be included.
  • X-Dt-Signature Includes a JSON Web Token (JWT). Once decoded using the signature secret, it contains all the necessary information to verify the request content and origin.
Note that depending on the framework used to receive the Data Connector events, the header name casing may differ. Some services will force header name to lower-case, like x-dt-signature.

Body

The request body contains three fields, event, labels, and metadata. The following snippet shows an example request body of a touch event for a humidity sensor forwarded by a Data Connector.
1
{
2
"event": {
3
"eventId": "<EVENT_ID>",
4
"targetName": "projects/<PROJECT_ID>/devices/<DEVICE_ID>",
5
"eventType": "touch",
6
"data": {
7
"touch": {
8
"updateTime": "2021-05-28T08:34:06.225872Z"
9
}
10
},
11
"timestamp": "2021-05-28T08:34:06.225872Z"
12
},
13
"labels": {
14
"room-number": "99"
15
},
16
"metadata": {
17
"deviceId": "<DEVICE_ID>",
18
"projectId": "<PROJECT_ID>",
19
"deviceType": "humidity",
20
"productNumber": "102081"
21
}
22
}
Copied!
Field
Type
Description
event
struct
Contains event data. See the Event documentation where the structure is explained in detail for each event type.
labels
struct
Device label key- and value pairs included by the Data Connector. See the Advanced Configuration page for details about include labels.
metadata
struct
Contains metadata about the event. See the section below for more details.

Event Metadata

Each event has a metadata field that includes details about the event. The event metadata has the following structure.
Field
Type
Description
deviceId
string
The identifier of the device that published the event.
projectId
string
The identifier of the project the device is in.
deviceType
string
The device type that published the event.
productNumber
string
The product number of the device that published the event.
Note
The structure of the metadata field might change in the future if event types are added that are not published by devices. Make sure to first check event.eventType to make sure it is a known device event before processing the metadata field.
See the code sample below for an example of how to do this.
The event metadata makes it possible to check which device type has published the event, even for event types like touch or networkStatus which are published by many types of devices. This makes it possible to add new devices to a database without having to first look up the device using the REST API.
The metadata also provides a more convenient way to get the deviceId and projectId of the device that published the event, without having to parse the event.targetName field.

Acknowledging Received Event

A request-reply flow on the Endpoint URL should be implemented as follows:
  1. 1.
    Your endpoint receives an HTTPS POST request.
  2. 2.
    Your service processes the data in some way.
  3. 3.
    Your service replies to the event request with a 200 OK response.
What is important to note here is that the request should never return an HTTP 200 OK response before you are done processing it. When the DT Cloud receives a response with a 200 status code, the event will be taken off the internal Data Connector queue and checked off as received.
Best Practice
Do not reply 200 OK until you have finished processing your data.
Note that any status code in the range 2xx will be accepted as OK in the response.

Verifying Signed Events

When using a Signature Secret, the X-Dt-Signature header is included and contains a JWT, signed by the Signature Secret. Inside, a checksum of the request body can be found and used to check for tampering.
The following steps sum up the process of verifying the received request at the receiving endpoint.
  1. 1.
    Extract the signed JWT from the HTTP header X-Dt-Signature of the received request.
  2. 2.
    Verify the JWT's signature with the signature secret.
  3. 3.
    Calculate a SHA1 checksum over the entire request body.
  4. 4.
    Compare the body checksum with the checksum contained in the JWT.
  5. 5.
    If these checksums are identical, you can be certain that the event has not been tampered with and originated from your Data Connector.
The following snippet from our Google Cloud Function example integration implements this verification process.
Python 3.9
Python API
Node.js 16
Go 1.16
1
import os
2
import hashlib
3
import jwt # pip install pyjwt==2.3.0
4
5
# Fetch environment variables.
6
SIGNATURE_SECRET = os.environ.get('DT_SIGNATURE_SECRET')
7
8
9
def verify_request(body, token):
10
"""
11
Verifies that the request originated from DT, and that the body
12
hasn't been modified since it was sent. This is done by verifying
13
that the checksum field of the JWT token matches the checksum of the
14
request body, and that the JWT is signed with the signature secret.
15
"""
16
17
# Decode the token using signature secret.
18
try:
19
payload = jwt.decode(token, SIGNATURE_SECRET, algorithms=["HS256"])
20
except Exception as err:
21
print(err)
22
return False
23
24
# Verify the request body checksum.
25
m = hashlib.sha1()
26
m.update(body)
27
checksum = m.digest().hex()
28
if payload["checksum"] != checksum:
29
print('Checksum Mismatch')
30
return False
31
32
return True
33
34
35
def dataconnector_endpoint(request):
36
# Extract the body as a bytestring and the signed JWT.
37
# We'll use these values to verify the request.
38
payload = request.get_data()
39
token = request.headers['x-dt-signature']
40
41
# Verify request origin and content integrity.
42
if not verify_request(payload, token):
43
return ('Could not verify request.', 400)
44
45
# Decode the body as JSON
46
body = request.get_json()
47
48
# First, check if the event type is one of the event
49
# types we're expecting.
50
# As an example, we'll check for touch events here.
51
if body['event']['eventType'] == 'touch':
52
# Now that we know this is a device event, we can
53
# check for the device type and device identifier
54
# in the event metadata.
55
device_type = body['metadata']['deviceType']
56
device_id = body['metadata']['deviceId']
57
58
print(f"Received touch event from {device_type} sensor with id {device_id}")
59
60
return ('OK', 200)
Copied!
1
import os
2
from dtintegrations import data_connector, provider
3
4
DT_SIGNATURE_SECRET = os.getenv('DT_SIGNATURE_SECRET')
5
6
7
def dataconnector_endpoint(request):
8
# Validate and decode the incoming request.
9
event = data_connector.http_push.decode_request(
10
request,
11
provider=provider.GCLOUD,
12
secret=DT_SIGNATURE_SECRET,
13
)
14
15
# Print the event data.
16
print(event)
17
18
# If all is well, return 200 response.
19
return ('OK', 200)
Copied!
1
const crypto = require('crypto')
2
const jwt = require('jsonwebtoken') // npm install [email protected]
3
4
// Fetch environment variables
5
const signatureSecret = process.env.DT_SIGNATURE_SECRET
6
7
// Verifies that the request originated from DT, and that the body
8
// hasn't been modified since it was sent. This is done by verifying
9
// that the checksum field of the JWT token matches the checksum of the
10
// request body, and that the JWT is signed with the signature secret.
11
function verifyRequest(body, token) {
12
// Decode the JWT, and verify that it was
13
// signed using the signature secret.
14
let decoded
15
try {
16
decoded = jwt.verify(token, signatureSecret)
17
} catch(err) {
18
console.log(err)
19
return false
20
}
21
22
// Verify the request body checksum.
23
let shasum = crypto.createHash('sha1')
24
let checksum = shasum.update(body).digest('hex')
25
if (checksum !== decoded.checksum) {
26
console.log('Checksum Mismatch')
27
return false
28
}
29
30
return true
31
}
32
33
exports.dataconnectorEndpoint = (req, res) => {
34
// Extract the body as a string and the signed JWT.
35
// We'll use these values to verify the request.
36
let payload = JSON.stringify(req.body)
37
let token = req.get('X-Dt-Signature')
38
39
// Validate request origin and content integrity.
40
if (verifyRequest(payload, token) === false) {
41
res.sendStatus(400)
42
return
43
}
44
45
// First, check if the event type is one of the event
46
// types we're expecting.
47
// As an example, we'll check for touch events here.
48
switch (req.body.event.eventType) {
49
case 'touch':
50
// Now that we know this is a device event, we can
51
// check for the device type and device identifier
52
// in the event metadata.
53
deviceType = req.body.metadata.deviceType
54
deviceId = req.body.metadata.deviceId
55
56
console.log(`Received touch event from ${deviceType} sensor with id ${deviceId}`)
57
break
58
default:
59
break
60
}
61
62
res.sendStatus(200);
63
};
Copied!
1
package main
2
3
import (
4
"crypto/sha1"
5
"encoding/hex"
6
"encoding/json"
7
"fmt"
8
"io/ioutil"
9
"net/http"
10
"os"
11
12
jwt "github.com/golang-jwt/jwt/v4" // go get github.com/golang-jwt/jwt/[email protected]
13
)
14
15
// Environment variables.
16
var signatureSecret = os.Getenv("DT_SIGNATURE_SECRET")
17
18
// verifyRequest verifies that the request originated from DT, and that the
19
// body hasn't been modified since it was sent. This is done by verifying
20
// that the checksum field of the JWT token matches the checksum of the
21
// request body, and that the JWT is signed with the signature secret.
22
func verifyRequest(bodyBytes []byte, tokenString string) error {
23
// Decode the JWT, and verify that it was signed using the signature secret.
24
// Also verifies the algorithm used to sign the JWT.
25
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
26
// Return out signature secret to verify that it was used to sign the JWT.
27
return []byte(signatureSecret), nil
28
}, jwt.WithValidMethods([]string{"HS256"}))
29
if err != nil {
30
return err
31
}
32
33
// Verify the request body checksum.
34
sha1Bytes := sha1.Sum(bodyBytes)
35
sha1String := hex.EncodeToString(sha1Bytes[:])
36
claims := token.Claims.(jwt.MapClaims)
37
if sha1String != claims["checksum"] {
38
return fmt.Errorf("Checksum mismatch.")
39
}
40
41
return nil
42
}
43
44
// DataConnectorEndpoint receives, validates, and returns a response for the forwarded event.
45
func DataconnectorEndpoint(w http.ResponseWriter, r *http.Request) {
46
47
// Extract the body and the signed JWT.
48
// We'll use these values to verify the request.
49
tokenString := r.Header.Get("x-dt-signature")
50
bodyBytes, err := ioutil.ReadAll(r.Body)
51
if err != nil {
52
fmt.Println(err)
53
http.Error(w, err.Error(), http.StatusBadRequest)
54
return
55
}
56
57
// Validate request origin and content integrity.
58
if err := verifyRequest(bodyBytes, tokenString); err != nil {
59
fmt.Println(err)
60
http.Error(w, err.Error(), http.StatusBadRequest)
61
return
62
}
63
64
// We now know the request came from DT Cloud, and the integrity
65
// of the body has been verify. We can now handle the event safely.
66
if err := handleEvent(bodyBytes); err != nil {
67
fmt.Println(err)
68
http.Error(w, err.Error(), http.StatusBadRequest)
69
return
70
}
71
72
// Respond with a 200 status code to ack the event,
73
w.WriteHeader(http.StatusOK)
74
_, _ = w.Write([]byte("OK"))
75
}
76
77
func handleEvent(payload []byte) error {
78
// The structure of the events we'll received from a Data Connector.
79
type Event struct {
80
Event struct {
81
EventId string `json:"eventId"`
82
EventType string `json:"eventType"`
83
Data json.RawMessage `json:"data"`
84
Timestamp string `json:"timestamp"`
85
} `json:"event"`
86
Labels map[string]string `json:"labels"`
87
Metadata map[string]string `json:"metadata"`
88
}
89
90
// The structure of the `Event.Data` field for a touch event.
91
// We'll be using touch events for this example.
92
type TouchData struct {
93
Touch struct {
94
Timestamp string `json:"updateTime"`
95
} `json:"touch"`
96
}
97
98
// Decode the event
99
var event Event
100
if err := json.Unmarshal(payload, &event); err != nil {
101
return err
102
}
103
104
// First, check if the event type is one of the event
105
// types we're expecting.
106
// As an example, we'll check for touch events here.
107
switch event.Event.EventType {
108
case "touch":
109
// Now that we know this is a touch event, we can decode
110
// the `Event.Data` field.
111
var touchData TouchData
112
if err := json.Unmarshal(event.Event.Data, &touchData); err != nil {
113
return err
114
}
115
116
// Also, since we now know this is a device event, we can
117
// check for the device type and device identifier
118
// in the event metadata.
119
deviceType := event.Metadata["deviceType"]
120
deviceId := event.Metadata["deviceId"]
121
timestamp := touchData.Touch.Timestamp
122
123
fmt.Printf("Received touch event at %s from %s sensor with id %s\n",
124
timestamp,
125
deviceType,
126
deviceId,
127
)
128
}
129
130
return nil
131
}
132
Copied!

Handling Duplicates

Every event received by DT Cloud is put in a dedicated, per-Data Connector queue. Messages are removed from this queue once acknowledged, or if the message is older than 12 hours.
A side effect of this delivery guarantee is that, under certain conditions, you may receive duplicates of the same event. While rare, deduplication should be performed on the receiving end by checking event IDs.
Best Practice
Use the included eventId field to check for duplicated events.

Retry policy

Any time a Data Connector does not receive a successful response (HTTP status code 2xx), the event will be retried. If an event has not been successfully acknowledged after 12 hours, it will be discarded.
The retry interval is calculated as an exponential backoff policy, given by
t02n1,t_0\cdot2^{n-1},
where
t0t0
is the initial interval of 8 seconds and
nn
the retry counter. The interval will not exceed 1 hour. For very slow endpoints, the minimum retry interval will be
4x4x
the response time.
Attempt
Retry Interval [s]
1
8
2
16
3
32
...
...
9
2048
10
3600
11
3600
Last modified 1mo ago