-
Notifications
You must be signed in to change notification settings - Fork 61
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
fa0ec99
feat: draft implementation for JSON format. Only CloudEvent serializa…
PlugaruT 8aeed15
Implement read method
PlugaruT adfee8f
small fix to read method
PlugaruT a893fb3
wrap up JSON format completely and make it compliant with the spec
PlugaruT fbcfba9
add type annotations
PlugaruT 3978caf
chore(docs): move docstrings from implementation to protocol class
PlugaruT 34acf65
chore(docs): document Format protocol
PlugaruT File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
| """ | ||
| ... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
| """ | ||
| ... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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): | ||
| 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") | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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
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 -> bytesandbytes -> CEfor each supported format as per the specs and let engineers do manipulations as they see fit.