Skip to content

Fix Kafka to_binary() crash on missing datacontenttype or non-string attributes - #305

Open
amdadulbari wants to merge 1 commit into
cloudevents:mainfrom
amdadulbari:fix/kafka-to-binary-optional-datacontenttype
Open

Fix Kafka to_binary() crash on missing datacontenttype or non-string attributes#305
amdadulbari wants to merge 1 commit into
cloudevents:mainfrom
amdadulbari:fix/kafka-to-binary-optional-datacontenttype

Conversation

@amdadulbari

@amdadulbari amdadulbari commented Aug 13, 2026

Copy link
Copy Markdown

Related Issue: #304

Type of change:

  • Bug fix (non-breaking change which fixes an issue)

Description:

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

  • KeyError when the optional datacontenttype attribute was absent — it was read via event["datacontenttype"]. The sibling to_structured() in the same file already guards this with if "datacontenttype" in attrs:.
  • AttributeError when an extension attribute had a non-string (e.g. int) value — value.encode("utf-8") was called directly. The newer core Kafka binding already stringifies with str(attr_value).encode(...).

This reads datacontenttype via .get() and stringifies attribute values before encoding, so to_binary() handles all valid events.


Pre-submission checklist:

  • I have read the CONTRIBUTING.md file.
  • I have signed off my commits using git commit --signoff.
  • I have added tests that prove my fix is effective (test_no_datacontenttype, test_non_string_extension_attribute — both fail before this change and pass after).
  • I have updated the documentation (CHANGELOG.md).
  • I have run pre-commit (ruff, ruff-format, mypy) and the Kafka test suite; all checks pass.
  • This pull request is ready to be reviewed.

The Kafka binary conversion to_binary() read the optional datacontenttype
attribute with event["datacontenttype"], raising KeyError for any event that
does not set it (datacontenttype is optional in the CloudEvents spec). It also
called .encode() directly on attribute values, raising AttributeError for
spec-legal non-string extension attributes (e.g. integers).

Read datacontenttype via .get() -- matching the sibling to_structured(), which
already guards this attribute -- and stringify attribute values before encoding,
matching the newer core Kafka binding. Add regression tests for both cases.

Signed-off-by: Md. Amdadul Bari Imad <amdadulbari@gmail.com>
@amdadulbari
amdadulbari force-pushed the fix/kafka-to-binary-optional-datacontenttype branch from d235ef3 to 4e081e9 Compare August 13, 2026 04:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant