pymeasure / pyleco

Python implementation of the Laboratory Experiment COntrol (LECO) protocol
MIT License
9 stars 3 forks source link

MessageHandler should allow batch handling #56

Closed BenediktBurger closed 8 months ago

BenediktBurger commented 8 months ago

Currently the MessageHandler only handles a single request/response in handle_json_message (identified as a dict).

According to https://www.jsonrpc.org/specification (6 Batch), a batch (identified as a list of dicts) should be possible as well. All members of the list are either requests or responses, so only the type of the first one has to be checked.

The openrpc server is able to handle it.

Sketch for get_json_content_type, to be used in handle_json_message to distinguish types:

class JsonContentType(Enum):
    """Type of the JSON content."""

    REQUEST = "request"
    RESULT = "result"
    INVALID = "invalid"

def get_json_content_type(message: Message) -> JsonContentType:
    try:
        data = message.data
    except JSONDecodeError:
        return JsonContentType.INVALID
    if isinstance(data, list):
        try:
            data = data[0]
        except IndexError:
            return JsonContentType.INVALID
    if isinstance(data, dict):
        if "method" in data.keys():
           return JsonContentType.REQUEST
        elif "result" in data.keys() or "error" in data.keys():
            return JsonContentType.RESULT
    return JsonContentType.INVALID

However, our request interpreter (RPC client) does not support batches (but others might).