Skip to content

Use a queue per request id to handle responses #2

@fwcd

Description

@fwcd

Currently, a dict is used to share responses from the receive loop with other tasks and a queue of Events that is drained every time a response is received:

self._received_messages = cast(dict[str, ServerMessage], {})
self._receive_events = asyncio.Queue()
async def _run_receive_loop(self):
try:
while True:
binary = await self._websocket.recv()
message = deserialize(ServerMessage, msgpack.unpackb(binary))
self._received_messages[message.request_id] = message
while not self._receive_events.empty():
event = cast(asyncio.Event, await self._receive_events.get())
event.set()
except websockets.ConnectionClosed:
pass

Note

Since we use async/await we don't have to worry about threading issues, since the asyncio runtime is single-threaded. In fact, most asyncio primitives (e.g. Queue or Event) are not thread-safe either.

The disadvantage with this approach is that we only store a single (the most recent) message per request id. For some use cases (e.g. streaming the model itself) this may be fine, but for others it's not (e.g. input events). We should therefore make sure that no responses get discarded. One way to achieve this would be to replace the dict[int, ServerMessage] with a dict[int, Queue[ServerMessage]].

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions