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
@@ -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):