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 two fields, event and labels. The following snippet shows an example request body of a touch event forwarded by a Data Connector.

{
"event": {
"eventId": "EVENT_ID",
"targetName": "projects/PROJECT_ID/devices/DEVICE_ID",
"eventType": "touch",
"data": {
"touch": {
"updateTime": "2021-05-28T08:34:06.225872Z"
}
},
"timestamp": "2021-05-28T08:34:06.225872Z"
},
"labels": {
"room-number": "99"
}
}

Field

Type

Description

event

struct

Contains event data. See the Event documentation where the structure is explained in detail for each event type.

labels

sctruct

Device label key- and value pairs included by the Data Connector. See the Advanced Configuration page for details about include labels.

Acknowledging Received Event

A request-reply flow on the Endpoint URL should be implemented as follows:

  1. Your endpoint receives an HTTPS POST request.

  2. Your service processes the data in some way.

  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 our cloud receives a 200 OK, 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 the status code range 2xx will also 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. Extract the signed JWT from the HTTP header X-Dt-Signature of the received request.

  2. Verify the JWT's signature with the signature secret.

  3. Calculate a SHA1 checksum over the entire request body.

  4. Compare the body checksum with the checksum contained in the JWT.

  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 implements the verification process. It is written to run on a Google Cloud Function.

Python 3.9
Python API (Beta)
Node.js 14
Go 1.13
Python 3.9
import os
import hashlib
import jwt
# Fetch environment variables.
SIGNATURE_SECRET = os.environ.get('DT_SIGNATURE_SECRET')
def verify_request(body, token):
# Decode the token using signature secret.
try:
payload = jwt.decode(token, SIGNATURE_SECRET, algorithms=["HS256"])
except Exception as err:
print(err)
return False
# Verify the request body checksum.
m = hashlib.sha1()
m.update(body)
checksum = m.digest().hex()
if payload["checksum"] != checksum:
print('Checksum Mismatch')
return False
return True
def dataconnector_endpoint(request):
# Extract necessary request information.
body = request.get_data()
token = request.headers['x-dt-signature']
# Validate request origin and content integrity.
if not verify_request(body, token):
return ('Could not verify request.', 400)
#
# Further processing here.
#
return ('OK', 200)
Python API (Beta)
import os
from dtintegrations import data_connector, provider
DT_SIGNATURE_SECRET = os.getenv('DT_SIGNATURE_SECRET')
def dataconnector_endpoint(request):
# Validate and decode the incoming request.
event = data_connector.http_push.decode_request(
request,
provider=provider.GCLOUD,
secret=DT_SIGNATURE_SECRET,
)
# Print the event data.
print(event)
# If all is well, return 200 response.
return ('OK', 200)
Node.js 14
const crypto = require('crypto')
const jwt = require('jsonwebtoken') // npm install [email protected]
// Fetch environment variables
const signatureSecret = process.env.SIGNATURE_SECRET
function verifyRequest(body, token) {
// Decode the token using signature secret.
let decoded
try {
decoded = jwt.verify(token, signatureSecret)
} catch(err) {
console.log(err)
return false
}
// Verify the request body checksum.
let shasum = crypto.createHash('sha1')
let checksum = shasum.update(body).digest('hex')
if (checksum !== decoded.checksum) {
console.log('Checksum Mismatch')
return false
}
return true
}
exports.dataconnectorEndpoint = (req, res) => {
// Extract necessary request information.
let body = JSON.stringify(req.body)
let token = req.get('X-Dt-Signature')
// Validate request origin and content integrity.
if (verifyRequest(body, token) === false) {
res.sendStatus(400)
return
}
//
// Further processing here.
//
res.sendStatus(200);
};
Go 1.13
package triggerfunction
import (
"crypto/sha1"
"encoding/hex"
"fmt"
jwt "github.com/dgrijalva/jwt-go" // go get github.com/dgrijalva/[email protected]
"io/ioutil"
"log"
"net/http"
"os"
)
// Environment variables.
var signatureSecret = os.Getenv("DT_SIGNATURE_SECRET")
// verifyRequest validates the request origin and content integrity.
func verifyRequest(bodyBytes []byte, tokenString string) error {
// Decode the token using signature secret.
claims := jwt.MapClaims{}
_, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(signatureSecret), nil
})
if err != nil {
return err
}
// Verify the request body checksum.
sha1Bytes := sha1.Sum(bodyBytes)
sha1String := hex.EncodeToString(sha1Bytes[:])
if sha1String != claims["checksum"] {
return fmt.Errorf("Checksum mismatch.")
}
return nil
}
// DataConnectorEndpoint receives, validates, and returns a response for the forwarded event.
func DataconnectorEndpoint(w http.ResponseWriter, r *http.Request) {
// Extract necessary request information.
tokenString := r.Header.Get("x-dt-signature")
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
}
// Validate request origin and content integrity.
if err := verifyRequest(bodyBytes, tokenString); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
//
// Further processing here.
//
log.Println("OK")
fmt.Fprintf(w, "OK\n")
}

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 (HTTP 200 OK) response, the request will be retried. 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