msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

Allow to customize tag field position in array_like struct encoding

Open regnarg opened this issue 1 year ago • 0 comments

Description

When we create a tagged array_like struct, it is not possible to influence where the tag field is in the field order. This prevents using this feature to implement msgpack-rpc. In msgpack-rpc, the request is a 4-element array [type,msgid,method,params], where the type of params depends on the method. An intuitive way to implement this would be to create a single struct for each method, tagged by the 'method' field, and then use a Union of those to decode the request. However, this currently cannot be done as there is no way to put the tag on the third position.

In contrast to that, for JSON-RPC (where requests are dicts instead of arrays, this can be done):

    def _create_request_decoder(self):
        request_types = []
        for method_name, method_spec in self.methods.items():
            request_type = msgspec.defstruct(method_name, [
                ('jsonrpc', Literal["2.0"]),
                ('params', method_spec.params_type),
                ('id', str|int|None, None),
            ], tag=method_name, tag_field="method")
            request_types.append(request_type)
        return msgspec.json.Decoder(Union[*request_types])

regnarg avatar Sep 16 '24 13:09 regnarg