Skip to content

Kafka to_binary() crashes on events without datacontenttype or with non-string attributes #304

Description

@amdadulbari

Description

to_binary() in cloudevents/v1/kafka/conversion.py raises on two kinds of perfectly valid CloudEvents:

1. Missing datacontenttype (optional attribute) → KeyError

    headers = {}
    if event["datacontenttype"]:                      # KeyError if unset
        headers["content-type"] = event["datacontenttype"].encode("utf-8")

datacontenttype is optional, so event["datacontenttype"] raises KeyError for any event that does not set it. The sibling to_structured() in the same file already guards this with if "datacontenttype" in attrs:.

2. Non-string attribute value → AttributeError

            if value is not None:
                headers["ce_{0}".format(attr)] = value.encode("utf-8")   # AttributeError if not str

CloudEvents extension attributes may be non-string (e.g. Integer/Boolean), so value.encode(...) raises AttributeError: 'int' object has no attribute 'encode'. The newer core Kafka binding already does str(attr_value).encode(...).

Reproduction

from cloudevents.v1.http import CloudEvent
from cloudevents.v1.kafka import to_binary

# 1) no datacontenttype -> KeyError: 'datacontenttype'
to_binary(CloudEvent({"type": "t", "source": "s"}, {"a": 1}))

# 2) non-string extension -> AttributeError: 'int' object has no attribute 'encode'
to_binary(CloudEvent({"type": "t", "source": "s",
                      "datacontenttype": "application/json", "ext1": 5}, {"a": 1}))

Expected behaviour

to_binary() should handle both valid events: omit the content-type header when datacontenttype is absent, and stringify non-string attribute values.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions