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.

{
    "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"
    },
    "metadata": {
        "deviceId": "<DEVICE_ID>",
        "projectId": "<PROJECT_ID>",
        "deviceType": "humidity",
        "productNumber": "102081"
    }
}

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.

FieldTypeDescription

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. 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 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. 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 SHA256 checksum over the entire request body.

  4. Compare the body checksum with the checksum_sha256 field contained in the JWT (there's a checksum field as well that uses SHA1 which is less secure than SHA256, and is kept only for backward compatibility).

  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.

# This Python script is built on Flask, docs are available here:
# https://flask.palletsprojects.com/en/2.0.x/quickstart/

import os
import hashlib
import jwt                        # pip install pyjwt==2.7.0
from flask import Flask, request  # pip install Flask==2.3.2

app = Flask(__name__)

# Read environment variable.
SIGNATURE_SECRET = os.environ.get('DT_SIGNATURE_SECRET')


@app.route('/', methods=["POST"])
def data_connector_endpoint():
    # Extract the body as a bytestring and the signed JWT.
    # We'll use these values to verify the request.
    payload = request.get_data()
    token = request.headers['x-dt-signature']

    # Verify request origin and content integrity.
    if not verify_request(payload, token):
        return ('Could not verify request.', 400)

    # We now know the request came from DT Cloud, and the integrity
    # of the body has been verify. We can now handle the event safely.
    handle_event(request.get_json())

    # Respond with a 200 status code to ack the event. Any states codes
    # that are outside the 2xx range will nack the event, meaning it will
    # be retried later.
    return ('OK', 200)


def verify_request(body, token):
    """
    Verifies that the request originated from DT, and that the body
    hasn't been modified since it was sent. This is done by verifying
    that the checksum field of the JWT token matches the checksum of the
    request body, and that the JWT is signed with the signature secret.
    """

    # Decode the JWT, and verify that it was signed using the
    # signature secret. Also verifies that the algorithm used was HS256.
    try:
        payload = jwt.decode(token, SIGNATURE_SECRET, algorithms=["HS256"])
    except Exception as err:
        print(err)
        return False

    # Verify the request body checksum.
    m = hashlib.sha256()
    m.update(body)
    checksum = m.digest().hex()
    if payload["checksum_sha256"] != checksum:
        print('Checksum Mismatch')
        return False

    return True


def handle_event(body):
    """
    Processes the event itself. For this example, we will just
    decode a touch event, and print out the timestamp, device ID,
    and the device type.
    """
    # First, check if the event type is one of the event
    # types we're expecting.
    # As an example, we'll check for touch events here.
    if body['event']['eventType'] == 'touch':
        # Now that we know this is a device event, we can
        # check for the device type and device identifier
        # in the event metadata.
        device_type = body['metadata']['deviceType']
        device_id = body['metadata']['deviceId']
        timestamp = body['event']['data']['touch']['updateTime']

        print("Got touch event at {} from {} sensor with id {}".format(
            timestamp,
            device_type,
            device_id,
        ))

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 updated