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:
@@ -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
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user