Files
bonaminandClaude Opus 5.5 f85894a72e refactor(connect): one live connection, no token in any address (SSE removed)
Plan step 4.0. Owner (2026-11-17): no phone in use needs to keep working, so no
compatibility path.
- Removed the SSE channel: routers/sse.py (/api/sse/stream, which still accepted a JWT whose
  session had ended — a signed-out phone could keep listening), services/sse_bus.py (every
  backend module now calls services/ws_bus.broadcast_sync directly), waiter useSSE.js.
- Credentials only in the first frame: the waiter's useWebSocket and the manager's
  LiveProvider send {token} there like the terminal; routers/ws.py no longer reads ?token=
  (a token in a URL ends up in proxy and server logs).
- Waiter: SSEContext → LiveContext (LiveProvider, useLiveContext, liveAlive, the
  'live-event' / 'live-reconnected' window events), dead SSE compat code removed.
- Tests: a token in the address is refused, /api/sse/stream is 404; e2e browser (3 delivery
  modes) and manager assert no token in the live connection's address. Android taps now
  wait for their element (the fixed sleeps made the suite flaky, KI-009).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:49:21 +02:00

246 lines
9.6 KiB
Python

"""
WebSocket Event Bus: every live event the backend sends (phase 4.0: the only one; SSE is gone).
Every router and service calls broadcast_sync() here (user_ids / device_ids to address it).
The WS endpoint (routers/ws.py) registers each open socket with connect()/disconnect().
Protocol (JSON frames):
Server → Client: { "seq": 123, "type": "order_updated", "data": { ... } }
Client → Server: { "cursor": 120, ... } (sent immediately after connect)
Server → Client: { "type": "ping" } (every 25s keepalive)
Client → Server: { "type": "pong" } (optional, ignored if not sent)
On connect the client sends its last known seq. The server replays everything
it has stored since that seq, then switches to live streaming. Events are stored
in the sync_events SQLite table (written here, pruned on startup).
Who gets what (plan step 3.1a):
- Each socket is a Conn: a user (user_id + session sid) and/or a paired device
(device_id + app_key). `all_events` is False only for a device socket without a user
whose app needs a sign-in (a KDS on its sign-in screen): it gets only events
addressed to its device.
- broadcast_sync(type, data) every socket with all_events
- broadcast_sync(..., user_ids=[...]) sockets of those users
- broadcast_sync(..., device_ids=[...]) sockets of those devices (3.4: a POS
pushes to its own customer display)
(both lists given: either matches)
- Control frames, not stored, no seq: notify_device() sends `device.updated`;
end_session() / end_device() send `session.ended` / `device.revoked` / `device.updated`
and close the socket (routers/ws.py closes with code 4001/4003). They are called by
core.sessions when a session ends and by routers/devices.py on revoke/reassign/edit.
Agent notes:
- Each Conn keeps the event loop it runs on; every push goes through
loop.call_soon_threadsafe, so broadcast_sync works from sync routes (thread pool), from
async code and from the TestClient's per-connection loops alike.
"""
import asyncio
import json
import logging
import threading
from dataclasses import dataclass, field
from datetime import timedelta
from typing import Iterable, Optional
from core.timeutil import to_db_str, utcnow
logger = logging.getLogger(__name__)
QUEUE_SIZE = 512
# ── Event loop (captured once at startup; kept for callers that still read it) ─
_main_loop: asyncio.AbstractEventLoop | None = None
def init_loop(loop: asyncio.AbstractEventLoop) -> None:
global _main_loop
_main_loop = loop
# ── Connected sockets ─────────────────────────────────────────────────────────
@dataclass(eq=False)
class Conn:
user_id: Optional[int] = None
sid: Optional[str] = None
device_id: Optional[int] = None
app_key: Optional[str] = None
all_events: bool = True
loop: asyncio.AbstractEventLoop | None = None
queue: asyncio.Queue = field(default_factory=lambda: asyncio.Queue(maxsize=QUEUE_SIZE))
closing: Optional[tuple[str, int]] = None # (last frame, close code) once it must close
def sees(self, user_ids: Optional[list[int]], device_ids: Optional[list[int]]) -> bool:
if user_ids is None and device_ids is None:
return self.all_events
return ((user_ids is not None and self.user_id is not None and self.user_id in user_ids)
or (device_ids is not None and self.device_id is not None and self.device_id in device_ids))
_conns: set[Conn] = set()
_lock = threading.Lock()
async def connect(user_id: Optional[int] = None, *, sid: str | None = None, device_id: int | None = None,
app_key: str | None = None, all_events: bool = True) -> Conn:
conn = Conn(user_id=user_id, sid=sid, device_id=device_id, app_key=app_key, all_events=all_events,
loop=asyncio.get_running_loop())
with _lock:
_conns.add(conn)
return conn
async def disconnect(conn: Conn) -> None:
with _lock:
_conns.discard(conn)
def _matching(pred) -> list[Conn]:
with _lock:
return [c for c in _conns if pred(c)]
def _offer(q: asyncio.Queue, item) -> None:
try:
q.put_nowait(item)
except asyncio.QueueFull:
pass # slow client: drop the live frame; it replays on reconnect
def _push(conn: Conn, item) -> None:
try:
conn.loop.call_soon_threadsafe(_offer, conn.queue, item)
except RuntimeError:
pass # its loop is gone: the socket is closing anyway
def _close(conns: Iterable[Conn], frame: dict, code: int) -> int:
text = json.dumps(frame)
n = 0
for c in conns:
if c.closing is None:
c.closing = (text, code)
_push(c, None) # wake the socket's loop; it sees `closing` and ends
n += 1
return n
CLOSE_SESSION = 4001 # session ended / not signed in: sign in again
CLOSE_DEVICE = 4003 # device removed / not paired / changed: re-read /api/devices/me
def end_session(sid: str, reason: str) -> int:
"""A session ended (core.sessions): its sockets get `session.ended` and close."""
return _close(_matching(lambda c: c.sid == sid), {"type": "session.ended", "data": {"reason": reason}},
CLOSE_SESSION)
def end_device(device_id: int, event: str = "device.revoked", data: dict | None = None) -> int:
"""A device was removed (`device.revoked`) or now runs another app (`device.updated`):
every socket of the device gets the event and closes."""
return _close(_matching(lambda c: c.device_id == device_id),
{"type": event, "data": {"device_id": device_id, **(data or {})}}, CLOSE_DEVICE)
def notify_device(device_ids: Iterable[int] | None = None, *, every_device: bool = False,
data: dict | None = None) -> int:
"""`device.updated` to the sockets of these devices (or of every paired device): the screen
re-reads GET /api/devices/me (config, login mode, app on/off). Not stored."""
ids = set(device_ids or ())
conns = _matching(lambda c: c.device_id is not None and (every_device or c.device_id in ids))
for c in conns:
_push(c, json.dumps({"type": "device.updated", "data": {"device_id": c.device_id, **(data or {})}}))
return len(conns)
# ── Persistence helpers ───────────────────────────────────────────────────────
def _get_db():
from database import SessionLocal
return SessionLocal()
def _persist_event(event_type: str, data: dict, user_ids: list[int] | None,
device_ids: list[int] | None = None) -> int:
"""Write event to sync_events table, return the new seq_id."""
from sqlalchemy import text
db = _get_db()
try:
result = db.execute(
text(
"INSERT INTO sync_events (event_type, payload, target_user_ids, target_device_ids, created_at) "
"VALUES (:et, :payload, :uids, :dids, :now)"
),
{
"et": event_type,
"payload": json.dumps(data),
"uids": json.dumps(user_ids) if user_ids is not None else None,
"dids": json.dumps(device_ids) if device_ids is not None else None,
"now": to_db_str(utcnow()), # same text format as UTCDateTime
},
)
db.commit()
return result.lastrowid
finally:
db.close()
def get_events_since(cursor: int, conn: Conn) -> list[dict]:
"""All stored events with seq_id > cursor that this socket may see."""
from sqlalchemy import text
db = _get_db()
try:
rows = db.execute(
text(
"SELECT id, event_type, payload, target_user_ids, target_device_ids FROM sync_events "
"WHERE id > :cursor ORDER BY id ASC LIMIT 500"
),
{"cursor": cursor},
).fetchall()
finally:
db.close()
events = []
for row in rows:
uids = json.loads(row[3]) if row[3] else None
dids = json.loads(row[4]) if row[4] else None
if conn.sees(uids, dids):
events.append({"seq": row[0], "type": row[1], "data": json.loads(row[2])})
return events
def prune_old_events(hours: int = 24) -> int:
"""Delete events older than `hours`. Called on startup."""
from sqlalchemy import text
db = _get_db()
try:
cutoff = to_db_str(utcnow() - timedelta(hours=hours))
result = db.execute(
text("DELETE FROM sync_events WHERE created_at < :cutoff"),
{"cutoff": cutoff},
)
db.commit()
return result.rowcount
finally:
db.close()
# ── Broadcast ─────────────────────────────────────────────────────────────────
def broadcast_sync(event_type: str, data: dict, *, user_ids: list[int] | None = None,
device_ids: list[int] | None = None) -> None:
"""
Persists the event (so reconnecting clients can replay it), then pushes it to every
open socket that may see it. Safe from sync routes, async code and any thread.
"""
try:
seq_id = _persist_event(event_type, data, user_ids, device_ids)
except Exception:
logger.exception("ws_bus: failed to persist event %s", event_type)
seq_id = 0
frame = json.dumps({"seq": seq_id, "type": event_type, "data": data})
for c in _matching(lambda c: c.sees(user_ids, device_ids)):
_push(c, frame)