Skip to content

feat: implementation for JSON format. #245

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: v2
Choose a base branch
from
Draft
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
45 changes: 45 additions & 0 deletions src/cloudevents/core/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# 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):
def __init__(
self, attributes: dict[str, Any], data: Optional[Union[dict, str, bytes]] = None
) -> None: ...

def get_id(self) -> str: ...

def get_source(self) -> str: ...

def get_type(self) -> str: ...

def get_specversion(self) -> str: ...

def get_datacontenttype(self) -> Optional[str]: ...

def get_dataschema(self) -> Optional[str]: ...

def get_subject(self) -> Optional[str]: ...

def get_time(self) -> Optional[datetime]: ...

def get_extension(self, extension_name: str) -> Any: ...

def get_data(self) -> Optional[Union[dict, str, bytes]]: ...

def get_attributes(self) -> dict[str, Any]: ...
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.
24 changes: 24 additions & 0 deletions src/cloudevents/core/formats/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# 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 Protocol, Union

from cloudevents.core.base import BaseCloudEvent


class Format(Protocol):
def read(self, data: Union[str, bytes]) -> BaseCloudEvent: ...

def write(self, event: BaseCloudEvent) -> bytes: ...
101 changes: 101 additions & 0 deletions src/cloudevents/core/formats/json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# 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, Final, Pattern, Type, TypeVar, Union

from dateutil.parser import isoparse

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

T = TypeVar("T", bound=BaseCloudEvent)


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-Z]+\\+)?json(;.*)*$"
)

def read(self, event_klass: Type[T], data: Union[str, bytes]) -> T:
"""
Read a CloudEvent from a JSON formatted byte string.

:param data: The JSON formatted byte array.
:return: The CloudEvent instance.
"""
if isinstance(data, bytes):
decoded_data: str = 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[str, bytes] = event_attributes.get("data")
if event_data is None:
event_data_base64 = event_attributes.get("data_base64")
if event_data_base64 is not None:
event_data = base64.b64decode(event_data_base64)

# disable mypy due to https://github.com/python/mypy/issues/9003
return event_klass(event_attributes, event_data) # type: ignore

def write(self, event: T) -> 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", JSONFormat.CONTENT_TYPE
)
if re.match(JSONFormat.JSON_CONTENT_TYPE_PATTERN, datacontenttype):
event_dict["data"] = dumps(event_data)
else:
event_dict["data"] = str(event_data)

return dumps(event_dict, cls=_JSONEncoderWithDatetime).encode("utf-8")
21 changes: 16 additions & 5 deletions src/cloudevents/core/v1/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
import re
from collections import defaultdict
from datetime import datetime
from typing import Any, Final, Optional
from typing import Any, Final, Optional, Union

from cloudevents.core.base import BaseCloudEvent
from cloudevents.core.v1.exceptions import (
BaseCloudEventException,
CloudEventValidationError,
Expand All @@ -35,7 +36,7 @@
]


class CloudEvent:
class CloudEvent(BaseCloudEvent):
"""
The CloudEvent Python wrapper contract exposing generically-available
properties and APIs.
Expand All @@ -44,7 +45,9 @@ class CloudEvent:
obliged to follow this contract.
"""

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

Expand All @@ -56,7 +59,7 @@ def __init__(self, attributes: dict[str, Any], data: Optional[dict] = None) -> N
"""
self._validate_attribute(attributes=attributes)
self._attributes: dict[str, Any] = attributes
self._data: Optional[dict] = data
self._data: Optional[Union[dict, str, bytes]] = data

@staticmethod
def _validate_attribute(attributes: dict[str, Any]) -> None:
Expand Down Expand Up @@ -315,10 +318,18 @@ def get_extension(self, extension_name: str) -> Any:
"""
return self._attributes.get(extension_name)

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

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

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

:return: The attributes of the event.
"""
return self._attributes
13 changes: 13 additions & 0 deletions tests/test_core/test_format/__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.
Loading