"""The chat socket: WS /v1/chat/ws. Every chat read and write as a command, plus live events (live.py). Frames are JSON text. The client sends {"id", "type", ...params}; the reply repeats the id: {"id", "type": ".ok", "data"} or {"id", "type": "error", "status", "error": {code, message, fields}}. Events arrive without an id: {"type": "message.new" | "thread.read" | "thread.new", "data"}. The first frame must be {"type": "auth", "token": }. Each command runs in its own short database transaction through ThreadService, so the rules and shapes are the ones the REST endpoints have. """ import asyncio import json import logging from collections.abc import Awaitable, Callable from datetime import UTC, datetime from typing import Any, Literal from uuid import UUID import jwt from fastapi import APIRouter, WebSocket, WebSocketDisconnect from pydantic import Field, TypeAdapter, ValidationError from sqlalchemy.ext.asyncio import AsyncSession from app.common.academy_access import staff_context from app.common.schemas import RequestModel from app.core.database import get_autocommit_engine, get_session_factory from app.core.errors import AppError, Forbidden, Unauthenticated, ValidationFailed, _field_path from app.core.pagination import PageParams, decode_cursor from app.core.security import decode_access_token from app.integrations.push import get_push_client from app.integrations.storage import get_storage from app.modules.accounts.models import Account from app.modules.idempotency.service import run_idempotent from app.modules.threads import live from app.modules.threads.schemas import EnsureThreadIn, MessageIn from app.modules.threads.service import ThreadService log = logging.getLogger(__name__) router = APIRouter() AUTH_TIMEOUT_S = 10.0 CLOSE_UNAUTHENTICATED = 4401 class ListIn(RequestModel): mode: Literal["h", "p"] | None = None player_id: UUID | None = None unread: bool | None = None cursor: str | None = None limit: int = Field(50, ge=1, le=200) class GetIn(RequestModel): thread_id: UUID message_cursor: str | None = None message_limit: int = Field(50, ge=1, le=100) class ForSessionIn(RequestModel): session_id: UUID class ReadIn(RequestModel): thread_id: UUID last_message_id: UUID | None = None class SendIn(RequestModel): thread_id: UUID message: MessageIn idempotency_key: str | None = Field(None, min_length=1, max_length=200) class EnsureIn(EnsureThreadIn): player_id: UUID Context = tuple[ThreadService, Account, AsyncSession, live.Connection] async def _list(ctx: Context, p: ListIn) -> Any: service, account, _, connection = ctx page = await service.list_threads(account, PageParams(p.limit, decode_cursor(p.cursor) if p.cursor else None), mode=p.mode, player_id=p.player_id, unread=p.unread) connection.watched.update(t.id for t in page.items) return page async def _get(ctx: Context, p: GetIn) -> Any: service, account, _, connection = ctx thread = await service.get(account, p.thread_id, p.message_cursor, p.message_limit) connection.watched.add(thread.id) return {"thread": thread} async def _for_session(ctx: Context, p: ForSessionIn) -> Any: service, account, _, connection = ctx thread = await service.for_session(account, p.session_id) connection.watched.add(thread.id) return {"thread": thread} async def _read(ctx: Context, p: ReadIn) -> Any: service, account, _, _ = ctx await service.mark_read(account, p.thread_id, p.last_message_id) return {} async def _send(ctx: Context, p: SendIn) -> Any: service, account, db, _ = ctx # A resend after a dropped connection carries the same key and gets the first result back. response = await run_idempotent(db, account.id, p.idempotency_key, p.message, lambda: service.send(account, p.thread_id, p.message), status_code=201, scope=p.thread_id) return json.loads(response.body) async def _ensure(ctx: Context, p: EnsureIn) -> Any: service, account, db, connection = ctx staff = await staff_context(db, account) if staff is None: raise Forbidden("Only coaches can do this.") thread, created = await service.ensure_general(staff, p.player_id, EnsureThreadIn(mode=p.mode)) connection.watched.add(thread.id) return {"thread": thread, "created": created} # type -> (params model, handler, read-only) COMMANDS: dict[str, tuple[type[RequestModel], Callable[[Context, Any], Awaitable[Any]], bool]] = { "threads.list": (ListIn, _list, True), "thread.get": (GetIn, _get, True), "thread.for_session": (ForSessionIn, _for_session, True), "thread.read": (ReadIn, _read, False), "message.send": (SendIn, _send, False), "thread.ensure": (EnsureIn, _ensure, False), } _FRAME = TypeAdapter(dict[str, Any]) def _error(exc: Exception) -> dict: if isinstance(exc, ValidationError): fields: dict[str, str] = {} for err in exc.errors(): fields.setdefault(_field_path(tuple(err.get("loc", ()))), err.get("msg", "Invalid value.")) exc = ValidationFailed(fields=fields) if not isinstance(exc, AppError): log.exception("chat socket command failed", exc_info=exc) exc = AppError() error: dict = {"code": exc.code, "message": exc.message} if exc.fields: error["fields"] = exc.fields return {"type": "error", "status": exc.status_code, "error": error} def _authenticate(token: Any) -> tuple[UUID, datetime]: if not isinstance(token, str): raise Unauthenticated() account_id = decode_access_token(token) # verifies signature, type and expiry expires = jwt.decode(token, options={"verify_signature": False})["exp"] return account_id, datetime.fromtimestamp(expires, UTC) async def _run(connection: live.Connection, kind: str, params: dict) -> Any: if kind not in COMMANDS: raise ValidationFailed(fields={"type": "Unknown command."}) model, handler, read_only = COMMANDS[kind] parsed = model.model_validate(params) # Reads skip BEGIN/COMMIT like GET requests do; the connection goes back to the pool after every command. async with get_session_factory()(**({"bind": get_autocommit_engine()} if read_only else {})) as db: account = await db.get(Account, connection.account_id) if account is None: raise Unauthenticated() service = ThreadService(db, get_storage(), get_push_client()) result = await handler((service, account, db, connection), parsed) await db.commit() return result async def serve(socket) -> None: """One connection, start to finish. `socket` needs accept, receive_text, send_text and close.""" await socket.accept() connection: live.Connection | None = None try: while True: # An unauthenticated socket may not sit open: the first frame has to arrive promptly. raw = await asyncio.wait_for(socket.receive_text(), None if connection else AUTH_TIMEOUT_S) reply: dict = {} try: frame = _FRAME.validate_json(raw) kind, request_id = frame.pop("type", None), frame.pop("id", None) if request_id is not None: reply["id"] = request_id if kind == "ping": reply["type"] = "pong" elif kind == "auth": account_id, expires_at = _authenticate(frame.get("token")) if connection is None: connection = live.Connection(socket, account_id, expires_at) live.CONNECTIONS.add(connection) elif connection.account_id != account_id: raise Unauthenticated("This connection belongs to another account.") connection.expires_at = expires_at reply.update(type="auth.ok", data={"account_id": account_id, "expires_at": expires_at}) elif connection is None: raise Unauthenticated() elif connection.expires_at <= datetime.now(UTC): raise Unauthenticated("Your sign-in has expired. Send auth again with a new token.", code="TOKEN_EXPIRED") else: reply.update(type=f"{kind}.ok", data=await _run(connection, kind, frame)) except Exception as exc: reply.update(_error(exc)) if connection is not None: await connection.send(reply) else: await socket.send_text(json.dumps(reply)) await socket.close(CLOSE_UNAUTHENTICATED) # no valid auth as the first frame return except TimeoutError: await socket.close(CLOSE_UNAUTHENTICATED) except WebSocketDisconnect: pass finally: if connection is not None: live.CONNECTIONS.discard(connection) @router.websocket("/v1/chat/ws") async def chat_socket(socket: WebSocket) -> None: await serve(socket)