-
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
Changes from 5 commits
fa0ec99
8aeed15
adfee8f
a893fb3
fbcfba9
3978caf
34acf65
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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]: ... |
| 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. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| # 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): | ||
| def read( | ||
| self, | ||
| event_factory: Callable[ | ||
| [dict, Optional[Union[dict, str, bytes]]], BaseCloudEvent | ||
| ], | ||
| data: Union[str, bytes], | ||
| ) -> BaseCloudEvent: ... | ||
|
|
||
| def write(self, event: BaseCloudEvent) -> bytes: ... | ||
| 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): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. how do you envision usage of this class by the end users?
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. 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 |
||
| 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") | ||
xSAVIKx marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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. |
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.
can you please move/add some docs here?
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.
done