diff --git a/CHANGELOG.md b/CHANGELOG.md index aa654e2a..79659ae2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Added the JSON Batch format (`application/cloudevents-batch+json`) and HTTP batched + content mode: `BatchFormat`, `JSONFormat.write_batch`/`read_batch`, and + `http.to_batch`/`from_batch` with `to_events_batch`/`from_events_batch`. ([#334]) + ## [2.2.0] ### Changed @@ -368,3 +374,4 @@ CloudEvents v2 is a rewrite with ongoing development ([#271]) [#279]: https://github.com/cloudevents/sdk-python/pull/279 [#284]: https://github.com/cloudevents/sdk-python/pull/284 [#291]: https://github.com/cloudevents/sdk-python/pull/291 +[#334]: https://github.com/cloudevents/sdk-python/pull/334 diff --git a/src/cloudevents/core/bindings/http.py b/src/cloudevents/core/bindings/http.py index e5d1b2be..33ec20c9 100644 --- a/src/cloudevents/core/bindings/http.py +++ b/src/cloudevents/core/bindings/http.py @@ -12,6 +12,7 @@ # License for the specific language governing permissions and limitations # under the License. +from collections.abc import Sequence from dataclasses import dataclass from datetime import datetime from typing import Any, Final @@ -26,7 +27,7 @@ TIME_ATTR, get_event_factory_for_version, ) -from cloudevents.core.formats.base import Format +from cloudevents.core.formats.base import BatchFormat, Format from cloudevents.core.formats.json import JSONFormat from cloudevents.core.spec import SPECVERSION_V1_0 @@ -260,6 +261,30 @@ def from_structured( return event_format.read(event_factory, message.body) +def _reject_batch(message: HTTPMessage, event_format: Format) -> None: + """ + Raise a clear error when a batched mode message is parsed as a single event. + """ + if not isinstance(event_format, BatchFormat): + return + + content_type = next( + ( + value + for key, value in message.headers.items() + if key.lower() == CONTENT_TYPE_HEADER + ), + "", + ) + received = content_type.split(";")[0].strip().lower() + expected = event_format.get_batch_content_type().strip().lower() + if received == expected: + raise ValueError( + f"Content type '{received}' is the batch content type '{expected}'; " + "use from_batch() or from_events_batch() to parse batched CloudEvents" + ) + + def from_http( message: HTTPMessage, event_format: Format, @@ -299,13 +324,74 @@ def from_http( :param event_format: Format implementation for deserialization :param event_factory: Factory function to create CloudEvent instances (auto-detected if None) :return: CloudEvent instance + :raises ValueError: If the message is a batch (use from_batch instead) """ + _reject_batch(message, event_format) + if any(key.lower().startswith(CE_PREFIX) for key in message.headers.keys()): return from_binary(message, event_format, event_factory) return from_structured(message, event_format, event_factory) +def to_batch( + events: Sequence[BaseCloudEvent], event_format: BatchFormat +) -> HTTPMessage: + """ + Convert CloudEvents to HTTP batched content mode (HTTP binding section 3.3). + + The events are serialized into the HTTP body as a JSON batch, and the + Content-Type header is set to ``application/cloudevents-batch+json``. + + Example: + >>> from cloudevents.core.formats.json import JSONFormat + >>> + >>> message = to_batch([event1, event2], JSONFormat()) + >>> # message.headers = {"content-type": "application/cloudevents-batch+json"} + >>> # message.body = b'[{"type": ...}, {"type": ...}]' + + :param events: The CloudEvents to convert + :param event_format: Batch format implementation for serialization + :return: HTTPMessage with the JSON batch in body + :raises ValueError: If the events have different specversion values + """ + headers = {CONTENT_TYPE_HEADER: event_format.get_batch_content_type()} + + body = event_format.write_batch(events) + + return HTTPMessage(headers=headers, body=body) + + +def from_batch( + message: HTTPMessage, + event_format: BatchFormat, + event_factory: EventFactory | None = None, +) -> list[BaseCloudEvent]: + """ + Parse an HTTP batched content mode message to a list of CloudEvents. + + Deserializes the JSON batch in the HTTP body. If event_factory is not + provided, the version is detected for each event from its 'specversion'. + + Example: + >>> from cloudevents.core.formats.json import JSONFormat + >>> + >>> message = HTTPMessage( + ... headers={"content-type": "application/cloudevents-batch+json"}, + ... body=b'[{"type": "com.example.test", "source": "/test", ...}]' + ... ) + >>> events = from_batch(message, JSONFormat()) + + :param message: HTTPMessage to parse + :param event_format: Batch format implementation for deserialization + :param event_factory: Factory function to create CloudEvent instances. + If None, the version is detected for each event. + :return: The CloudEvents in the batch, in order + """ + events: list[BaseCloudEvent] = event_format.read_batch(event_factory, message.body) + return events + + def to_binary_event( event: BaseCloudEvent, event_format: Format | None = None, @@ -402,6 +488,48 @@ def from_structured_event( return from_structured(message, event_format, None) +def to_events_batch( + events: Sequence[BaseCloudEvent], + event_format: BatchFormat | None = None, +) -> HTTPMessage: + """ + Convenience wrapper for to_batch with JSON format as default. + + Example: + >>> from cloudevents.core.bindings import http + >>> message = http.to_events_batch([event1, event2]) + + :param events: The CloudEvents to convert + :param event_format: Batch format implementation (defaults to JSONFormat) + :return: HTTPMessage with the batch in body + """ + if event_format is None: + event_format = JSONFormat() + return to_batch(events, event_format) + + +def from_events_batch( + message: HTTPMessage, + event_format: BatchFormat | None = None, +) -> list[BaseCloudEvent]: + """ + Convenience wrapper for from_batch with JSON format and auto-detection. + + Auto-detects the CloudEvents version (v0.3 or v1.0) of the events. + + Example: + >>> from cloudevents.core.bindings import http + >>> events = http.from_events_batch(message) + + :param message: HTTPMessage to parse + :param event_format: Batch format implementation (defaults to JSONFormat) + :return: The CloudEvents in the batch, in order + """ + if event_format is None: + event_format = JSONFormat() + return from_batch(message, event_format, None) + + def from_http_event( message: HTTPMessage, event_format: Format | None = None, diff --git a/src/cloudevents/core/formats/base.py b/src/cloudevents/core/formats/base.py index ae2d9d0a..0ace690b 100644 --- a/src/cloudevents/core/formats/base.py +++ b/src/cloudevents/core/formats/base.py @@ -12,7 +12,8 @@ # License for the specific language governing permissions and limitations # under the License. -from typing import Any, Protocol +from collections.abc import Sequence +from typing import Any, Protocol, runtime_checkable from cloudevents.core.base import BaseCloudEvent, EventFactory @@ -88,3 +89,53 @@ def get_content_type(self) -> str: :return: Content type string for CloudEvents structured content mode """ ... + + +@runtime_checkable +class BatchFormat(Format, Protocol): + """ + Protocol for formats that also support batches of CloudEvents. + + It is separate from :class:`Format`, so a format can support single events + without implementing batches, and existing ``Format`` implementations keep + working. It is ``runtime_checkable``, so code that takes a ``Format`` can + detect batch support with ``isinstance``. + + All CloudEvents in a batch MUST have the same ``specversion`` (CloudEvents + spec, "Event batching"). + """ + + def write_batch(self, events: Sequence[BaseCloudEvent]) -> bytes: + """ + Serialize CloudEvents into the format's batch representation. + + :param events: The CloudEvents to serialize. + :return: The batch serialized as bytes. + :raises ValueError: If the events have different ``specversion`` values. + """ + ... + + def read_batch( + self, + event_factory: EventFactory | None, + data: str | bytes, + ) -> list[BaseCloudEvent]: + """ + Deserialize the format's batch representation into CloudEvents. + + :param event_factory: Factory to create CloudEvent instances, or None to + detect the version of each event. + :param data: The serialized batch as a string or bytes. + :return: The CloudEvents in the batch, in order. + :raises ValueError: If the batch is malformed, an event in it is invalid, + or the events have different ``specversion`` values. + """ + ... + + def get_batch_content_type(self) -> str: + """ + Get the Content-Type header value for batches. + + :return: Media type of the format's batch representation. + """ + ... diff --git a/src/cloudevents/core/formats/json.py b/src/cloudevents/core/formats/json.py index fa99cfee..08684b53 100644 --- a/src/cloudevents/core/formats/json.py +++ b/src/cloudevents/core/formats/json.py @@ -14,6 +14,7 @@ import base64 import re +from collections.abc import Sequence from datetime import datetime from json import JSONEncoder, dumps, loads from typing import Any, Final, Pattern @@ -21,7 +22,7 @@ from dateutil.parser import isoparse from cloudevents.core.base import BaseCloudEvent, EventFactory -from cloudevents.core.formats.base import Format +from cloudevents.core.formats.base import BatchFormat from cloudevents.core.spec import SPECVERSION_V0_3, SPECVERSION_V1_0 @@ -42,8 +43,18 @@ def default(self, obj: Any) -> Any: return super().default(obj) -class JSONFormat(Format): +def _check_same_specversion(events: Sequence[BaseCloudEvent]) -> None: + specversions = {str(event.get_attributes().get("specversion")) for event in events} + if len(specversions) > 1: + raise ValueError( + "All CloudEvents in a batch MUST have the same specversion, " + f"got {', '.join(sorted(specversions))}" + ) + + +class JSONFormat(BatchFormat): CONTENT_TYPE: Final[str] = "application/cloudevents+json" + BATCH_CONTENT_TYPE: Final[str] = "application/cloudevents-batch+json" DEFAULT_CONTENT_TYPE: Final[str] = "application/json" JSON_CONTENT_TYPE_PATTERN: Pattern[str] = re.compile( r"^(application|text)/([a-zA-Z0-9\-\.]+\+)?json(;.*)?$" @@ -72,12 +83,56 @@ def read( else: decoded_data = data + return self._read_event(event_factory, loads(decoded_data)) + + def read_batch( + self, + event_factory: EventFactory | None, + data: str | bytes, + ) -> list[BaseCloudEvent]: + """ + Read CloudEvents from a JSON batch: a JSON array of events in the JSON + event format (JSON format section 4). + + :param event_factory: A factory function to create CloudEvent instances. + If None, the version is detected for each event. + :param data: The JSON batch as a byte array or string. + :return: The CloudEvents in the batch, in order. + :raises ValueError: If the data is not a JSON array of JSON objects, an + event in it is invalid, or the events have + different specversion values. + """ + decoded_data = data.decode("utf-8") if isinstance(data, bytes) else data + raw_events = loads(decoded_data) + if not isinstance(raw_events, list): + raise ValueError( + f"A JSON batch must be a JSON array, got {type(raw_events).__name__}" + ) + + events: list[BaseCloudEvent] = [] + for index, raw_event in enumerate(raw_events): + if not isinstance(raw_event, dict): + raise ValueError( + f"JSON batch element at index {index} must be a JSON object, " + f"got {type(raw_event).__name__}" + ) + try: + events.append(self._read_event(event_factory, raw_event)) + except Exception as exc: + raise ValueError( + f"Invalid CloudEvent at index {index} of the JSON batch: {exc}" + ) from exc + + _check_same_specversion(events) + return events + + def _read_event( + self, event_factory: EventFactory | None, raw_event: dict[str, Any] + ) -> BaseCloudEvent: # JSON null attributes have the same meaning as omitted attributes. # Only filter the envelope; null values inside data are payload content. event_attributes = { - key: value - for key, value in loads(decoded_data).items() - if value is not None + key: value for key, value in raw_event.items() if value is not None } # Auto-detect version if factory not provided @@ -125,32 +180,50 @@ def write(self, event: BaseCloudEvent) -> bytes: :param event: The CloudEvent to write. :return: The CloudEvent as a JSON formatted byte array. """ + return dumps(self._event_to_dict(event), cls=_JSONEncoderWithDatetime).encode( + "utf-8" + ) + + def write_batch(self, events: Sequence[BaseCloudEvent]) -> bytes: + """ + Write CloudEvents as a JSON batch: a JSON array of events in the JSON + event format (JSON format section 4). + + :param events: The CloudEvents to write. + :return: The JSON batch as a byte array. + :raises ValueError: If the events have different specversion values. + """ + _check_same_specversion(events) + return dumps( + [self._event_to_dict(event) for event in events], + cls=_JSONEncoderWithDatetime, + ).encode("utf-8") + + def _event_to_dict(self, event: BaseCloudEvent) -> dict[str, Any]: event_data = event.get_data() event_dict: dict[str, Any] = dict(event.get_attributes()) specversion = event_dict.get("specversion", SPECVERSION_V1_0) - if event_data is not None: - if isinstance(event_data, (bytes, bytearray)): - # Handle binary data based on version - if specversion == SPECVERSION_V0_3: - # v0.3: Use datacontentencoding with base64-encoded data field - event_dict["datacontentencoding"] = "base64" - event_dict["data"] = base64.b64encode(event_data).decode("utf-8") - else: - # v1.0: Use data_base64 field - event_dict["data_base64"] = base64.b64encode(event_data).decode( - "utf-8" - ) + if event_data is None: + return event_dict + + if isinstance(event_data, (bytes, bytearray)): + # Handle binary data based on version + if specversion == SPECVERSION_V0_3: + # v0.3: Use datacontentencoding with base64-encoded data field + event_dict["datacontentencoding"] = "base64" + event_dict["data"] = base64.b64encode(event_data).decode("utf-8") else: - datacontenttype = event_dict.get( - "datacontenttype", self.DEFAULT_CONTENT_TYPE - ) - if re.match(JSONFormat.JSON_CONTENT_TYPE_PATTERN, datacontenttype): - event_dict["data"] = event_data - else: - event_dict["data"] = str(event_data) + # v1.0: Use data_base64 field + event_dict["data_base64"] = base64.b64encode(event_data).decode("utf-8") + return event_dict - return dumps(event_dict, cls=_JSONEncoderWithDatetime).encode("utf-8") + datacontenttype = event_dict.get("datacontenttype", self.DEFAULT_CONTENT_TYPE) + if re.match(JSONFormat.JSON_CONTENT_TYPE_PATTERN, datacontenttype): + event_dict["data"] = event_data + else: + event_dict["data"] = str(event_data) + return event_dict def write_data( self, @@ -236,3 +309,11 @@ def get_content_type(self) -> str: :return: Content type string for CloudEvents structured content mode """ return self.CONTENT_TYPE + + def get_batch_content_type(self) -> str: + """ + Get the Content-Type header value for batched content mode. + + :return: Content type string for a JSON batch of CloudEvents + """ + return self.BATCH_CONTENT_TYPE diff --git a/tests/test_core/test_bindings/test_http.py b/tests/test_core/test_bindings/test_http.py index cf46ba4d..92c2d330 100644 --- a/tests/test_core/test_bindings/test_http.py +++ b/tests/test_core/test_bindings/test_http.py @@ -13,20 +13,25 @@ # under the License. from datetime import datetime, timezone +from json import loads from typing import Any import pytest from cloudevents.core.bindings.http import ( HTTPMessage, + from_batch, from_binary, from_binary_event, + from_events_batch, from_http, from_http_event, from_structured, from_structured_event, + to_batch, to_binary, to_binary_event, + to_events_batch, to_structured, to_structured_event, ) @@ -1139,3 +1144,55 @@ def test_convenience_with_explicit_format_override() -> None: assert recovered.get_type() == event.get_type() assert recovered.get_data() == event.get_data() + + +def test_to_batch() -> None: + events = [create_event({"id": "1"}), create_event({"id": "2"}, data={"k": "v"})] + + message = to_batch(events, JSONFormat()) + + assert message.headers == {"content-type": "application/cloudevents-batch+json"} + assert [e["id"] for e in loads(message.body)] == ["1", "2"] + + +@pytest.mark.parametrize("event_factory", [CloudEvent, None]) +def test_from_batch_round_trip(event_factory: Any) -> None: + events = [create_event({"id": "1"}), create_event({"id": "2"}, data={"k": "v"})] + + result = from_batch(to_batch(events, JSONFormat()), JSONFormat(), event_factory) + + assert [e.get_id() for e in result] == ["1", "2"] + assert result[1].get_data() == {"k": "v"} + + +def test_from_batch_empty() -> None: + message = HTTPMessage( + headers={"content-type": "application/cloudevents-batch+json"}, body=b"[]" + ) + + assert from_batch(message, JSONFormat()) == [] + + +def test_events_batch_round_trip() -> None: + events = [create_event({"id": "1"}), create_event({"id": "2"}, data={"k": "v"})] + + message = to_events_batch(events) + result = from_events_batch(message) + + assert message.headers == {"content-type": "application/cloudevents-batch+json"} + assert [e.get_id() for e in result] == ["1", "2"] + assert result[1].get_data() == {"k": "v"} + + +@pytest.mark.parametrize( + "content_type", + [ + "application/cloudevents-batch+json", + "Application/CloudEvents-Batch+JSON; charset=utf-8", + ], +) +def test_from_http_rejects_batch(content_type: str) -> None: + message = HTTPMessage(headers={"Content-Type": content_type}, body=b"[]") + + with pytest.raises(ValueError, match="use from_batch"): + from_http(message, JSONFormat()) diff --git a/tests/test_core/test_format/test_json.py b/tests/test_core/test_format/test_json.py index 91abbdc0..1194b7d8 100644 --- a/tests/test_core/test_format/test_json.py +++ b/tests/test_core/test_format/test_json.py @@ -19,7 +19,10 @@ import pytest from cloudevents.core.base import BaseCloudEvent, EventFactory +from cloudevents.core.exceptions import CloudEventValidationError +from cloudevents.core.formats.base import BatchFormat from cloudevents.core.formats.json import JSONFormat +from cloudevents.core.v03.event import CloudEvent as CloudEventV03 from cloudevents.core.v1.event import CloudEvent @@ -389,3 +392,127 @@ def factory(attributes: dict[str, Any], data: Any) -> BaseCloudEvent: assert "subject" not in received assert "extension" not in received assert event.get_data() is None + + +def _batch_events() -> list[CloudEvent]: + return [ + CloudEvent( + attributes={ + "type": "com.example.json", + "source": "/json", + "id": "1", + "datacontenttype": "application/json", + }, + data={"key": "value"}, + ), + CloudEvent( + attributes={ + "type": "com.example.binary", + "source": "/binary", + "id": "2", + "datacontenttype": "application/octet-stream", + }, + data=b"\x00\x01", + ), + CloudEvent( + attributes={"type": "com.example.empty", "source": "/empty", "id": "3"}, + data=None, + ), + ] + + +def test_write_batch_is_array_of_json_events() -> None: + events = _batch_events() + + batch = loads(JSONFormat().write_batch(events)) + + assert batch == [loads(JSONFormat().write(event)) for event in events] + assert batch[1]["data_base64"] == "AAE=" + + +@pytest.mark.parametrize("event_factory", [CloudEvent, None]) +def test_read_batch_round_trip(event_factory: EventFactory | None) -> None: + events = _batch_events() + + result = JSONFormat().read_batch(event_factory, JSONFormat().write_batch(events)) + + assert [e.get_attributes() for e in result] == [e.get_attributes() for e in events] + assert [e.get_data() for e in result] == [e.get_data() for e in events] + + +def test_read_batch_detects_version() -> None: + data = dumps( + [ + {"specversion": "0.3", "type": "t", "source": "/s", "id": "1"}, + {"specversion": "0.3", "type": "t", "source": "/s", "id": "2"}, + ] + ) + + result = JSONFormat().read_batch(None, data) + + assert all(isinstance(event, CloudEventV03) for event in result) + assert [e.get_id() for e in result] == ["1", "2"] + + +def test_read_batch_rejects_mixed_specversions() -> None: + data = dumps( + [ + {"specversion": "1.0", "type": "t", "source": "/s", "id": "1"}, + {"specversion": "0.3", "type": "t", "source": "/s", "id": "2"}, + ] + ) + + with pytest.raises(ValueError, match="same specversion, got 0.3, 1.0"): + JSONFormat().read_batch(None, data) + + +def test_write_batch_rejects_mixed_specversions() -> None: + events = [ + CloudEvent(attributes={"type": "t", "source": "/s", "id": "1"}), + CloudEventV03( + attributes={"specversion": "0.3", "type": "t", "source": "/s", "id": "2"} + ), + ] + + with pytest.raises(ValueError, match="same specversion"): + JSONFormat().write_batch(events) + + +def test_read_batch_reports_invalid_event_index() -> None: + data = dumps( + [ + {"specversion": "1.0", "type": "t", "source": "/s", "id": "1"}, + {"specversion": "1.0", "source": "/s", "id": "2"}, + ] + ) + + with pytest.raises(ValueError, match="index 1 of the JSON batch") as exc_info: + JSONFormat().read_batch(None, data) + + assert isinstance(exc_info.value.__cause__, CloudEventValidationError) + + +def test_json_format_is_batch_format() -> None: + assert isinstance(JSONFormat(), BatchFormat) + + +def test_empty_batch() -> None: + assert JSONFormat().write_batch([]) == b"[]" + assert JSONFormat().read_batch(None, b"[]") == [] + + +@pytest.mark.parametrize( + "data, message", + [ + (b'{"type": "t", "source": "/s", "id": "1"}', "JSON array, got dict"), + (b"[1]", "index 0 must be a JSON object, got int"), + (b'["event"]', "index 0 must be a JSON object, got str"), + ], +) +def test_read_batch_rejects_non_array_of_objects(data: bytes, message: str) -> None: + with pytest.raises(ValueError, match=message): + JSONFormat().read_batch(None, data) + + +def test_batch_content_type() -> None: + assert JSONFormat().get_batch_content_type() == "application/cloudevents-batch+json"