diff --git a/src/cloudevents/core/bindings/kafka.py b/src/cloudevents/core/bindings/kafka.py index 920b1472..f0e5461f 100644 --- a/src/cloudevents/core/bindings/kafka.py +++ b/src/cloudevents/core/bindings/kafka.py @@ -307,7 +307,8 @@ def from_kafka( Auto-detects CloudEvents version and uses appropriate event factory if not provided. Automatically detects whether the message uses binary or structured content mode: - - If any ce_ prefixed headers are present → binary mode + - If content-type matches the supplied event format → structured mode + - Otherwise, if any ce_ prefixed headers are present → binary mode - Otherwise → structured mode This function provides a convenient way to handle both content modes without @@ -338,6 +339,14 @@ def from_kafka( :param event_factory: Factory function to create CloudEvent instances (auto-detected if None) :return: CloudEvent instance """ + # Structured messages may include ce_ headers alongside the envelope. + for name, value in message.headers.items(): + if name.lower() == CONTENT_TYPE_HEADER: + media_type = value.partition(b";")[0].strip().lower() + format_type = event_format.get_content_type().partition(";")[0].strip() + if media_type == format_type.lower().encode("utf-8"): + return from_structured(message, event_format, event_factory) + for header_name in message.headers.keys(): if header_name.lower().startswith(CE_PREFIX): return from_binary(message, event_format, event_factory) diff --git a/tests/test_core/test_bindings/test_kafka.py b/tests/test_core/test_bindings/test_kafka.py index 35f2115b..8462fb56 100644 --- a/tests/test_core/test_bindings/test_kafka.py +++ b/tests/test_core/test_bindings/test_kafka.py @@ -501,6 +501,7 @@ def test_from_kafka_detects_binary_mode() -> None: """Test from_kafka detects binary mode (ce_ headers present)""" message = KafkaMessage( headers={ + "content-type": b"application/json", "ce_type": b"com.example.test", "ce_source": b"/test", "ce_id": b"123", @@ -526,6 +527,34 @@ def test_from_kafka_detects_structured_mode() -> None: assert event.get_type() == "com.example.test" +@pytest.mark.parametrize( + "headers", + [ + {"ce_subject": b"orders", "content-type": b"application/cloudevents+json"}, + { + "ce_specversion": b"1.0", + "ce_source": b"/test", + "ce_type": b"com.example.test", + "ce_id": b"123", + "Content-Type": b"Application/CloudEvents+JSON; charset=utf-8", + }, + ], +) +def test_from_kafka_structured_with_metadata_headers(headers: dict[str, bytes]) -> None: + message = KafkaMessage( + headers=headers, + key=None, + value=( + b'{"specversion":"1.0","source":"/test","type":"com.example.test",' + b'"id":"123","subject":"orders","data":{"amount":5}}' + ), + ) + + event = from_kafka(message, JSONFormat(), CloudEvent) + + assert event.get_data() == {"amount": 5} + + def test_from_kafka_case_insensitive_detection() -> None: """Test from_kafka detection is case-insensitive""" message = KafkaMessage(