-
Notifications
You must be signed in to change notification settings - Fork 58
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
PlugaruT
wants to merge
2
commits into
cloudevents:v2
Choose a base branch
from
PlugaruT:tudor/json-format
base: v2
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
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,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]: ... |
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,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: ... |
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,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): | ||
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") |
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,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. |
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?
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 -> bytes
andbytes -> CE
for each supported format as per the specs and let engineers do manipulations as they see fit.