Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
130 changes: 129 additions & 1 deletion src/cloudevents/core/bindings/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
53 changes: 52 additions & 1 deletion src/cloudevents/core/formats/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.
"""
...
Loading