Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 30 additions & 12 deletions marge/seq/pulserver_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,14 +276,18 @@ 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

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:
Expand All @@ -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."""
Expand Down
36 changes: 36 additions & 0 deletions tests/test_pulserver_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
{
Expand Down
Loading