From 06122c66ddd096e1f27be9fcde72ae2e8b8eb213 Mon Sep 17 00:00:00 2001 From: Lucio Chen Date: Sat, 25 Jul 2026 09:27:24 -0700 Subject: [PATCH] fix: single-reader CDP session; prime walk no longer fails silently prime ran the in-page click walk as a task while drain() also read the websocket. `websockets` forbids concurrent recv(), so this was always broken -- it just failed differently by version: loudly on websockets 15.0.1, and silently on 16.0, where the JS still executed but its return value was lost. The `walk: None` in every prime summary was that failure being swallowed by a bare `except Exception`, and I read past it. CDPSession now runs exactly one reader coroutine that dispatches command replies to futures and events to a queue, so call() and drain() can safely run concurrently -- which priming genuinely needs, since the requests being observed are triggered by the script being awaited. call() also gains a timeout so a lost reply fails instead of hanging, and the walk now reports its error rather than reporting None. Tests use a fake websocket that asserts the socket never has more than one concurrent reader. 129 tests, no network required. Co-Authored-By: Claude Opus 5 --- pyproject.toml | 5 +- src/wodify/cdp.py | 94 +++++++++++++++++++++-------- src/wodify/prime.py | 17 ++++-- tests/test_cdp.py | 141 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 226 insertions(+), 31 deletions(-) create mode 100644 tests/test_cdp.py diff --git a/pyproject.toml b/pyproject.toml index f238e07..07fba48 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,7 +13,7 @@ dependencies = [] # CDP is a WebSocket protocol, so priming needs a client. The query path is # deliberately stdlib-only. prime = ["websockets>=12"] -dev = ["pytest>=8"] +dev = ["pytest>=8", "pytest-asyncio>=0.23"] [project.scripts] wodify = "wodify.cli:main" @@ -23,3 +23,6 @@ where = ["src"] [tool.pytest.ini_options] testpaths = ["tests"] +# The CDP session spawns its reader task on construction, so its fixtures must +# be built inside a running loop. +asyncio_mode = "auto" diff --git a/src/wodify/cdp.py b/src/wodify/cdp.py index 558e86a..fb40376 100644 --- a/src/wodify/cdp.py +++ b/src/wodify/cdp.py @@ -40,14 +40,22 @@ def resolve_ws_url(cdp_root: str | None = None, timeout: int = 8) -> str: class CDPSession: - """A connected CDP session with one attached page target.""" + """A connected CDP session with one attached page target. + + Exactly one coroutine reads the socket: :meth:`_pump` dispatches command + replies to waiting futures and everything else to an event queue. This is + not incidental structure -- ``websockets`` raises if two coroutines call + ``recv`` concurrently, and priming genuinely needs to run a long in-page + script *while* watching the requests it triggers. + """ def __init__(self, ws: Any) -> None: self._ws = ws self._id = 0 self.session_id: str | None = None - #: Events received while waiting for command replies. - self._events: list[dict[str, Any]] = [] + self._pending: dict[int, asyncio.Future] = {} + self._events: asyncio.Queue = asyncio.Queue() + self._reader: asyncio.Task | None = None @classmethod async def connect(cls, ws_url: str | None = None) -> "CDPSession": @@ -59,28 +67,62 @@ class CDPSession: ) from exc url = ws_url or resolve_ws_url() ws = await websockets.connect(url, max_size=64 * 1024 * 1024) - return cls(ws) + session = cls(ws) + session.start() + return session + + def start(self) -> None: + if self._reader is None: + self._reader = asyncio.create_task(self._pump()) + + async def _pump(self) -> None: + """Sole reader. Routes replies to futures, events to the queue.""" + try: + async for raw in self._ws: + try: + msg = json.loads(raw) + except (TypeError, ValueError): + continue + mid = msg.get("id") + fut = self._pending.pop(mid, None) if mid is not None else None + if fut is not None: + if not fut.done(): + fut.set_result(msg) + elif msg.get("method"): + self._events.put_nowait(msg) + except Exception as exc: # noqa: BLE001 - surface to every waiter + for fut in self._pending.values(): + if not fut.done(): + fut.set_exception(exc) + self._pending.clear() async def close(self) -> None: + if self._reader is not None: + self._reader.cancel() + self._reader = None await self._ws.close() async def call(self, method: str, params: dict[str, Any] | None = None, - *, on_target: bool = False) -> dict[str, Any]: + *, on_target: bool = False, timeout: float = 60.0) -> dict[str, Any]: self._id += 1 - msg: dict[str, Any] = {"id": self._id, "method": method, "params": params or {}} + mid = self._id + msg: dict[str, Any] = {"id": mid, "method": method, "params": params or {}} if on_target: if not self.session_id: raise RuntimeError(f"{method}: no page target attached") msg["sessionId"] = self.session_id + + fut: asyncio.Future = asyncio.get_event_loop().create_future() + self._pending[mid] = fut await self._ws.send(json.dumps(msg)) - while True: - raw = json.loads(await self._ws.recv()) - if raw.get("id") == self._id: - if "error" in raw: - raise RuntimeError(f"{method}: {raw['error']}") - return raw.get("result", {}) - if raw.get("method"): - self._events.append(raw) + try: + raw = await asyncio.wait_for(fut, timeout=timeout) + except asyncio.TimeoutError as exc: + self._pending.pop(mid, None) + raise RuntimeError(f"{method}: timed out after {timeout}s") from exc + if "error" in raw: + raise RuntimeError(f"{method}: {raw['error']}") + return raw.get("result", {}) async def open_page(self, url: str = "about:blank") -> None: target = await self.call("Target.createTarget", {"url": url}) @@ -123,18 +165,20 @@ class CDPSession: async def drain(self, seconds: float, handler: Callable[[dict[str, Any]], None]) -> None: - """Feed every event received over ``seconds`` to ``handler``.""" - for event in self._events: - handler(event) - self._events.clear() + """Feed every event received over ``seconds`` to ``handler``. - deadline = asyncio.get_event_loop().time() + seconds - while asyncio.get_event_loop().time() < deadline: - remaining = deadline - asyncio.get_event_loop().time() + Reads from the queue the pump fills, never from the socket, so this can + run concurrently with :meth:`call`. + """ + loop = asyncio.get_event_loop() + deadline = loop.time() + seconds + while True: + remaining = deadline - loop.time() + if remaining <= 0: + return try: - raw = json.loads(await asyncio.wait_for(self._ws.recv(), - timeout=max(0.1, min(2.0, remaining)))) + event = await asyncio.wait_for(self._events.get(), + timeout=min(1.0, remaining)) except asyncio.TimeoutError: continue - if raw.get("method"): - handler(raw) + handler(event) diff --git a/src/wodify/prime.py b/src/wodify/prime.py index b36e5cd..909c0e3 100644 --- a/src/wodify/prime.py +++ b/src/wodify/prime.py @@ -161,14 +161,21 @@ async def _run(walk=WALK, workout_date: str | None = None) -> dict[str, Any]: await session.drain(wait, lambda ev: _observe(ev, found, csrf)) # Walk to a real workout screen so GetAllWorkoutData (and the class - # detail actions) actually fire. + # detail actions) actually fire. The walk and the request-observer run + # concurrently on purpose: the requests we want are triggered *by* the + # walk. CDPSession multiplexes one socket reader, so this is safe. script = WORKOUT_WALK_JS.replace("__DATE_LABEL__", _date_label(workout_date)) walk_task = asyncio.create_task(session.evaluate(script, await_promise=True)) - await session.drain(26, lambda ev: _observe(ev, found, csrf)) + drain_task = asyncio.create_task( + session.drain(30, lambda ev: _observe(ev, found, csrf)) + ) try: - walk_log = await asyncio.wait_for(walk_task, timeout=10) - except (asyncio.TimeoutError, Exception): # noqa: BLE001 - best effort - walk_log = None + walk_log = await asyncio.wait_for(asyncio.shield(walk_task), timeout=45) + except asyncio.TimeoutError: + walk_log = {"error": "walk timed out"} + except Exception as exc: # noqa: BLE001 - report, do not hide + walk_log = {"error": f"{type(exc).__name__}: {exc}"} + await drain_task module_version = await session.evaluate( "fetch('/WodifyClient/moduleservices/moduleversioninfo')" diff --git a/tests/test_cdp.py b/tests/test_cdp.py new file mode 100644 index 0000000..c95df62 --- /dev/null +++ b/tests/test_cdp.py @@ -0,0 +1,141 @@ +"""CDP session multiplexing. + +`websockets` raises if two coroutines call recv() concurrently, and priming +genuinely needs to run a long in-page script *while* watching the requests that +script triggers. An earlier version ran both against the socket directly; it +failed loudly on one machine and silently on another, losing the walk result +while looking like it worked. +""" +from __future__ import annotations + +import asyncio +import json + +import pytest + +from wodify import cdp + + +class FakeWS: + """Minimal websocket: replies to commands, can inject events.""" + + def __init__(self): + self.sent: list[dict] = [] + self._out: asyncio.Queue = asyncio.Queue() + self.closed = False + self.recv_callers = 0 + self.max_concurrent_recv = 0 + + async def send(self, raw): + msg = json.loads(raw) + self.sent.append(msg) + await self._out.put(json.dumps( + {"id": msg["id"], "result": {"echo": msg["method"]}})) + + async def inject_event(self, method, params=None): + await self._out.put(json.dumps({"method": method, "params": params or {}})) + + async def close(self): + self.closed = True + + def __aiter__(self): + return self + + async def __anext__(self): + self.recv_callers += 1 + self.max_concurrent_recv = max(self.max_concurrent_recv, self.recv_callers) + try: + return await self._out.get() + finally: + self.recv_callers -= 1 + + +@pytest.fixture() +async def session(): + # Built inside a running loop: start() spawns the reader task. + ws = FakeWS() + s = cdp.CDPSession(ws) + s.start() + return s, ws + + +@pytest.mark.asyncio +async def test_call_returns_result(session): + s, ws = session + result = await s.call("Page.enable") + assert result == {"echo": "Page.enable"} + await s.close() + + +@pytest.mark.asyncio +async def test_events_go_to_drain_not_to_call(session): + s, ws = session + seen = [] + drain = asyncio.create_task(s.drain(1.5, seen.append)) + await ws.inject_event("Network.requestWillBeSent", {"n": 1}) + result = await s.call("Runtime.evaluate") + await drain + assert result == {"echo": "Runtime.evaluate"} + assert [e["params"]["n"] for e in seen] == [1] + await s.close() + + +@pytest.mark.asyncio +async def test_call_and_drain_run_concurrently_without_conflict(session): + """The regression: exactly one coroutine may read the socket.""" + s, ws = session + seen = [] + drain = asyncio.create_task(s.drain(1.5, seen.append)) + await asyncio.gather(*(s.call(f"M{i}") for i in range(5))) + await ws.inject_event("Network.requestWillBeSent", {"n": 2}) + await drain + assert ws.max_concurrent_recv <= 1, "socket must have a single reader" + assert len(seen) == 1 + await s.close() + + +@pytest.mark.asyncio +async def test_call_times_out_rather_than_hanging(): + class Silent(FakeWS): + async def send(self, raw): + self.sent.append(json.loads(raw)) # never replies + + ws = Silent() + s = cdp.CDPSession(ws) + s.start() + with pytest.raises(RuntimeError, match="timed out"): + await s.call("Never.Replies", timeout=0.2) + await s.close() + + +@pytest.mark.asyncio +async def test_error_reply_raises(session): + class Failing(FakeWS): + async def send(self, raw): + msg = json.loads(raw) + await self._out.put(json.dumps( + {"id": msg["id"], "error": {"message": "nope"}})) + + ws = Failing() + s = cdp.CDPSession(ws) + s.start() + with pytest.raises(RuntimeError, match="nope"): + await s.call("Bad.Method") + await s.close() + + +@pytest.mark.asyncio +async def test_drain_returns_after_its_window(session): + s, _ = session + started = asyncio.get_event_loop().time() + await s.drain(0.3, lambda _: None) + assert asyncio.get_event_loop().time() - started >= 0.3 + await s.close() + + +@pytest.mark.asyncio +async def test_call_on_target_without_attachment_raises(session): + s, _ = session + with pytest.raises(RuntimeError, match="no page target"): + await s.call("Page.navigate", on_target=True) + await s.close()