group_stream.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. """Authenticated, cursor-based event streaming for Yaoyao Group Chat."""
  2. from __future__ import annotations
  3. import asyncio
  4. import json
  5. import re
  6. import time
  7. from collections.abc import Callable, Mapping
  8. from typing import Any
  9. from uuid import UUID
  10. from fastapi import WebSocket
  11. from starlette.websockets import WebSocketDisconnect
  12. from .group_protocol import MAX_EVENT_BATCH_SIZE, MAX_EVENT_FRAME_BYTES
  13. HEARTBEAT_SECONDS = 20
  14. EVENT_POLL_SECONDS = 0.1
  15. IDLE_POLL_SECONDS = 0.5
  16. PLUGIN_STATE_POLL_SECONDS = 1.0
  17. MAX_CURSOR = 2**63 - 1
  18. FRAME_TOO_LARGE_CLOSE_CODE = 1009
  19. PLUGIN_DISABLED_CLOSE_CODE = 4404
  20. _ASCII_DECIMAL = re.compile(r"[0-9]+", flags=re.ASCII)
  21. _DISCONNECT_RUNTIME_MESSAGES = frozenset(
  22. {
  23. 'cannot call "receive" once a disconnect message has been received.',
  24. 'cannot call "send" once a close message has been sent.',
  25. 'websocket is not connected. need to call "accept" first.',
  26. }
  27. )
  28. def websocket_upgrade_allowed(websocket: WebSocket) -> tuple[bool, int]:
  29. """Apply the core Dashboard WebSocket guards, in their required order."""
  30. try:
  31. from hermes_cli import web_server
  32. except Exception:
  33. return False, 4401
  34. try:
  35. if not web_server._ws_auth_ok(websocket):
  36. return False, 4401
  37. except Exception:
  38. return False, 4401
  39. try:
  40. if not web_server._ws_request_is_allowed(websocket):
  41. return False, 4403
  42. except Exception:
  43. return False, 4403
  44. return True, 1000
  45. def parse_cursor(value: str | None) -> int:
  46. """Parse an unsigned 63-bit ASCII decimal cursor without coercion."""
  47. raw = "0" if value is None else value
  48. if not isinstance(raw, str) or _ASCII_DECIMAL.fullmatch(raw) is None:
  49. raise ValueError("cursor is malformed")
  50. cursor = int(raw, 10)
  51. if cursor > MAX_CURSOR:
  52. raise ValueError("cursor is out of range")
  53. return cursor
  54. def _canonical_epoch(value: object) -> str | None:
  55. if not isinstance(value, str):
  56. return None
  57. try:
  58. canonical = str(UUID(value))
  59. except ValueError:
  60. return None
  61. return canonical if value == canonical else None
  62. def _epoch_matches(value: str | None, current_epoch: str) -> bool:
  63. return _canonical_epoch(value) == current_epoch
  64. async def _store_call(
  65. store_provider: Callable[[], object],
  66. method: str,
  67. *args: object,
  68. ) -> Any:
  69. """Resolve the shared store and perform one complete read off-loop."""
  70. def invoke() -> Any:
  71. store = store_provider()
  72. return getattr(store, method)(*args)
  73. return await asyncio.to_thread(invoke)
  74. def event_frame(event: Mapping[str, object]) -> dict[str, object]:
  75. """Project a persisted Store event onto the exact public WS envelope."""
  76. return {
  77. "type": "group.event",
  78. "epoch": event["epoch"],
  79. "cursor": event["cursor"],
  80. "roomId": event["roomId"],
  81. "event": event["eventType"],
  82. "payload": event["payload"],
  83. }
  84. def _encode_frame_json(frame: object) -> str:
  85. """Match Starlette's text-frame JSON encoding for byte-limit checks."""
  86. return json.dumps(frame, separators=(",", ":"), ensure_ascii=False)
  87. async def _send_json_bounded(
  88. websocket: WebSocket,
  89. frame: dict[str, object],
  90. ) -> bool:
  91. """Send one v1 frame, or close without advancing a replay cursor."""
  92. encoded = _encode_frame_json(frame)
  93. if len(encoded.encode("utf-8")) > MAX_EVENT_FRAME_BYTES:
  94. await websocket.close(code=FRAME_TOO_LARGE_CLOSE_CODE)
  95. return False
  96. await websocket.send_json(frame)
  97. return True
  98. def _batch_has_different_epoch(events: object, *, epoch: str) -> bool:
  99. """Return whether a shaped event belongs to another journal epoch."""
  100. if not isinstance(events, list):
  101. return False
  102. for event in events:
  103. if not isinstance(event, Mapping):
  104. continue
  105. event_epoch = _canonical_epoch(event.get("epoch"))
  106. if event_epoch is not None and event_epoch != epoch:
  107. return True
  108. return False
  109. def _batch_is_contiguous(
  110. events: object,
  111. *,
  112. cursor: int,
  113. epoch: str,
  114. ) -> bool:
  115. if not isinstance(events, list):
  116. return False
  117. expected = cursor + 1
  118. for event in events:
  119. if not isinstance(event, Mapping):
  120. return False
  121. event_cursor = event.get("cursor")
  122. if (
  123. not isinstance(event_cursor, int)
  124. or isinstance(event_cursor, bool)
  125. or event_cursor != expected
  126. or event.get("epoch") != epoch
  127. or "roomId" not in event
  128. or not isinstance(event.get("eventType"), str)
  129. or not isinstance(event.get("payload"), Mapping)
  130. ):
  131. return False
  132. expected += 1
  133. return True
  134. async def _send_reset(
  135. websocket: WebSocket,
  136. store_provider: Callable[[], object],
  137. *,
  138. reason: str,
  139. epoch: str,
  140. accepted: bool,
  141. ) -> None:
  142. latest_cursor = await _store_call(store_provider, "latest_cursor")
  143. if not accepted:
  144. await websocket.accept()
  145. if not await _send_json_bounded(
  146. websocket,
  147. {
  148. "type": "group.reset_required",
  149. "reason": reason,
  150. "epoch": epoch,
  151. "cursor": latest_cursor,
  152. },
  153. ):
  154. return
  155. await websocket.close(code=4409)
  156. async def _send_status_reset(
  157. websocket: WebSocket,
  158. store_provider: Callable[[], object],
  159. *,
  160. status: object,
  161. current_epoch: str,
  162. accepted: bool,
  163. ) -> None:
  164. reason = "epoch_mismatch" if status == "epoch_mismatch" else "cursor_expired"
  165. epoch = current_epoch
  166. if reason == "epoch_mismatch":
  167. epoch = await _store_call(store_provider, "journal_epoch")
  168. await _send_reset(
  169. websocket,
  170. store_provider,
  171. reason=reason,
  172. epoch=epoch,
  173. accepted=accepted,
  174. )
  175. async def _watch_disconnect(websocket: WebSocket) -> None:
  176. """Wait for peer disconnect without consuming or mutating runtime state."""
  177. while True:
  178. message = await websocket.receive()
  179. if message.get("type") == "websocket.disconnect":
  180. return
  181. async def _pause_until_poll(
  182. disconnect_task: asyncio.Task[None], seconds: float
  183. ) -> bool:
  184. done, _ = await asyncio.wait({disconnect_task}, timeout=seconds)
  185. if disconnect_task not in done:
  186. return True
  187. await disconnect_task
  188. return False
  189. def _is_disconnect_runtime_error(error: RuntimeError) -> bool:
  190. return str(error).lower() in _DISCONNECT_RUNTIME_MESSAGES
  191. async def _stream_authorized(
  192. websocket: WebSocket,
  193. store_provider: Callable[[], object],
  194. *,
  195. availability_provider: Callable[[], bool] | None = None,
  196. ) -> None:
  197. if availability_provider is not None and not await asyncio.to_thread(
  198. availability_provider
  199. ):
  200. await websocket.close(code=PLUGIN_DISABLED_CLOSE_CODE)
  201. return
  202. current_epoch = await _store_call(store_provider, "journal_epoch")
  203. requested_epoch = websocket.query_params.get("epoch")
  204. if not _epoch_matches(requested_epoch, current_epoch):
  205. await _send_reset(
  206. websocket,
  207. store_provider,
  208. reason="epoch_mismatch",
  209. epoch=current_epoch,
  210. accepted=False,
  211. )
  212. return
  213. try:
  214. cursor = parse_cursor(websocket.query_params.get("cursor"))
  215. except ValueError:
  216. await _send_reset(
  217. websocket,
  218. store_provider,
  219. reason="cursor_expired",
  220. epoch=current_epoch,
  221. accepted=False,
  222. )
  223. return
  224. status = await _store_call(store_provider, "cursor_status", current_epoch, cursor)
  225. if status != "ok":
  226. await _send_status_reset(
  227. websocket,
  228. store_provider,
  229. status=status,
  230. current_epoch=current_epoch,
  231. accepted=False,
  232. )
  233. return
  234. await websocket.accept()
  235. if not await _send_json_bounded(
  236. websocket,
  237. {
  238. "type": "group.ready",
  239. "epoch": current_epoch,
  240. "cursor": cursor,
  241. "heartbeatSeconds": HEARTBEAT_SECONDS,
  242. },
  243. ):
  244. return
  245. last_activity = time.monotonic()
  246. last_availability_check = last_activity
  247. disconnect_task = asyncio.create_task(_watch_disconnect(websocket))
  248. try:
  249. while not disconnect_task.done():
  250. now = time.monotonic()
  251. if (
  252. availability_provider is not None
  253. and now - last_availability_check >= PLUGIN_STATE_POLL_SECONDS
  254. ):
  255. if not await asyncio.to_thread(availability_provider):
  256. await websocket.close(code=PLUGIN_DISABLED_CLOSE_CODE)
  257. return
  258. last_availability_check = now
  259. status = await _store_call(
  260. store_provider, "cursor_status", current_epoch, cursor
  261. )
  262. if status != "ok":
  263. await _send_status_reset(
  264. websocket,
  265. store_provider,
  266. status=status,
  267. current_epoch=current_epoch,
  268. accepted=True,
  269. )
  270. return
  271. events = await _store_call(
  272. store_provider,
  273. "events_after",
  274. cursor,
  275. MAX_EVENT_BATCH_SIZE,
  276. )
  277. observed_epoch = await _store_call(store_provider, "journal_epoch")
  278. if observed_epoch != current_epoch or _batch_has_different_epoch(
  279. events, epoch=current_epoch
  280. ):
  281. await _send_reset(
  282. websocket,
  283. store_provider,
  284. reason="epoch_mismatch",
  285. epoch=observed_epoch,
  286. accepted=True,
  287. )
  288. return
  289. if not _batch_is_contiguous(events, cursor=cursor, epoch=current_epoch):
  290. await _send_reset(
  291. websocket,
  292. store_provider,
  293. reason="cursor_expired",
  294. epoch=current_epoch,
  295. accepted=True,
  296. )
  297. return
  298. if disconnect_task.done():
  299. await disconnect_task
  300. return
  301. for event in events:
  302. next_cursor = int(event["cursor"])
  303. if not await _send_json_bounded(websocket, event_frame(event)):
  304. return
  305. cursor = next_cursor
  306. last_activity = time.monotonic()
  307. now = time.monotonic()
  308. if not events and now - last_activity >= HEARTBEAT_SECONDS:
  309. if not await _send_json_bounded(
  310. websocket,
  311. {"type": "group.heartbeat", "cursor": cursor},
  312. ):
  313. return
  314. last_activity = time.monotonic()
  315. delay = EVENT_POLL_SECONDS if events else IDLE_POLL_SECONDS
  316. if not await _pause_until_poll(disconnect_task, delay):
  317. return
  318. finally:
  319. disconnect_task.cancel()
  320. try:
  321. await disconnect_task
  322. except (asyncio.CancelledError, WebSocketDisconnect):
  323. pass
  324. except RuntimeError as error:
  325. if not _is_disconnect_runtime_error(error):
  326. raise
  327. async def stream_group_events(
  328. websocket: WebSocket,
  329. store_provider: Callable[[], object],
  330. ) -> None:
  331. """Authenticate and stream persisted events without touching Agent runtime."""
  332. allowed, close_code = websocket_upgrade_allowed(websocket)
  333. if not allowed:
  334. await websocket.close(code=close_code)
  335. return
  336. await stream_authorized_group_events(websocket, store_provider)
  337. async def stream_authorized_group_events(
  338. websocket: WebSocket,
  339. store_provider: Callable[[], object],
  340. *,
  341. availability_provider: Callable[[], bool] | None = None,
  342. ) -> None:
  343. """Stream after the caller has consumed auth and request guards exactly once."""
  344. try:
  345. await _stream_authorized(
  346. websocket,
  347. store_provider,
  348. availability_provider=availability_provider,
  349. )
  350. except WebSocketDisconnect:
  351. return
  352. except RuntimeError as error:
  353. if not _is_disconnect_runtime_error(error):
  354. raise