feat(backend): live connection and per-device settings for paired screens (platform-v2 3.1a)

- WebSocket: credentials may come in the first frame ({cursor, token?, device?}).
  A device token alone connects a paired screen (login-none apps get every event, a
  sign-in app only events addressed to it); a terminal session's JWT needs its own
  device, as over HTTP. Refusals send {type: refused, data: {code}} + close 4001/4003.
- ws_bus: registry of open sockets by user, session and device. Ending a session
  closes its sockets (session.ended); revoke/reassign close the device's sockets
  (device.revoked / device.updated); edits and module on/off send device.updated.
  Events can target devices (device_ids=..., sync_events.target_device_ids, rev 0014).
  Pushes go through each socket's own loop (call_soon_threadsafe).
- Device config: DeviceApp.config = typed ConfigFields, validated on pair/edit/
  reassign (validation.device_config), effective values (defaults filled) in both
  device views and the module catalogue. First field: auto_sign_out_minutes (KDS, POS).
- Manager: DeviceConfigFields renders an app's fields in the pair and edit dialogs.
- @xenia/api createLiveClient: `credentials` and `onRefused` options.
- Tests: tests/test_live.py (11), module texts for config fields, live client,
  devices logic, manager.mjs device setting + live socket checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 16:31:59 +02:00
co-authored by Claude Opus 5.5
parent 034426f870
commit bda5cde92b
31 changed files with 974 additions and 145 deletions
+139 -65
View File
@@ -1,32 +1,55 @@
"""
WebSocket Event Bus — replaces sse_bus.py for real-time communication.
Drop-in replacement: all routers continue calling broadcast_sync() unchanged.
The WS endpoint uses connect()/disconnect()/replay_missed() to manage clients.
Routers keep calling sse_bus.broadcast_sync() (which calls broadcast_sync() here).
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)
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
from typing import Dict, Set
from core.timeutil import to_db_str, utcnow
from datetime import datetime, timedelta, timezone
import threading
from dataclasses import dataclass, field
from datetime import timedelta
from typing import Iterable, Optional
from fastapi import WebSocket
from core.timeutil import to_db_str, utcnow
logger = logging.getLogger(__name__)
# ── Event loop (captured once at startup) ────────────────────────────────────
QUEUE_SIZE = 512
# ── Event loop (captured once at startup; kept for callers that still read it) ─
_main_loop: asyncio.AbstractEventLoop | None = None
@@ -36,24 +59,100 @@ def init_loop(loop: asyncio.AbstractEventLoop) -> None:
_main_loop = loop
# ── Connected clients: user_id → set of asyncio.Queue ────────────────────────
# ── Connected sockets ─────────────────────────────────────────────────────────
_connections: Dict[int, Set[asyncio.Queue]] = {}
@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))
async def connect(user_id: int) -> asyncio.Queue:
q: asyncio.Queue = asyncio.Queue(maxsize=512)
if user_id not in _connections:
_connections[user_id] = set()
_connections[user_id].add(q)
return q
_conns: set[Conn] = set()
_lock = threading.Lock()
async def disconnect(user_id: int, q: asyncio.Queue) -> None:
if user_id in _connections:
_connections[user_id].discard(q)
if not _connections[user_id]:
del _connections[user_id]
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 ───────────────────────────────────────────────────────
@@ -63,20 +162,22 @@ def _get_db():
return SessionLocal()
def _persist_event(event_type: str, data: dict, user_ids: list[int] | None) -> int:
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, created_at) "
"VALUES (:et, :payload, :uids, :now)"
"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
},
)
@@ -86,14 +187,14 @@ def _persist_event(event_type: str, data: dict, user_ids: list[int] | None) -> i
db.close()
def get_events_since(cursor: int, user_id: int) -> list[dict]:
"""Return all events with seq_id > cursor that are visible to user_id."""
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 FROM sync_events "
"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},
@@ -103,13 +204,10 @@ def get_events_since(cursor: int, user_id: int) -> list[dict]:
events = []
for row in rows:
target_user_ids = json.loads(row[3]) if row[3] else None
if target_user_ids is None or user_id in target_user_ids:
events.append({
"seq": row[0],
"type": row[1],
"data": json.loads(row[2]),
})
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
@@ -131,41 +229,17 @@ def prune_old_events(hours: int = 24) -> int:
# ── Broadcast ─────────────────────────────────────────────────────────────────
def broadcast_sync(event_type: str, data: dict, *, user_ids: list[int] | None = None) -> None:
def broadcast_sync(event_type: str, data: dict, *, user_ids: list[int] | None = None,
device_ids: list[int] | None = None) -> None:
"""
Called from sync route thread-pool workers.
Persists the event to DB (so reconnecting clients can replay it),
then schedules an async push to all currently connected sockets.
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)
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
if _main_loop is None:
return
_main_loop.call_soon_threadsafe(
_main_loop.create_task,
_broadcast_live(seq_id, event_type, data, user_ids),
)
async def _broadcast_live(
seq_id: int,
event_type: str,
data: dict,
user_ids: list[int] | None,
) -> None:
frame = json.dumps({"seq": seq_id, "type": event_type, "data": data})
targets = (
{uid: qs for uid, qs in _connections.items() if uid in user_ids}
if user_ids is not None
else dict(_connections)
)
for qs in targets.values():
for q in list(qs):
try:
q.put_nowait(frame)
except asyncio.QueueFull:
pass # slow client — drop live frame; they'll replay on reconnect
for c in _matching(lambda c: c.sees(user_ids, device_ids)):
_push(c, frame)