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>
This commit is contained in:
2026-11-16 10:49:21 +02:00
co-authored by Claude Opus 5.5
parent d0c6a10e47
commit f85894a72e
43 changed files with 112 additions and 350 deletions
+1 -1
View File
@@ -102,7 +102,7 @@ def notify(key: str, severity: str, audience: str, params: dict | None = None, *
db.commit()
logger.info("notification.created id=%s key=%s audience=%s", row.id, key, audience)
try:
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
broadcast_sync(EVENT, {"id": row.id}, user_ids=recipients(db, audience))
except Exception:
logger.exception("notification.event_failed id=%s", row.id)
-2
View File
@@ -43,12 +43,10 @@ def _init_chat():
@asynccontextmanager
async def lifespan(app: FastAPI):
import asyncio
from services.sse_bus import init_loop as sse_init_loop
from services.ws_bus import init_loop as ws_init_loop, prune_old_events
from services.reservation_tasks import start_reservation_tasks
from services.printer_service import start_print_retry_thread
loop = asyncio.get_running_loop()
sse_init_loop(loop)
ws_init_loop(loop)
# Schema = Alembic revisions only (core/schema.py, APPS_PLATFORM D-13). Refuses v1 databases.
from core.schema import upgrade_to_head
-1
View File
@@ -41,7 +41,6 @@ MODULE = Module(
Mount('routers.waiters', '/api/waiters'),
Mount('routers.system', '/api/system'),
Mount('routers.settings', '/api/settings'),
Mount('routers.sse', '/api/sse'),
Mount('routers.ws', '/api/ws'),
Mount('routers.recovery', '/api/recovery'),
Mount('routers.devices', '/api/devices'),
+1 -1
View File
@@ -20,7 +20,7 @@ from schemas.chat import (
MessageOut,
ParticipantOut,
)
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
router = APIRouter()
+1 -1
View File
@@ -38,7 +38,7 @@ from core.timeutil import utcnow
from database import get_db
from models.order import Order, OrderItem
from schemas.order import OrderItemOut, OrderOut
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
logger = logging.getLogger(__name__)
router = APIRouter()
+1 -1
View File
@@ -236,7 +236,7 @@ def _apply_rule(rule, body: RuleBody):
def _changed():
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
broadcast_sync("fees_changed", {})
+1 -1
View File
@@ -7,7 +7,7 @@ from models.flag import TableFlagDef, TableFlagAssignment
from schemas.flag import FlagDefCreate, FlagDefUpdate, FlagDefOut, FlagAssignmentOut, SetTableFlagsRequest
from routers.deps import get_current_user, require_manager
from models.user import User
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
router = APIRouter()
+1 -1
View File
@@ -58,7 +58,7 @@ from core.access.context import current_device
from core.modules import device_config
from core.access.deps import require
from routers.deps import get_current_user, require_kds
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
router = APIRouter(dependencies=[Depends(require_kds)])
+1 -1
View File
@@ -11,7 +11,7 @@ from schemas.message import (
QuickTemplateCreate, QuickTemplateUpdate, QuickTemplateOut,
)
from routers.deps import get_current_user, require_manager
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
router = APIRouter()
+1 -1
View File
@@ -55,7 +55,7 @@ class RevertPaymentRequest(BaseModel):
from routers.deps import get_current_user, require_manager
from services.printer_service import route_and_print, route_and_print_sync, print_order_receipt, print_order_synopsis, print_cancellation_ticket
from models.settings import PosSettings
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
router = APIRouter()
+1 -1
View File
@@ -624,7 +624,7 @@ def pos_refund(order_id: int, body: RefundBody, request: Request, db: Session =
→ {refund_id, order_id, amount, method, drawer, fiscal}"""
from models.order import Order, OrderItem
from services import fiscal, refunds
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
+1 -1
View File
@@ -606,7 +606,7 @@ def accept_deal_offer(
))
db.commit()
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
broadcast_sync()
return {
+1 -1
View File
@@ -21,7 +21,7 @@ from schemas.product import (
CategoryReparentRequest, ModifierGroupCreate, ModifierGroupOut,
)
from routers.deps import get_current_user, require_menu_manager
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
router = APIRouter()
-61
View File
@@ -1,61 +0,0 @@
"""
SSE stream endpoint — one long-lived GET per connected phone.
Authentication: token passed as query param ?token=<jwt>
(EventSource API in browsers cannot set custom headers, so query param is the standard pattern.)
The client receives a stream of JSON lines:
data: {"type": "...", "data": {...}}\n\n
A keepalive comment (": ping") is sent every 25 seconds to prevent proxy timeouts.
"""
from core.access.deps import public
import asyncio
from fastapi import Depends, APIRouter, Query
from fastapi.responses import StreamingResponse
from routers.deps import decode_token
from services.sse_bus import subscribe, unsubscribe
router = APIRouter()
KEEPALIVE_INTERVAL = 25 # seconds
async def _event_stream(user_id: int):
q = await subscribe(user_id)
try:
while True:
try:
payload = await asyncio.wait_for(q.get(), timeout=KEEPALIVE_INTERVAL)
yield f"data: {payload}\n\n"
except asyncio.TimeoutError:
# keepalive — prevents nginx/proxies from closing idle connections
yield ": ping\n\n"
except asyncio.CancelledError:
pass
finally:
await unsubscribe(user_id, q)
@router.get("/stream", dependencies=[Depends(public())])
async def sse_stream(token: str = Query(...)):
"""
Open an SSE stream for the authenticated user.
The phone connects once on login and stays connected.
On reconnect (after network drop) it does a full GET first, then reconnects here.
"""
# decode_token raises HTTPException on invalid/expired — no manual check needed
payload = decode_token(token)
user_id: int = int(payload["sub"])
return StreamingResponse(
_event_stream(user_id),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no", # disable nginx buffering
"Connection": "keep-alive",
},
)
+1 -1
View File
@@ -16,7 +16,7 @@ from schemas.table import (
TableBatchCreate, MAX_TABLE_NAME_LENGTH,
)
from routers.deps import get_current_user, require_tables_manager
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
# Tables with a pending reservation due within this many hours get the RESERVED badge
RESERVATION_LOOKAHEAD_HOURS = 4
+10 -10
View File
@@ -2,12 +2,12 @@
WebSocket endpoint — one persistent connection per client (waiter app, manager, terminal).
Protocol:
1. Client connects: ws://host/api/ws/connect (terminal: no query)
or: ws://host/api/ws/connect?token=<jwt> (waiter, manager)
1. Client connects: ws://host/api/ws/connect (no query: a token in a URL ends up in
proxy and server logs; the `?token=` form was removed in phase 4.0)
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.
(cursor 0 = first connect / no history). Every client (waiter, manager, terminal)
sends its credentials here.
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
@@ -38,7 +38,7 @@ import asyncio
import json
import logging
from fastapi import Depends, APIRouter, WebSocket, WebSocketDisconnect, Query
from fastapi import Depends, APIRouter, WebSocket, WebSocketDisconnect
from starlette.websockets import WebSocketState
from core.errors import XeniaError
@@ -102,21 +102,21 @@ def authenticate(db, token: str | None, device_token: str | None) -> dict:
@router.websocket("/connect", dependencies=[Depends(public())])
async def ws_endpoint(websocket: WebSocket, token: str | None = Query(None)):
async def ws_endpoint(websocket: WebSocket):
await websocket.accept()
# ── First frame: cursor (+ credentials) ───────────────────────────────────
cursor, device_token = 0, None
# ── First frame: cursor + credentials ─────────────────────────────────────
cursor, token, device_token = 0, None, None
try:
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
token = msg.get("token") or None
device_token = msg.get("device") or None
except WebSocketDisconnect:
return
except Exception:
pass # no (valid) first frame: fresh connect, credentials from the query only
pass # no (valid) first frame: no credentials → refused below
# ── Auth ──────────────────────────────────────────────────────────────────
try:
+1 -1
View File
@@ -540,7 +540,7 @@ async def _pull_pending_orders():
return
from database import SessionLocal
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
db = SessionLocal()
booked, at_table = [], []
@@ -161,7 +161,7 @@ def fire(db, r) -> list | None:
def send_to_kitchen(db, order_id: int, item_ids: list) -> None:
"""Kitchen tickets and the KDS for a fired booking's order (after commit)."""
from services.printer_service import route_and_print_sync
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
if item_ids:
try:
route_and_print_sync(order_id, item_ids, db)
+1 -1
View File
@@ -80,7 +80,7 @@ def after(db, placed: dict, opener_id: int) -> None:
from core.i18n import t, venue_language
from routers.kds import _save_and_broadcast_message
from services.printer_service import route_and_print_sync
from services.sse_bus import broadcast_sync
from services.ws_bus import broadcast_sync
from services.table_qr import label
order, table, ids = placed["order"], placed["table"], placed["item_ids"]
try:
-90
View File
@@ -1,90 +0,0 @@
"""
SSE Event Bus — in-memory broadcaster for Server-Sent Events.
All routers import `broadcast_sync()` to push events from sync routes.
The SSE endpoint imports `subscribe()` / `unsubscribe()` to manage per-client queues.
Event shape (JSON-serialisable dict):
{ "type": "<event_type>", "data": { ... } }
Supported event types:
order_updated — order created / item added / transferred / merged
order_paid — items paid on an order
order_closed — order closed or cancelled
table_list_changed — table added/removed
table_flags_changed — flags set/cleared on a table
message_sent — new staff message (targeted or broadcast)
shift_changed — shift started / ended by manager
business_day_changed — business day opened / closed
"""
import asyncio
import json
from typing import Dict, Set
# Captured once at startup by init_loop() called from lifespan.
# Sync route threads use this to schedule coroutines safely.
_main_loop: asyncio.AbstractEventLoop | None = None
# waiter_id → set of asyncio.Queue (one per SSE connection for that user)
_queues: Dict[int, Set[asyncio.Queue]] = {}
def init_loop(loop: asyncio.AbstractEventLoop) -> None:
"""Call once from the FastAPI lifespan (async context) to capture the event loop."""
global _main_loop
_main_loop = loop
async def subscribe(user_id: int) -> asyncio.Queue:
q: asyncio.Queue = asyncio.Queue(maxsize=256)
if user_id not in _queues:
_queues[user_id] = set()
_queues[user_id].add(q)
return q
async def unsubscribe(user_id: int, q: asyncio.Queue) -> None:
if user_id in _queues:
_queues[user_id].discard(q)
if not _queues[user_id]:
del _queues[user_id]
def broadcast_sync(event_type: str, data: dict, *, user_ids: list[int] | None = None) -> None:
"""
Fire-and-forget broadcast from a synchronous FastAPI route (thread-pool worker).
Delegates to ws_bus which persists the event and pushes to WS clients.
Also pushes to legacy SSE clients so the old endpoint keeps working during transition.
"""
# WS bus handles persistence + WS delivery
from services.ws_bus import broadcast_sync as ws_broadcast_sync
ws_broadcast_sync(event_type, data, user_ids=user_ids)
# Legacy SSE push (no persistence needed — WS is the source of truth)
if _main_loop is None:
return
_main_loop.call_soon_threadsafe(
_main_loop.create_task,
broadcast(event_type, data, user_ids=user_ids),
)
async def broadcast(event_type: str, data: dict, *, user_ids: list[int] | None = None) -> None:
"""
Push an event to connected clients.
user_ids=None → broadcast to ALL connected users
user_ids=[...] → send only to those specific user IDs
"""
payload = json.dumps({"type": event_type, "data": data})
targets = (
{uid: qs for uid, qs in _queues.items() if uid in user_ids}
if user_ids is not None
else dict(_queues)
)
for qs in targets.values():
for q in list(qs):
try:
q.put_nowait(payload)
except asyncio.QueueFull:
pass # slow client — drop rather than block
+2 -2
View File
@@ -1,7 +1,7 @@
"""
WebSocket Event Bus — replaces sse_bus.py for real-time communication.
WebSocket Event Bus: every live event the backend sends (phase 4.0: the only one; SSE is gone).
Routers keep calling sse_bus.broadcast_sync() (which calls broadcast_sync() here).
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):
+1 -1
View File
@@ -72,7 +72,7 @@ def _no_event_persistence(monkeypatch):
"""services.ws_bus writes every broadcast to sync_events through its OWN connection,
which waits on the test's open transaction until SQLite's 5 s lock timeout (and then
fails quietly). Tests don't use the replay buffer, so the write is skipped here.
Tests about events capture services.sse_bus.broadcast_sync instead."""
Tests about events capture services.ws_bus.broadcast_sync instead."""
import services.ws_bus as ws_bus
monkeypatch.setattr(ws_bus, "_persist_event", lambda *a, **k: 0)
+8 -4
View File
@@ -69,13 +69,17 @@ def expect_closed(sock, close):
# ── who may connect ──────────────────────────────────────────────────────────
def test_user_token_in_query_still_works(client, make_user, login):
def test_a_token_in_the_address_is_ignored(client, make_user, login):
"""Phase 4.0: credentials only in the first frame (a token in a URL ends up in logs)."""
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}}
assert sock.receive_json()["type"] == "refused"
def test_the_sse_stream_is_gone(client, make_user, login):
h = login(make_user(role="waiter"), "waiter")
assert client.get(f"/api/sse/stream?token={h['Authorization'][7:]}").status_code == 404
def test_nothing_or_garbage_is_refused(client):
+2 -2
View File
@@ -12,8 +12,8 @@ URL = "/api/platform/notifications"
@pytest.fixture
def events(monkeypatch):
sent = []
import services.sse_bus as bus
monkeypatch.setattr(bus, "broadcast_sync", lambda t, d, user_ids=None: sent.append((t, d, sorted(user_ids or []))))
import services.ws_bus as bus
monkeypatch.setattr(bus, "broadcast_sync", lambda t, d, user_ids=None, device_ids=None: sent.append((t, d, sorted(user_ids or []))))
return sent