diff --git a/marge/seq/pulserver_console.py b/marge/seq/pulserver_console.py index cbbad0f..4f255fa 100644 --- a/marge/seq/pulserver_console.py +++ b/marge/seq/pulserver_console.py @@ -276,7 +276,9 @@ class AsyncGateway: Under Pyodide a Qt handler cannot wait on the network, so every request is a coroutine; the connection is the browser's WebSocket there and the - ``websockets`` asyncio client elsewhere. + ``websockets`` asyncio client elsewhere. Requests may overlap, as two scans + started one after the other do: each reply reaches the request whose id it + carries, whichever request read it off the connection. """ asynchronous = True @@ -284,6 +286,8 @@ class AsyncGateway: def __init__(self, connection: Any) -> None: self._connection = connection self._next = 0 + self._replies: dict[int, asyncio.Queue] = {} + self._reading = asyncio.Lock() @classmethod async def open(cls, address: str) -> AsyncGateway: @@ -300,17 +304,31 @@ async def request( """Send one request and return its last reply, as :meth:`Gateway.request` does.""" self._next += 1 ident = self._next - await self._connection.send(json.dumps({"id": ident, "call": call, **fields})) - while True: - reply = json.loads(await self._connection.recv()) - if reply.get("id") != ident: - continue - if "error" in reply: - raise RuntimeError(reply["error"]) - if call != "scan" or "done" in reply: - return reply - if on_message is not None: - on_message(reply) + self._replies[ident] = asyncio.Queue() + try: + await self._connection.send(json.dumps({"id": ident, "call": call, **fields})) + while True: + reply = await self._reply(ident) + if "error" in reply: + raise RuntimeError(reply["error"]) + if call != "scan" or "done" in reply: + return reply + if on_message is not None: + on_message(reply) + finally: + del self._replies[ident] + + async def _reply(self, ident: int) -> dict: + """Return the next reply to request ``ident``, reading the connection, one reader at a time, until one has arrived.""" + replies = self._replies[ident] + while replies.empty(): + async with self._reading: + if not replies.empty(): + break + reply = json.loads(await self._connection.recv()) + if reply.get("id") in self._replies: + self._replies[reply["id"]].put_nowait(reply) + return replies.get_nowait() async def localizer(self, subject: str, coil: str | None = None) -> list[bytes]: """Start an exam on ``subject`` in ``coil`` and return its three-plane localizer, as :meth:`Gateway.localizer` does.""" diff --git a/tests/test_pulserver_console.py b/tests/test_pulserver_console.py index c0f6b9c..dfe0547 100644 --- a/tests/test_pulserver_console.py +++ b/tests/test_pulserver_console.py @@ -307,6 +307,42 @@ def test_an_asynchronous_scan_request_passes_its_clock_on_and_returns_when_done( assert seen == [{"id": 1, "clock": 0.5, "duration": 1.0}] +class _InterleavedSocket: + """A console connection answering two scans at once, their replies interleaved, as a console answers overlapping requests.""" + + def __init__(self): + self.sent = [] + self._replies = asyncio.Queue() + + async def send(self, text): + ident = json.loads(text)["id"] + self.sent.append(ident) + if len(self.sent) == 2: + for message in ({"clock": 0.5}, {"dicom": "a"}, {"done": 0}): + for which in self.sent: + self._replies.put_nowait({"id": which, **message}) + + async def recv(self): + return json.dumps(await self._replies.get()) + + +def test_two_scans_requested_at_once_each_receive_their_own_replies_to_their_end(): + gateway = console.AsyncGateway(_InterleavedSocket()) + seen = {1: [], 2: []} + + async def both(): + return await asyncio.gather( + gateway.request("scan", on_message=seen[1].append, design="d1"), + gateway.request("scan", on_message=seen[2].append, design="d2"), + ) + + done = asyncio.run(asyncio.wait_for(both(), timeout=5.0)) + + assert done == [{"id": 1, "done": 0}, {"id": 2, "done": 0}] + for ident, messages in seen.items(): + assert messages == [{"id": ident, "clock": 0.5}, {"id": ident, "dicom": "a"}] + + def test_the_listings_are_each_plugins_entries(): gateway = _Scripted( {