Bases: Generic[MessageT]
Container for serialized Message instances.
This class provides an intermediate structure to wrap received
serialized messages, that enables parsing their exact type and
therefore running any kind of filtering or validation prior to
actually de-serializing the message's content (which may cause
non-trivial time and memory usage, assignment of data on a GPU,
etc.).
Usage:
>>> proto = SerializedMessage.from_message_string(string)
>>> assert issubclass(proto.message_cls, ExpectedMessageType)
>>> message = proto.deserialize() # type: `proto.message_cls`
Source code in declearn/messaging/_api.py
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166 | class SerializedMessage(Generic[MessageT]):
"""Container for serialized Message instances.
This class provides an intermediate structure to wrap received
serialized messages, that enables parsing their exact type and
therefore running any kind of filtering or validation prior to
actually de-serializing the message's content (which may cause
non-trivial time and memory usage, assignment of data on a GPU,
etc.).
Usage:
```
>>> proto = SerializedMessage.from_message_string(string)
>>> assert issubclass(proto.message_cls, ExpectedMessageType)
>>> message = proto.deserialize() # type: `proto.message_cls`
```
"""
def __init__(
self,
message_cls: Type[MessageT],
string_data: str,
) -> None:
"""Instantiate the serialized message container."""
self.message_cls = message_cls
self.string_data = string_data
@property
def typekey(self) -> str:
"""Typekey string associated with this message."""
return self.message_cls.typekey
def deserialize(
self,
) -> MessageT:
"""Deserialize this message into a 'self.message_cls' instance."""
try:
data = json.loads(self.string_data, object_hook=json_unpack)
except json.JSONDecodeError as exc:
raise ValueError(
f"Failed to decode JSON dump of '{self.message_cls}' message."
) from exc
return self.message_cls.from_kwargs(**data)
@classmethod
def from_message_string(
cls,
string: str,
) -> Self:
"""Parse a serialized message string into a 'SerializedMessage'."""
try:
typekey, string_data = string.split("\n", 1)
except ValueError as exc:
raise TypeError(
"Input string appears not to be a Message dump."
) from exc
try:
message_cls = access_registered(typekey, group="Message")
except KeyError as exc:
raise KeyError(
f"No registered Message type matches typekey '{typekey}'."
) from exc
if not issubclass(message_cls, Message): # pragma: no cover
raise RuntimeError(
f"Retrieved a non-Message class '{message_cls}' from 'Message'"
" type registry. This indicates undue tempering."
)
return cls(
message_cls=message_cls, # type: ignore
string_data=string_data,
)
|
typekey: str
property
Typekey string associated with this message.
__init__(message_cls, string_data)
Instantiate the serialized message container.
Source code in declearn/messaging/_api.py
114
115
116
117
118
119
120
121 | def __init__(
self,
message_cls: Type[MessageT],
string_data: str,
) -> None:
"""Instantiate the serialized message container."""
self.message_cls = message_cls
self.string_data = string_data
|
deserialize()
Deserialize this message into a 'self.message_cls' instance.
Source code in declearn/messaging/_api.py
128
129
130
131
132
133
134
135
136
137
138 | def deserialize(
self,
) -> MessageT:
"""Deserialize this message into a 'self.message_cls' instance."""
try:
data = json.loads(self.string_data, object_hook=json_unpack)
except json.JSONDecodeError as exc:
raise ValueError(
f"Failed to decode JSON dump of '{self.message_cls}' message."
) from exc
return self.message_cls.from_kwargs(**data)
|
from_message_string(string)
classmethod
Parse a serialized message string into a 'SerializedMessage'.
Source code in declearn/messaging/_api.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166 | @classmethod
def from_message_string(
cls,
string: str,
) -> Self:
"""Parse a serialized message string into a 'SerializedMessage'."""
try:
typekey, string_data = string.split("\n", 1)
except ValueError as exc:
raise TypeError(
"Input string appears not to be a Message dump."
) from exc
try:
message_cls = access_registered(typekey, group="Message")
except KeyError as exc:
raise KeyError(
f"No registered Message type matches typekey '{typekey}'."
) from exc
if not issubclass(message_cls, Message): # pragma: no cover
raise RuntimeError(
f"Retrieved a non-Message class '{message_cls}' from 'Message'"
" type registry. This indicates undue tempering."
)
return cls(
message_cls=message_cls, # type: ignore
string_data=string_data,
)
|