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
+3 -2
View File
@@ -17,8 +17,9 @@ Agent notes:
- last_seen_at is written at most every LAST_SEEN_EVERY_S.
- A user session started on a device (client "terminal") is bound to it: routers.deps.
get_current_user refuses it without that device's header (device.required), so scope
can't be escaped by dropping the header. SSE/WebSocket (token in the query, browsers
can't set headers there) only stream events and are not bound; revisit in phase 3.
can't be escaped by dropping the header. The WebSocket (routers/ws.py, 3.1a) applies the
same rule with the device token in its first frame; the legacy SSE stream doesn't (it
goes in phase 4).
"""
from __future__ import annotations
+1
View File
@@ -81,6 +81,7 @@ CODES: dict[str, tuple[int, str]] = {
"validation.unknown_language": (422, "Unsupported language: {language}."),
"validation.unknown_timezone": (422, "Unknown time zone: {timezone}."),
"validation.setting_value": (422, "{key} can't be set to {value!r}."),
"validation.device_config": (422, "This device setting is not valid: {key}."),
# server
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
# domain
+5 -2
View File
@@ -26,7 +26,7 @@ from pydantic import BaseModel
from sqlalchemy.orm import Session
from core import i18n, timeutil
from core.modules import entitlements, state
from core.modules import device_config, entitlements, state
from core.modules.registry import all_permissions, registry
from database import get_db
from core.access.deps import require
@@ -70,7 +70,8 @@ def _module_out(m, enabled: dict, effective: frozenset) -> dict:
"value": ent.limit(m.key, lim.key)} for lim in m.limits],
"settings": [{"key": sd.key, "type": sd.type, "default": sd.default, "description": sd.description}
for sd in m.settings],
"device_app": ({"login_modes": list(m.device_app.login_modes), "scope": list(m.device_app.scope)}
"device_app": ({"login_modes": list(m.device_app.login_modes), "scope": list(m.device_app.scope),
"config": device_config.describe(m.device_app.config)}
if m.device_app else None),
"workers": len(m.workers),
}
@@ -141,5 +142,7 @@ class ModuleToggle(BaseModel):
def set_module(key: str, body: ModuleToggle, db: Session = Depends(get_db),
user=Depends(require("core.modules.manage"))):
effective = state.set_enabled(db, key, body.enabled, user_id=getattr(user, "id", None) or None)
from services import ws_bus
ws_bus.notify_device(every_device=True) # paired screens re-read their app_status (3.1a)
enabled = state.enabled_map(db)
return _module_out(registry()[key], enabled, effective)
+100
View File
@@ -0,0 +1,100 @@
"""Per-device settings of an app (plan step 3.1a): what the manager may store in
devices.config and what the device reads back.
- validate(fields, config, db) -> dict | None: the cleaned config to store. Unknown keys,
wrong types, values outside choices/min/max and refs to missing rows raise
validation.device_config {key}. None/{} -> None (all defaults).
- effective(fields, stored, db=None) -> dict: every field, its stored value when still
valid, else its default. What GET /api/devices/me returns, so a screen never handles
a missing or stale value (an old free-form config, a prep zone that was deleted).
- for_app(app_key) -> the app's ConfigFields (from its manifest's DeviceApp.config).
Agent notes:
- Fields are declared in the app's manifest (core/modules/model.py ConfigField). A new
field needs its label in packages/i18n/locales/{en,el}/modules.json
(`<app>.config.<key>.label`, plus `.choices.<value>` per choice); test_module_texts fails
otherwise. The manager renders the fields generically (DeviceConfigFields.jsx).
- `ref` sources: "prep_zones" (PrepZone ids), "devices:<app_key>" (live devices of that app).
"""
from __future__ import annotations
from core.errors import XeniaError
MAX_STR = 200
def for_app(app_key: str) -> tuple:
from core.access.context import device_app
da = device_app(app_key)
return tuple(da.config) if da else ()
def _bad(key: str):
return XeniaError("validation.device_config", key=key)
def _ref_exists(source: str, value: int, db) -> bool:
if source == "prep_zones":
from models.prep_zone import PrepZone
return db.get(PrepZone, value) is not None
if source.startswith("devices:"):
from models.device import Device
d = db.get(Device, value)
return d is not None and d.revoked_at is None and d.app_key == source.split(":", 1)[1]
return False
def _clean(f, value, db, *, strict: bool):
"""The value as stored, or raise (strict) / return the default (not strict)."""
def bad():
if strict:
raise _bad(f.key)
return f.default
if f.type == "bool":
return value if isinstance(value, bool) else bad()
if f.type == "int":
if isinstance(value, bool) or not isinstance(value, int):
return bad()
if (f.choices and value not in f.choices) or (f.min is not None and value < f.min) \
or (f.max is not None and value > f.max):
return bad()
return value
if f.type == "str":
return value.strip() if isinstance(value, str) and len(value) <= MAX_STR else bad()
if f.type == "enum":
return value if value in f.choices else bad()
if f.type == "ref":
if value is None:
return None
if isinstance(value, bool) or not isinstance(value, int):
return bad()
if db is not None and not _ref_exists(f.choices_from or "", value, db):
return bad()
return value
return bad()
def validate(fields, config, db) -> dict | None:
if config is None:
return None
if not isinstance(config, dict):
raise _bad("config")
by_key = {f.key: f for f in fields}
out = {}
for key, value in config.items():
f = by_key.get(key)
if f is None:
raise _bad(key)
out[key] = _clean(f, value, db, strict=True)
return out or None
def effective(fields, stored, db=None) -> dict:
stored = stored if isinstance(stored, dict) else {}
return {f.key: (_clean(f, stored[f.key], db, strict=False) if f.key in stored else f.default) for f in fields}
def describe(fields) -> list[dict]:
"""The fields for the manager (module catalogue)."""
return [{"key": f.key, "type": f.type, "default": f.default, "choices": list(f.choices),
"min": f.min, "max": f.max, "choices_from": f.choices_from} for f in fields]
+19
View File
@@ -54,11 +54,30 @@ class SettingDef:
choices: tuple[str, ...] = () # for type "enum"
ConfigType = Literal["bool", "int", "str", "enum", "ref"]
@dataclass(frozen=True)
class ConfigField:
"""One setting of a device running an app (plan step 3.1a). Stored in devices.config,
validated by core/modules/device_config.py, edited in the manager's pair/edit dialogs.
Texts: modules:<app>.config.<key>.label (+ .hint optional, + .choices.<value> for each
choice), checked by tests/test_module_texts.py."""
key: str
type: ConfigType
default: object = None
choices: tuple = () # enum, or int limited to these values
min: Optional[int] = None # int
max: Optional[int] = None # int
choices_from: Optional[str] = None # ref: "prep_zones" | "devices:<app_key>"; value = id or None
@dataclass(frozen=True)
class DeviceApp:
"""For kind="app" modules that run on a paired device (step 1.8, D-8)."""
login_modes: tuple[str, ...] = ("pin", "tap", "password")
scope: tuple[str, ...] = () # permission-key patterns the device token may use
config: tuple[ConfigField, ...] = () # per-device settings (3.1a)
@dataclass(frozen=True)
+3
View File
@@ -21,6 +21,7 @@ Agent notes:
device_id binds it to that device, and a new login on the device replaces the old one),
"support" (1.10).
- Never trust a JWT alone: always go through validate().
- Ending a session also closes its live sockets (services.ws_bus.end_session, plan 3.1a).
"""
from __future__ import annotations
@@ -100,6 +101,8 @@ def _end_row(row, reason: str) -> None:
row.end_reason = reason
with _lock:
_cache.pop(row.id, None)
from services import ws_bus
ws_bus.end_session(row.id, reason) # its open sockets get session.ended and close (3.1a)
logger.info("session.ended sid=%s user=%s client=%s reason=%s", row.id[:8], row.user_id, row.client, reason)
@@ -0,0 +1,24 @@
"""sync_events.target_device_ids: live events addressed to paired devices (plan step 3.1a)
Revision ID: 0014_sync_event_devices
Revises: 0013_product_categories
Create Date: 2026-11-14 18:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0014_sync_event_devices'
down_revision = '0013_product_categories'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('sync_events', schema=None) as batch_op:
batch_op.add_column(sa.Column('target_device_ids', sa.Text(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('sync_events', schema=None) as batch_op:
batch_op.drop_column('target_device_ids')
+2 -1
View File
@@ -19,5 +19,6 @@ class SyncEvent(Base):
id = Column(Integer, primary_key=True)
event_type = Column(String, nullable=False)
payload = Column(Text, nullable=False)
target_user_ids = Column(Text, nullable=True)
target_user_ids = Column(Text, nullable=True) # JSON list; NULL = not addressed to users
target_device_ids = Column(Text, nullable=True) # JSON list of devices (plan 3.1a); NULL = none
created_at = Column(UTCDateTime, nullable=False, index=True)
+7 -2
View File
@@ -1,5 +1,9 @@
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
from core.modules.model import DeviceApp, Limit, Module, Mount, Perm
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm
# Back to the sign-in screen after this many idle minutes (shared screens; 0 = never). Used by
# the terminal from step 3.1c.
AUTO_SIGN_OUT = ConfigField('auto_sign_out_minutes', 'int', default=0, choices=(0, 2, 5, 10, 30, 60))
MODULE = Module(
key='kds',
@@ -14,7 +18,8 @@ MODULE = Module(
limits=(
Limit('devices', 'Number of kitchen screens', free=0, licensed_default=1),
),
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('kds.*',)),
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('kds.*',),
config=(AUTO_SIGN_OUT,)),
routers=(
Mount('routers.kds', '/api/kds'),
),
@@ -1,5 +1,9 @@
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
from core.modules.model import DeviceApp, Limit, Module, Perm
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Perm
# Back to the sign-in screen after this many idle minutes (shared screens; 0 = never). Used by
# the terminal from step 3.1c.
AUTO_SIGN_OUT = ConfigField('auto_sign_out_minutes', 'int', default=0, choices=(0, 2, 5, 10, 30, 60))
MODULE = Module(
key='pos_counter',
@@ -13,5 +17,6 @@ MODULE = Module(
limits=(
Limit('devices', 'Number of counter terminals', free=0, licensed_default=1),
),
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('pos_counter.*', 'ordering.*')),
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('pos_counter.*', 'ordering.*'),
config=(AUTO_SIGN_OUT,)),
)
+25 -5
View File
@@ -19,6 +19,11 @@ Agent notes:
sessions ended). Rows are never deleted.
- Login on a device: POST /api/auth/login {client: "terminal", ...} with the device header
(routers/auth.py). The login mode is effective_login_mode(); tap/none exist only here.
- `config` is validated against the app's ConfigFields (core/modules/device_config.py,
3.1a); both views return the effective config (every field, defaults filled).
- Live (3.1a): an edit sends `device.updated` to the device's open sockets; reassign sends
`device.updated` and closes them; revoke sends `device.revoked` and closes them
(services/ws_bus.py). The screen re-reads GET /me or goes back to pairing.
"""
from __future__ import annotations
@@ -36,12 +41,14 @@ from sqlalchemy.orm import Session
from core import sessions
from core.access.context import hash_token
from core.modules import device_config
from core.access.deps import public, require, require_device
from core.errors import XeniaError
from core.modules.registry import registry
from core.timeutil import iso_z, utcnow
from database import get_db
from models.device import Device, DevicePairRequest
from services import ws_bus
router = APIRouter()
@@ -143,6 +150,14 @@ def effective_login_mode(db, device) -> str:
return mode if mode in modes else modes[0]
def _config(app_key: str, config, db) -> dict | None:
return device_config.validate(device_config.for_app(app_key), config, db)
def _effective_config(d: Device, db) -> dict:
return device_config.effective(device_config.for_app(d.app_key), d.config, db)
def _get(db, device_id: int) -> Device:
d = db.get(Device, device_id)
if d is None:
@@ -153,7 +168,8 @@ def _get(db, device_id: int) -> Device:
def _out(d: Device, db) -> dict:
"""Manager view of a device."""
return {
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key, "config": d.config,
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key,
"config": _effective_config(d, db) if d.app_key in registry() else {},
"login_mode": d.login_mode,
"effective_login_mode": effective_login_mode(db, d) if d.app_key in registry() else None,
"linked_device_id": d.linked_device_id, "user_agent": d.user_agent,
@@ -169,7 +185,7 @@ def _self_out(d: Device, db) -> dict:
linked = db.get(Device, d.linked_device_id) if d.linked_device_id else None
status = "ok" if is_effective(d.app_key, db) else blocked_error(d.app_key, db).code
return {
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key, "config": d.config,
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key, "config": _effective_config(d, db),
"login_mode": effective_login_mode(db, d),
"linked_device": ({"id": linked.id, "uuid": linked.uuid, "name": linked.name, "app_key": linked.app_key}
if linked is not None and linked.revoked_at is None else None),
@@ -262,7 +278,8 @@ def approve_device(body: PairApprove, db: Session = Depends(get_db), user=Depend
_app(body.app_key)
_require_effective(body.app_key, db)
_check_limit(db, body.app_key)
d = Device(uuid=uuidlib.uuid4().hex, name=body.name.strip(), app_key=body.app_key, config=body.config,
d = Device(uuid=uuidlib.uuid4().hex, name=body.name.strip(), app_key=body.app_key,
config=_config(body.app_key, body.config, db),
login_mode=_check_mode(body.app_key, body.login_mode),
linked_device_id=_check_link(db, None, body.linked_device_id),
user_agent=row.user_agent, paired_at=now, paired_by=getattr(user, "id", None) or None)
@@ -308,12 +325,13 @@ def update_device(device_id: int, body: DevicePatch, db: Session = Depends(get_d
if "name" in sent and body.name:
d.name = body.name.strip()
if "config" in sent:
d.config = body.config
d.config = _config(d.app_key, body.config, db)
if "login_mode" in sent:
d.login_mode = _check_mode(d.app_key, body.login_mode)
if "linked_device_id" in sent:
d.linked_device_id = _check_link(db, d.id, body.linked_device_id)
db.commit()
ws_bus.notify_device([d.id])
return _out(d, db)
@@ -328,11 +346,12 @@ def reassign_device(device_id: int, body: DeviceReassign, db: Session = Depends(
_require_effective(body.app_key, db)
if body.app_key != d.app_key:
_check_limit(db, body.app_key, exclude_id=d.id)
d.config = _config(body.app_key, body.config, db)
d.app_key = body.app_key
d.config = body.config
if d.login_mode and d.login_mode not in _app(body.app_key).device_app.login_modes:
d.login_mode = None
db.commit()
ws_bus.end_device(d.id, "device.updated", {"app_key": d.app_key}) # before the session's own close
sessions.end_for_device(db, d.id, "device_reassigned")
return _out(d, db)
@@ -347,5 +366,6 @@ def revoke_device(device_id: int, db: Session = Depends(get_db), user=Depends(re
db.query(Device).filter(Device.linked_device_id == d.id).update({Device.linked_device_id: None})
db.query(DevicePairRequest).filter(DevicePairRequest.device_id == d.id).delete()
db.commit()
ws_bus.end_device(d.id, "device.revoked")
sessions.end_for_device(db, d.id, "device_revoked")
return _out(d, db)
+121 -45
View File
@@ -1,19 +1,36 @@
"""
WebSocket endpoint — one persistent connection per connected client (waiter PWA, KDS).
Authentication: JWT token passed as query param ?token=<jwt>
(Same pattern as SSE — browser WebSocket API also cannot set custom headers.)
WebSocket endpoint — one persistent connection per client (waiter app, manager, terminal).
Protocol:
1. Client connects: ws://host/api/ws?token=<jwt>
2. Client immediately sends: { "cursor": <last_seq_id> }
(0 = first connect / no history; any positive int = resume from that point)
3. Server replays all missed events (seq > cursor) as individual frames
4. Server sends { "type": "ready" } to signal end of replay / start of live stream
5. Live events arrive as: { "seq": 123, "type": "...", "data": { ... } }
6. Every 25s server sends: { "type": "ping" }
7. Client may respond: { "type": "pong" } (ignored if not sent)
8. On disconnect/error the client reconnects and repeats from step 2
1. Client connects: ws://host/api/ws/connect (terminal: no query)
or: ws://host/api/ws/connect?token=<jwt> (waiter, manager)
2. Client immediately sends its first frame:
{ "cursor": <last_seq_id>, "token"?: <jwt>, "device"?: <device token> }
(cursor 0 = first connect / no history). Credentials in the frame stay out of URLs
and proxy logs; the terminal always sends them there.
3. Server checks who it is (below). Refused → { "type": "refused", "data": {code} }
and close code 4001 (sign in again) or 4003 (device problem).
4. Server replays missed events the socket may see (seq > cursor) as individual frames
5. Server sends { "type": "ready" } to signal end of replay / start of live stream
6. Live events arrive as: { "seq": 123, "type": "...", "data": { ... } }
7. Every 25s server sends: { "type": "ping" }; the client may answer { "type": "pong" }
8. Control frames (no seq): `device.updated` (re-read /api/devices/me); and before the
server closes the socket itself: `session.ended` (4001), `device.revoked` or
`device.updated` after an app change (4003).
9. On disconnect/error the client reconnects and repeats from step 2
Who may connect (plan step 3.1a, D-8):
- a user session JWT alone (manager, waiter). A terminal session's JWT (bound to a device)
only together with that device's token, like routers.deps.user_from_token over HTTP.
- a device token alone: a paired screen without a signed-in user. If its app signs nobody
in (login mode `none`: customer display, signage, menu tablet) it gets every event;
otherwise (a KDS on its sign-in screen) only events addressed to the device.
- a device token + a terminal JWT of that device: everything a user socket gets.
Agent notes:
- Auth uses a short-lived DB session (the app's get_db, so tests' override applies) that
is closed before streaming starts: an open socket holds no DB connection.
- Never log tokens.
"""
from core.access.deps import public
@@ -24,44 +41,99 @@ import logging
from fastapi import Depends, APIRouter, WebSocket, WebSocketDisconnect, Query
from starlette.websockets import WebSocketState
from routers.deps import decode_token
from services.ws_bus import connect, disconnect, get_events_since
from core.errors import XeniaError
from database import get_db
from services import ws_bus
router = APIRouter()
logger = logging.getLogger(__name__)
KEEPALIVE_INTERVAL = 25 # seconds
FIRST_FRAME_TIMEOUT = 10.0
class Refused(Exception):
def __init__(self, code: str, close: int):
super().__init__(code)
self.code, self.close = code, close
def _with_db(app, fn):
"""Run fn(db) with a DB session from the app's get_db (honours dependency overrides)."""
gen = app.dependency_overrides.get(get_db, get_db)()
db = next(gen)
try:
return fn(db)
finally:
gen.close()
def authenticate(db, token: str | None, device_token: str | None) -> dict:
"""-> kwargs for ws_bus.connect(). Raises Refused."""
from core.access.context import lookup_device
from routers.deps import decode_session
device = None
if device_token:
try:
device = lookup_device(db, device_token)
except XeniaError as e:
raise Refused(e.code, ws_bus.CLOSE_DEVICE)
if token:
try:
payload, info = decode_session(token, db)
except XeniaError as e:
raise Refused(e.code, ws_bus.CLOSE_SESSION)
except Exception:
raise Refused("auth.session_ended", ws_bus.CLOSE_SESSION)
if info.device_id is not None and (device is None or device.id != info.device_id):
raise Refused("device.required", ws_bus.CLOSE_DEVICE)
user_id = info.user_id if info.user_id is not None else 0 # 0 = the support account
if info.user_id is not None:
from models.user import User
if db.query(User.id).filter(User.id == info.user_id, User.is_active == True).first() is None: # noqa: E712
raise Refused("auth.session_ended", ws_bus.CLOSE_SESSION)
return {"user_id": user_id, "sid": payload.get("sid"),
"device_id": device.id if device else None, "app_key": device.app_key if device else None}
if device is None:
raise Refused("auth.session_ended", ws_bus.CLOSE_SESSION)
from routers.devices import effective_login_mode
signs_nobody_in = effective_login_mode(db, device) == "none"
return {"device_id": device.id, "app_key": device.app_key, "all_events": signs_nobody_in}
@router.websocket("/connect", dependencies=[Depends(public())])
async def ws_endpoint(websocket: WebSocket, token: str = Query(...)):
# ── Auth ──────────────────────────────────────────────────────────────────
try:
payload = decode_token(token)
user_id: int = int(payload["sub"])
except Exception:
await websocket.close(code=4001)
return
async def ws_endpoint(websocket: WebSocket, token: str | None = Query(None)):
await websocket.accept()
# ── Wait for cursor frame ─────────────────────────────────────────────────
cursor = 0
# ── First frame: cursor (+ credentials) ───────────────────────────────────
cursor, device_token = 0, None
try:
raw = await asyncio.wait_for(websocket.receive_text(), timeout=10.0)
msg = json.loads(raw)
cursor = int(msg.get("cursor", 0))
except (asyncio.TimeoutError, Exception):
pass # no cursor sent — treat as fresh connect (cursor=0)
msg = json.loads(await asyncio.wait_for(websocket.receive_text(), timeout=FIRST_FRAME_TIMEOUT))
if isinstance(msg, dict):
cursor = int(msg.get("cursor") or 0)
token = msg.get("token") or token
device_token = msg.get("device") or None
except WebSocketDisconnect:
return
except Exception:
pass # no (valid) first frame: fresh connect, credentials from the query only
# ── Register this connection ──────────────────────────────────────────────
q = await connect(user_id)
# ── Auth ──────────────────────────────────────────────────────────────────
try:
who = await asyncio.to_thread(_with_db, websocket.app, lambda db: authenticate(db, token, device_token))
except Refused as r:
try:
await websocket.send_text(json.dumps({"type": "refused", "data": {"code": r.code}}))
await websocket.close(code=r.close)
except Exception:
pass
return
conn = await ws_bus.connect(**who)
try:
# ── Replay missed events ──────────────────────────────────────────────
if cursor > 0:
missed = get_events_since(cursor, user_id)
for event in missed:
for event in await asyncio.to_thread(ws_bus.get_events_since, cursor, conn):
await websocket.send_text(json.dumps(event))
# Signal end of replay / start of live stream
@@ -69,20 +141,24 @@ async def ws_endpoint(websocket: WebSocket, token: str = Query(...)):
# ── Live stream loop ──────────────────────────────────────────────────
while True:
if conn.closing is not None:
frame, code = conn.closing
await websocket.send_text(frame)
await websocket.close(code=code)
break
try:
frame = await asyncio.wait_for(q.get(), timeout=KEEPALIVE_INTERVAL)
if websocket.client_state == WebSocketState.CONNECTED:
await websocket.send_text(frame)
frame = await asyncio.wait_for(conn.queue.get(), timeout=KEEPALIVE_INTERVAL)
except asyncio.TimeoutError:
# Send keepalive ping
if websocket.client_state == WebSocketState.CONNECTED:
await websocket.send_text(json.dumps({"type": "ping"}))
else:
break
frame = json.dumps({"type": "ping"})
if frame is None or conn.closing is not None:
continue # a wake-up: the loop head sends the closing frame
if websocket.client_state != WebSocketState.CONNECTED:
break
await websocket.send_text(frame)
except WebSocketDisconnect:
pass
except Exception as e:
logger.debug("ws_endpoint: connection closed for user %s: %s", user_id, e)
logger.debug("ws_endpoint: connection closed (user %s, device %s): %s", conn.user_id, conn.device_id, e)
finally:
await disconnect(user_id, q)
await ws_bus.disconnect(conn)
+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)
+2 -2
View File
@@ -63,7 +63,7 @@ def test_pairing_flow(client, owner_h):
# the manager types the code (case and dashes don't matter)
typed = f"{code[:3].lower()}-{code[3:]}"
r = client.post("/api/devices", headers=owner_h,
json={"code": typed, "app_key": "kds", "name": "Bar KDS", "config": {"prep_zone_id": 2}})
json={"code": typed, "app_key": "kds", "name": "Bar KDS", "config": {"auto_sign_out_minutes": 5}})
assert r.status_code == 201, r.text
d = r.json()
assert d["claimed"] is False and d["user_agent"] == "KDS-Box" and d["effective_login_mode"] == "pin"
@@ -74,7 +74,7 @@ def test_pairing_flow(client, owner_h):
poll = client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})
assert poll.status_code == 200
token = poll.json()["device_token"]
assert poll.json()["device"]["config"] == {"prep_zone_id": 2} and poll.json()["device"]["app_status"] == "ok"
assert poll.json()["device"]["config"] == {"auto_sign_out_minutes": 5} and poll.json()["device"]["app_status"] == "ok"
# the token is handed out exactly once
assert err(client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})) \
== "device.pair_code_invalid"
+236
View File
@@ -0,0 +1,236 @@
"""Live connection for users and paired devices, device config (plan step 3.1a)."""
import pytest
from starlette.websockets import WebSocketDisconnect
from conftest import TEST_PIN
from core.modules import device_config
from core.modules.model import ConfigField
from services import ws_bus
WS = "/api/ws/connect"
def err(r):
return r.json()["error"]["code"]
@pytest.fixture
def owner_h(make_user, login):
return login(make_user(role="owner"))
@pytest.fixture
def pair(client, owner_h):
def _pair(app_key, name=None, **fields):
req = client.post("/api/devices/pair-request").json()
r = client.post("/api/devices", headers=owner_h,
json={"code": req["code"], "app_key": app_key, "name": name or f"{app_key} screen", **fields})
if r.status_code != 201:
return None, r
poll = client.get(f"/api/devices/pair-request/{req['code']}", headers={"X-Xenia-Pair-Secret": req["secret"]})
return poll.json()["device_token"], r
return _pair
def terminal_login(client, token, user):
r = client.post("/api/auth/login", headers={"X-Xenia-Device": token},
json={"client": "terminal", "user_id": user.id, "pin": TEST_PIN})
assert r.status_code == 200, r.text
return r.json()["access_token"]
def open_ws(client, **first):
ws = client.websocket_connect(WS)
sock = ws.__enter__()
sock.send_json({"cursor": 0, **first})
return ws, sock
def expect_ready(sock):
assert sock.receive_json() == {"type": "ready"}
def expect_refused(client, code, close, **first):
ws, sock = open_ws(client, **first)
try:
assert sock.receive_json() == {"type": "refused", "data": {"code": code}}
with pytest.raises(WebSocketDisconnect) as e:
sock.receive_json()
assert e.value.code == close
finally:
ws.__exit__(None, None, None)
def expect_closed(sock, close):
with pytest.raises(WebSocketDisconnect) as e:
sock.receive_json()
assert e.value.code == close
# ── who may connect ──────────────────────────────────────────────────────────
def test_user_token_in_query_still_works(client, make_user, login):
h = login(make_user(role="waiter"), "waiter")
with client.websocket_connect(f"{WS}?token={h['Authorization'][7:]}") as sock:
sock.send_json({"cursor": 0})
expect_ready(sock)
ws_bus.broadcast_sync("order_updated", {"order_id": 1})
assert sock.receive_json() == {"seq": 0, "type": "order_updated", "data": {"order_id": 1}}
def test_nothing_or_garbage_is_refused(client):
expect_refused(client, "auth.session_ended", 4001)
expect_refused(client, "auth.session_ended", 4001, token="nope")
expect_refused(client, "device.not_paired", 4003, device="nope")
def test_device_only_socket_of_a_login_none_app_gets_events(client, pair): # "done when" 1
token, _ = pair("customer_display")
ws, sock = open_ws(client, device=token)
try:
expect_ready(sock)
ws_bus.broadcast_sync("product_updated", {"id": 7})
assert sock.receive_json()["type"] == "product_updated"
finally:
ws.__exit__(None, None, None)
def test_device_only_socket_of_a_sign_in_app_gets_only_its_own_events(client, pair):
token, r = pair("kds")
dev_id = r.json()["id"]
other, r2 = pair("kds", "other")
ws, sock = open_ws(client, device=token)
try:
expect_ready(sock)
ws_bus.broadcast_sync("order_updated", {"order_id": 1}) # needs a signed-in chef
ws_bus.broadcast_sync("for_other", {}, device_ids=[r2.json()["id"]])
ws_bus.broadcast_sync("display", {"n": 1}, device_ids=[dev_id])
assert sock.receive_json() == {"seq": 0, "type": "display", "data": {"n": 1}}
finally:
ws.__exit__(None, None, None)
def test_terminal_jwt_needs_its_device(client, pair, make_user): # "done when" 2
token, _ = pair("kds")
other, _ = pair("kds", "other")
jwt = terminal_login(client, token, make_user(role="chef"))
expect_refused(client, "device.required", 4003, token=jwt)
expect_refused(client, "device.required", 4003, token=jwt, device=other)
ws, sock = open_ws(client, token=jwt, device=token)
try:
expect_ready(sock)
ws_bus.broadcast_sync("order_updated", {"order_id": 2}) # a chef sees everything
assert sock.receive_json()["type"] == "order_updated"
finally:
ws.__exit__(None, None, None)
def test_revoking_a_device_closes_its_sockets(client, pair, owner_h, make_user): # "done when" 3
token, r = pair("kds")
dev_id = r.json()["id"]
jwt = terminal_login(client, token, make_user(role="chef"))
ws1, user_sock = open_ws(client, token=jwt, device=token)
ws2, dev_sock = open_ws(client, device=token)
try:
expect_ready(user_sock)
expect_ready(dev_sock)
assert client.post(f"/api/devices/{dev_id}/revoke", headers=owner_h).status_code == 200
for sock in (user_sock, dev_sock):
assert sock.receive_json() == {"type": "device.revoked", "data": {"device_id": dev_id}}
expect_closed(sock, 4003)
finally:
ws1.__exit__(None, None, None)
ws2.__exit__(None, None, None)
expect_refused(client, "device.revoked", 4003, device=token)
def test_ending_a_session_closes_its_socket(client, make_user, login, owner_h):
w = make_user(role="waiter")
h = login(w, "waiter")
ws, sock = open_ws(client, token=h["Authorization"][7:])
try:
expect_ready(sock)
sid = next(s for s in client.get("/api/auth/sessions", headers=owner_h).json() if s["user_id"] == w.id)["id"]
assert client.post(f"/api/auth/sessions/{sid}/end", headers=owner_h).status_code == 200
msg = sock.receive_json()
assert msg["type"] == "session.ended" and msg["data"]["reason"]
expect_closed(sock, 4001)
finally:
ws.__exit__(None, None, None)
def test_reassign_and_edit_tell_the_device(client, pair, owner_h):
token, r = pair("kds")
dev_id = r.json()["id"]
ws, sock = open_ws(client, device=token)
try:
expect_ready(sock)
assert client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"name": "Grill"}).status_code == 200
assert sock.receive_json() == {"type": "device.updated", "data": {"device_id": dev_id}}
assert client.put("/api/platform/modules/tabs", headers=owner_h, json={"enabled": False}).status_code == 200
assert sock.receive_json()["type"] == "device.updated"
assert client.post(f"/api/devices/{dev_id}/reassign", headers=owner_h,
json={"app_key": "pos_counter"}).status_code == 200
assert sock.receive_json() == {"type": "device.updated", "data": {"device_id": dev_id, "app_key": "pos_counter"}}
expect_closed(sock, 4003)
finally:
ws.__exit__(None, None, None)
# ── device config ────────────────────────────────────────────────────────────
def test_config_validated_and_effective(client, pair, owner_h): # "done when" 4
_, r = pair("kds", config={"auto_sign_out_minutes": 7})
assert r.status_code == 422 and err(r) == "validation.device_config"
assert r.json()["error"]["params"] == {"key": "auto_sign_out_minutes"}
_, r = pair("kds", config={"colour": "red"})
assert err(r) == "validation.device_config"
token, r = pair("kds")
assert r.json()["config"] == {"auto_sign_out_minutes": 0} # defaults filled
dev_id = r.json()["id"]
r = client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"config": {"auto_sign_out_minutes": 5}})
assert r.status_code == 200 and r.json()["config"] == {"auto_sign_out_minutes": 5}
assert client.get("/api/devices/me", headers={"X-Xenia-Device": token}).json()["config"] \
== {"auto_sign_out_minutes": 5}
assert err(client.patch(f"/api/devices/{dev_id}", headers=owner_h,
json={"config": {"auto_sign_out_minutes": True}})) == "validation.device_config"
# an app without config fields refuses any key
r = client.post(f"/api/devices/{dev_id}/reassign", headers=owner_h,
json={"app_key": "customer_display", "config": {"auto_sign_out_minutes": 5}})
assert err(r) == "validation.device_config"
def test_module_catalogue_describes_config(client, owner_h):
mods = {m["key"]: m for m in client.get("/api/platform/modules", headers=owner_h).json()["modules"]}
assert mods["kds"]["device_app"]["config"] == [{"key": "auto_sign_out_minutes", "type": "int", "default": 0,
"choices": [0, 2, 5, 10, 30, 60], "min": None, "max": None,
"choices_from": None}]
assert mods["customer_display"]["device_app"]["config"] == []
def test_config_field_types(db, pair):
from models.prep_zone import PrepZone
zone = PrepZone(name="Grill")
db.add(zone)
db.commit()
_, r = pair("pos_counter")
pos_id = r.json()["id"]
fields = (ConfigField("zone", "ref", choices_from="prep_zones"),
ConfigField("pos", "ref", choices_from="devices:pos_counter"),
ConfigField("sound", "bool", default=True),
ConfigField("layout", "enum", default="grid", choices=("grid", "list")),
ConfigField("scale", "int", default=100, min=50, max=200),
ConfigField("title", "str", default=""))
ok = {"zone": zone.id, "pos": pos_id, "sound": False, "layout": "list", "scale": 150, "title": " Bar "}
assert device_config.validate(fields, ok, db) == {**ok, "title": "Bar"}
assert device_config.validate(fields, {}, db) is None
for bad in ({"zone": 99999}, {"pos": zone.id + 99999}, {"sound": "yes"}, {"layout": "tiles"},
{"scale": 10}, {"scale": 1.5}, {"title": 5}):
with pytest.raises(Exception) as e:
device_config.validate(fields, bad, db)
assert e.value.code == "validation.device_config"
# stale stored values fall back to the default; missing keys get theirs
eff = device_config.effective(fields, {"zone": 99999, "layout": "tiles", "scale": 120}, db)
assert eff == {"zone": None, "pos": None, "sound": True, "layout": "grid", "scale": 120, "title": ""}
assert device_config.effective(fields, "junk") == {f.key: f.default for f in fields}
+19
View File
@@ -46,3 +46,22 @@ def test_every_permission_has_a_label(lang):
yield from (leaves(f"{prefix}.{k}", v) if isinstance(v, dict) else [f"{prefix}.{k}"])
labelled = {k for mod, t in texts.items() for k in leaves(mod, t.get("permissions", {}))}
assert labelled - known == set(), "labels for permissions that don't exist"
@pytest.mark.parametrize("lang", ["en", "el"])
def test_every_device_config_field_has_texts(lang):
"""modules:<app>.config.<key>.label, and .choices.<value> for every choice (plan step 3.1a)."""
texts = json.loads((LOCALES / lang / "modules.json").read_text(encoding="utf-8"))
missing, known = [], set()
for m in registry().values():
for f in (m.device_app.config if m.device_app else ()):
t = texts.get(m.key, {}).get("config", {}).get(f.key, {})
if not t.get("label"):
missing.append(f"{m.key}.config.{f.key}.label")
for c in f.choices:
if not t.get("choices", {}).get(str(c)):
missing.append(f"{m.key}.config.{f.key}.choices.{c}")
known.add((m.key, f.key))
assert missing == []
extra = {(mod, k) for mod, t in texts.items() for k in t.get("config", {})} - known
assert extra == set(), "texts for device settings that don't exist"