Skip to content

declearn.communication.utils.verify_server_message_validity

Verify that a received serialized message matches expected type.

  • If the received message matches expected type, deserialize it.
  • If the recevied message is an unexpected Error message, raise.
  • If it belongs to any other type, send an Error to the server, then raise.

Parameters:

Name Type Description Default
netwk NetworkClient

NetworkClient endpoint, from which the processed message was received.

required
received SerializedMessage

Received SerializedMessage to type-check and deserialize.

required
expected Type[MessageT]

Expected Message subtype. Any subclass will be considered as valid.

required

Returns:

Name Type Description
message MessageT

Deserialized Message from received, with expected type.

Raises:

Type Description
ErrorMessageException

If received wraps an unexpected Error message.

MessageTypeException

If received wrapped message does not match expected type.

Source code in declearn/communication/utils/_parse.py
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
async def verify_server_message_validity(
    netwk: NetworkClient,
    received: SerializedMessage,
    expected: Type[MessageT],
) -> MessageT:
    """Verify that a received serialized message matches expected type.

    - If the received message matches expected type, deserialize it.
    - If the recevied message is an unexpected `Error` message, raise.
    - If it belongs to any other type, send an `Error` to the server,
      then raise.

    Parameters
    ----------
    netwk:
        `NetworkClient` endpoint, from which the processed message
        was received.
    received:
        Received `SerializedMessage` to type-check and deserialize.
    expected:
        Expected `Message` subtype. Any subclass will be considered
        as valid.

    Returns
    -------
    message:
        Deserialized `Message` from `received`, with `expected` type.

    Raises
    ------
    ErrorMessageException
        If `received` wraps an unexpected `Error` message.
    MessageTypeException
        If `received` wrapped message does not match `expected` type.
    """
    # If a proper message is received, deserialize and return it.
    if issubclass(received.message_cls, expected):
        return received.deserialize()
    # When an Error is received, merely raise using its content.
    error = f"Expected a '{expected}' message"
    if issubclass(received.message_cls, Error):
        msg = received.deserialize()
        error = f"{error}, received an Error message: '{msg.message}'."
        raise ErrorMessageException(error)
    # Otherwise, send an Error to the server, then raise.
    error = f"{error}, got a '{received.message_cls}'."
    await netwk.send_message(Error(error))
    raise MessageTypeException(error)