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 <[email protected]>
This commit is contained in:
1 parent
5a61890011
commit
06122c66dd
4 files changed
+226
-31
No files matched your search
+69
-25
@@ -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)
|
||||
+12
-5
@@ -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')"
|
||||
|
||||
Reference in new issue
Block a user