-
Notifications
You must be signed in to change notification settings - Fork 9
feat: add msgspec support #154
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| # | ||
| # Copyright (c) 2023-2025 - Restate Software, Inc., Restate GmbH | ||
| # | ||
| # This file is part of the Restate SDK for Python, | ||
| # which is released under the MIT license. | ||
| # | ||
| # You can find a copy of the license in file LICENSE in the root | ||
| # directory of this repository or package, or at | ||
| # https://github.com/restatedev/sdk-typescript/blob/main/LICENSE | ||
| # | ||
| """msgspec_greeter.py - Example using msgspec.Struct with Restate""" | ||
| # pylint: disable=C0116 | ||
| # pylint: disable=W0613 | ||
| # pylint: disable=C0115 | ||
| # pylint: disable=R0903 | ||
|
|
||
| import msgspec | ||
| from restate import Service, Context | ||
|
|
||
|
|
||
| # models | ||
| class GreetingRequest(msgspec.Struct): | ||
| name: str | ||
|
|
||
|
|
||
| class Greeting(msgspec.Struct): | ||
| message: str | ||
|
|
||
|
|
||
| # service | ||
|
|
||
| msgspec_greeter = Service("msgspec_greeter") | ||
|
|
||
|
|
||
| @msgspec_greeter.handler() | ||
| async def greet(ctx: Context, req: GreetingRequest) -> Greeting: | ||
| return Greeting(message=f"Hello {req.name}!") | ||
|
|
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
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 |
|---|---|---|
|
|
@@ -74,7 +74,24 @@ def _from_dict(data_class: typing.Any, data: typing.Any) -> typing.Any: # pylin | |
| return _to_dict, _from_dict | ||
|
|
||
|
|
||
| def try_import_msgspec_struct(): | ||
| """ | ||
| Try to import Struct from msgspec. | ||
| """ | ||
| try: | ||
| from msgspec import Struct # type: ignore # pylint: disable=import-outside-toplevel | ||
|
|
||
| return Struct | ||
| except ImportError: | ||
|
|
||
| class Dummy: # pylint: disable=too-few-public-methods | ||
| """a dummy class to use when msgspec is not available""" | ||
|
|
||
| return Dummy | ||
|
|
||
|
|
||
| PydanticBaseModel = try_import_pydantic_base_model() | ||
| MsgspecStruct = try_import_msgspec_struct() | ||
| # pylint: disable=C0103 | ||
| DaciteToDict, DaciteFromDict = try_import_from_dacite() | ||
|
|
||
|
|
@@ -97,6 +114,17 @@ def is_pydantic(annotation) -> bool: | |
| return False | ||
|
|
||
|
|
||
| def is_msgspec(annotation) -> bool: | ||
| """ | ||
| Check if an object is a msgspec Struct. | ||
| """ | ||
| try: | ||
| return issubclass(annotation, MsgspecStruct) | ||
| except TypeError: | ||
| # annotation is not a class or a type | ||
| return False | ||
|
|
||
|
|
||
| class Serde(typing.Generic[T], abc.ABC): | ||
| """serializer/deserializer interface.""" | ||
|
|
||
|
|
@@ -227,6 +255,10 @@ def deserialize(self, buf: bytes) -> typing.Optional[I]: | |
| """ | ||
| if not buf: | ||
| return None | ||
| if is_msgspec(self.type_hint): | ||
| import msgspec.json # type: ignore # pylint: disable=import-outside-toplevel | ||
|
|
||
| return msgspec.json.decode(buf, type=self.type_hint) | ||
| if is_pydantic(self.type_hint): | ||
| return self.type_hint.model_validate_json(buf) # type: ignore | ||
| if is_dataclass(self.type_hint): | ||
|
|
@@ -237,7 +269,7 @@ def deserialize(self, buf: bytes) -> typing.Optional[I]: | |
| def serialize(self, obj: typing.Optional[I]) -> bytes: | ||
| """ | ||
| Serializes a Python object into a byte array. | ||
| If the object is a Pydantic BaseModel, uses its model_dump_json method. | ||
| If the object is a msgspec Struct or Pydantic BaseModel, uses their respective methods. | ||
|
|
||
| Args: | ||
| obj (Optional[I]): The Python object to serialize. | ||
|
|
@@ -247,6 +279,10 @@ def serialize(self, obj: typing.Optional[I]) -> bytes: | |
| """ | ||
| if obj is None: | ||
| return bytes() | ||
| if is_msgspec(self.type_hint): | ||
| import msgspec.json # type: ignore # pylint: disable=import-outside-toplevel | ||
|
|
||
| return msgspec.json.encode(obj) | ||
| if is_pydantic(self.type_hint): | ||
| return obj.model_dump_json().encode("utf-8") # type: ignore[attr-defined] | ||
| if is_dataclass(obj): | ||
|
|
@@ -291,3 +327,44 @@ def serialize(self, obj: typing.Optional[I]) -> bytes: | |
| return bytes() | ||
| json_str = obj.model_dump_json() # type: ignore[attr-defined] | ||
| return json_str.encode("utf-8") | ||
|
|
||
|
|
||
| class MsgspecJsonSerde(Serde[I]): | ||
| """ | ||
| Serde for msgspec Structs to/from JSON | ||
| """ | ||
|
|
||
| def __init__(self, model): | ||
| self.model = model | ||
|
|
||
| def deserialize(self, buf: bytes) -> typing.Optional[I]: | ||
| """ | ||
| Deserializes a bytearray to a msgspec Struct. | ||
|
|
||
| Args: | ||
| buf (bytearray): The bytearray to deserialize. | ||
|
|
||
| Returns: | ||
| typing.Optional[I]: The deserialized msgspec Struct. | ||
| """ | ||
| if not buf: | ||
| return None | ||
| import msgspec.json # type: ignore # pylint: disable=import-outside-toplevel | ||
|
Contributor
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. Let's avoid these inline imports. |
||
|
|
||
| return msgspec.json.decode(buf, type=self.model) | ||
|
|
||
| def serialize(self, obj: typing.Optional[I]) -> bytes: | ||
| """ | ||
| Serializes a msgspec Struct to a bytearray. | ||
|
|
||
| Args: | ||
| obj (I): The msgspec Struct to serialize. | ||
|
|
||
| Returns: | ||
| bytearray: The serialized bytearray. | ||
| """ | ||
| if obj is None: | ||
| return bytes() | ||
| import msgspec.json # type: ignore # pylint: disable=import-outside-toplevel | ||
|
|
||
| return msgspec.json.encode(obj) | ||
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.
Let's avoid this inner import. I'd rather to have all the conditional imports captured elsewhere.