Skip to content
Merged
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
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ keywords = [
]
dependencies = [
"ruff>=0.6.8",
"python-dateutil>=2.8.2",
]

[project.urls]
Expand All @@ -53,6 +54,7 @@ dev-dependencies = [
"flake8-print>=5.0.0",
"pre-commit>=3.8.0",
"pytest-cov>=5.0.0",
"types-python-dateutil>=2.9.0.20241003",
]

[tool.uv.pip]
Expand Down
130 changes: 130 additions & 0 deletions src/cloudevents/core/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# Copyright 2018-Present The CloudEvents Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.


from datetime import datetime
from typing import Any, Optional, Protocol, Union


class BaseCloudEvent(Protocol):
"""
The CloudEvent Python wrapper contract exposing generically-available
properties and APIs.

Implementations might handle fields and have other APIs exposed but are
obliged to follow this contract.
"""

def __init__(
self, attributes: dict[str, Any], data: Optional[Union[dict, str, bytes]] = None
) -> None:
"""
Create a new CloudEvent instance.

:param attributes: The attributes of the CloudEvent instance.
:param data: The payload of the CloudEvent instance.

:raises ValueError: If any of the required attributes are missing or have invalid values.
:raises TypeError: If any of the attributes have invalid types.
"""
...

def get_id(self) -> str:
"""
Retrieve the ID of the event.

:return: The ID of the event.
"""
...

def get_source(self) -> str:
"""
Retrieve the source of the event.

:return: The source of the event.
"""
...

def get_type(self) -> str:
"""
Retrieve the type of the event.

:return: The type of the event.
"""
...

def get_specversion(self) -> str:
"""
Retrieve the specversion of the event.

:return: The specversion of the event.
"""
...

def get_datacontenttype(self) -> Optional[str]:
"""
Retrieve the datacontenttype of the event.

:return: The datacontenttype of the event.
"""
...

def get_dataschema(self) -> Optional[str]:
"""
Retrieve the dataschema of the event.

:return: The dataschema of the event.
"""
...

def get_subject(self) -> Optional[str]:
"""
Retrieve the subject of the event.

:return: The subject of the event.
"""
...

def get_time(self) -> Optional[datetime]:
"""
Retrieve the time of the event.

:return: The time of the event.
"""
...

def get_extension(self, extension_name: str) -> Any:
"""
Retrieve an extension attribute of the event.

:param extension_name: The name of the extension attribute.
:return: The value of the extension attribute.
"""
...

def get_data(self) -> Optional[Union[dict, str, bytes]]:
"""
Retrieve data of the event.

:return: The data of the event.
"""
...

def get_attributes(self) -> dict[str, Any]:
"""
Retrieve all attributes of the event.

:return: The attributes of the event.
"""
...
13 changes: 13 additions & 0 deletions src/cloudevents/core/formats/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Copyright 2018-Present The CloudEvents Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
58 changes: 58 additions & 0 deletions src/cloudevents/core/formats/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Copyright 2018-Present The CloudEvents Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.


from typing import Callable, Optional, Protocol, Union

from cloudevents.core.base import BaseCloudEvent


class Format(Protocol):
"""
Protocol defining the contract for CloudEvent format implementations.

Format implementations are responsible for serializing and deserializing CloudEvents
to and from specific wire formats (e.g., JSON, Avro, Protobuf). Each format must
implement both read and write operations to convert between CloudEvent objects and
their byte representations according to the CloudEvents specification.
"""

def read(
self,
event_factory: Callable[
[dict, Optional[Union[dict, str, bytes]]], BaseCloudEvent
],
data: Union[str, bytes],
) -> BaseCloudEvent:
"""
Deserialize a CloudEvent from its wire format representation.

:param event_factory: A factory function that creates CloudEvent instances from
attributes and data. The factory should accept a dictionary of attributes and
optional event data (dict, str, or bytes).
:param data: The serialized CloudEvent data as a string or bytes.
:return: A CloudEvent instance constructed from the deserialized data.
:raises ValueError: If the data cannot be parsed or is invalid according to the format.
"""
...

def write(self, event: BaseCloudEvent) -> bytes:
"""
Serialize a CloudEvent to its wire format representation.

:param event: The CloudEvent instance to serialize.
:return: The CloudEvent serialized as bytes in the format's wire representation.
:raises ValueError: If the event cannot be serialized according to the format.
"""
...
104 changes: 104 additions & 0 deletions src/cloudevents/core/formats/json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# Copyright 2018-Present The CloudEvents Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.


import base64
import re
from datetime import datetime
from json import JSONEncoder, dumps, loads
from typing import Any, Callable, Final, Optional, Pattern, Union

from dateutil.parser import isoparse # type: ignore[import-untyped]

from cloudevents.core.base import BaseCloudEvent
from cloudevents.core.formats.base import Format


class _JSONEncoderWithDatetime(JSONEncoder):
"""
Custom JSON encoder to handle datetime objects in the format required by the CloudEvents spec.
"""

def default(self, obj: Any) -> Any:
if isinstance(obj, datetime):
dt = obj.isoformat()
# 'Z' denotes a UTC offset of 00:00 see
# https://www.rfc-editor.org/rfc/rfc3339#section-2
if dt.endswith("+00:00"):
dt = dt.removesuffix("+00:00") + "Z"
return dt

return super().default(obj)


class JSONFormat(Format):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do you envision usage of this class by the end users?

Copy link
Author

@PlugaruT PlugaruT Nov 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Technically, there should be no need for this class to be used often, unless someone knows what they are doing.
Since for each binding, we would have to implement both structured and binary modes, this format class would be useful when using structured mode, since the entire CloudEvent class is serialized into JSON/Avro and send as a single message. This format would be injected into that "structured mode CE writer" implementation. Something like

to_structured(event, format):
...

from_structured(data, format):
...

I can't see this class being used for binary mode tho, correct me if I'm wrong please. But given that attributes are sent as message metadata, it can only be JSON format by default, no?

Anyway, I think it's worth having a way for having CE -> bytes and bytes -> CE for each supported format as per the specs and let engineers do manipulations as they see fit.

CONTENT_TYPE: Final[str] = "application/cloudevents+json"
JSON_CONTENT_TYPE_PATTERN: Pattern[str] = re.compile(
r"^(application|text)/([a-zA-Z0-9\-\.]+\+)?json(;.*)?$"
)

def read(
self,
event_factory: Callable[
[dict, Optional[Union[dict, str, bytes]]], BaseCloudEvent
],
data: Union[str, bytes],
) -> BaseCloudEvent:
"""
Read a CloudEvent from a JSON formatted byte string.

:param event_factory: A factory function to create CloudEvent instances.
:param data: The JSON formatted byte array.
:return: The CloudEvent instance.
"""
decoded_data: str
if isinstance(data, bytes):
decoded_data = data.decode("utf-8")
else:
decoded_data = data

event_attributes = loads(decoded_data)

if "time" in event_attributes:
event_attributes["time"] = isoparse(event_attributes["time"])

event_data: Union[dict, str, bytes, None] = event_attributes.pop("data", None)
if event_data is None:
event_data_base64 = event_attributes.pop("data_base64", None)
if event_data_base64 is not None:
event_data = base64.b64decode(event_data_base64)

return event_factory(event_attributes, event_data)

def write(self, event: BaseCloudEvent) -> bytes:
"""
Write a CloudEvent to a JSON formatted byte string.

:param event: The CloudEvent to write.
:return: The CloudEvent as a JSON formatted byte array.
"""
event_data = event.get_data()
event_dict: dict[str, Any] = dict(event.get_attributes())

if event_data is not None:
if isinstance(event_data, (bytes, bytearray)):
event_dict["data_base64"] = base64.b64encode(event_data).decode("utf-8")
else:
datacontenttype = event_dict.get("datacontenttype", "application/json")
if re.match(JSONFormat.JSON_CONTENT_TYPE_PATTERN, datacontenttype):
event_dict["data"] = event_data
else:
event_dict["data"] = str(event_data)

return dumps(event_dict, cls=_JSONEncoderWithDatetime).encode("utf-8")
Loading
Loading