- /api/ws authentifiziert über das Session-Cookie, Origin-Pflicht gegen CSWSH - Hub im Prozess verteilt clip.created/updated/deleted an alle Geräte des Benutzers - Ereignisse erst nach erfolgreichem Commit (BackgroundTasks), keine bei Konflikt - Logout, Session-Widerruf, Passwortänderung und Admin-Aktionen schließen betroffene Verbindungen (4401); Session wird alle 5 Minuten neu geprüft - Heartbeat alle 30 s, höchstens 20 Verbindungen pro Benutzer - CSP erlaubt wss:// zur eigenen Domain, eingehende WS-Nachrichten max. 64 KiB Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
80 lines
2.5 KiB
Python
80 lines
2.5 KiB
Python
"""In-process registry of WebSocket connections, keyed by user.
|
|
|
|
All methods run on the event loop; sync request handlers reach them via BackgroundTasks.
|
|
This only works with a single worker process (see CLAUDE.md).
|
|
"""
|
|
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
from collections import defaultdict
|
|
from dataclasses import dataclass
|
|
from typing import Any
|
|
|
|
from fastapi import WebSocket
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
SEND_TIMEOUT_SECONDS = 5
|
|
CLOSE_UNAUTHORIZED = 4401
|
|
|
|
|
|
@dataclass(eq=False)
|
|
class Connection:
|
|
websocket: WebSocket
|
|
user_id: int
|
|
session_id: int
|
|
|
|
|
|
class Hub:
|
|
def __init__(self) -> None:
|
|
self._by_user: dict[int, set[Connection]] = defaultdict(set)
|
|
|
|
def count(self, user_id: int) -> int:
|
|
return len(self._by_user.get(user_id, ()))
|
|
|
|
def add(self, conn: Connection) -> None:
|
|
self._by_user[conn.user_id].add(conn)
|
|
|
|
def remove(self, conn: Connection) -> None:
|
|
conns = self._by_user.get(conn.user_id)
|
|
if conns is not None:
|
|
conns.discard(conn)
|
|
if not conns:
|
|
del self._by_user[conn.user_id]
|
|
|
|
async def broadcast(self, user_id: int, message: dict[str, Any]) -> None:
|
|
"""Send a message to every connection of one user; dead connections are dropped."""
|
|
text = json.dumps(message)
|
|
for conn in list(self._by_user.get(user_id, ())):
|
|
try:
|
|
await asyncio.wait_for(conn.websocket.send_text(text), SEND_TIMEOUT_SECONDS)
|
|
except Exception:
|
|
logger.info("Dropping unresponsive WebSocket of user %s", user_id)
|
|
self.remove(conn)
|
|
await self._close(conn, 1011)
|
|
|
|
async def close_session(self, session_id: int) -> None:
|
|
await self._close_where(lambda c: c.session_id == session_id)
|
|
|
|
async def close_user(self, user_id: int, except_session_id: int | None = None) -> None:
|
|
await self._close_where(
|
|
lambda c: c.user_id == user_id and c.session_id != except_session_id
|
|
)
|
|
|
|
async def _close_where(self, predicate) -> None:
|
|
targets = [c for conns in self._by_user.values() for c in conns if predicate(c)]
|
|
for conn in targets:
|
|
self.remove(conn)
|
|
await self._close(conn, CLOSE_UNAUTHORIZED)
|
|
|
|
@staticmethod
|
|
async def _close(conn: Connection, code: int) -> None:
|
|
try:
|
|
await conn.websocket.close(code=code)
|
|
except Exception: # already closed or broken
|
|
logger.debug("WebSocket already closed", exc_info=True)
|
|
|
|
|
|
hub = Hub()
|