"""Live chat events: who is connected, and what they are told after a chat change is committed. Any code that inserts or re-sequences a Message (chat sends, coach reviews) is announced automatically through the mapper events below; read marks and new threads call announce(). Nothing is sent until the transaction commits, and a rollback drops the pending events. shortcut: connections live in this process's memory, so events reach only sockets connected to the same API process. Run one API process, or put Postgres LISTEN/NOTIFY or Redis behind deliver() before adding a second. """ import asyncio import json import logging from dataclasses import dataclass, field from datetime import UTC, datetime from typing import Protocol from uuid import UUID from fastapi.encoders import jsonable_encoder from sqlalchemy import event from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import Session, object_session from app.core.database import get_autocommit_engine, get_session_factory from app.integrations.storage import get_storage from app.modules.accounts.models import Account from app.modules.threads.models import Message log = logging.getLogger(__name__) class Socket(Protocol): async def send_text(self, data: str) -> None: ... @dataclass(eq=False) class Connection: socket: Socket account_id: UUID expires_at: datetime # of the access token; refreshed by a new auth message watched: set[UUID] = field(default_factory=set) # threads this socket has opened (staff other than the coach) lock: asyncio.Lock = field(default_factory=asyncio.Lock) async def send(self, payload: dict) -> None: async with self.lock: # replies and pushed events come from different tasks await self.socket.send_text(json.dumps(jsonable_encoder(payload))) CONNECTIONS: set[Connection] = set() _TASKS: set[asyncio.Task] = set() def announce(db: AsyncSession | Session, kind: str, thread_id: UUID, message_id: UUID | None = None) -> None: """Queue a live event on this transaction; it is delivered after commit.""" session = db.sync_session if isinstance(db, AsyncSession) else db pending = session.info.setdefault("live_events", []) if (kind, thread_id, message_id) not in pending: pending.append((kind, thread_id, message_id)) @event.listens_for(Message, "after_insert") @event.listens_for(Message, "after_update") def _message_written(mapper, connection, message: Message) -> None: session = object_session(message) if session is not None: announce(session, "message.new", message.thread_id, message.id) @event.listens_for(Session, "after_commit") def _committed(session: Session) -> None: events = session.info.pop("live_events", None) if events and CONNECTIONS: task = asyncio.get_running_loop().create_task(deliver(events)) _TASKS.add(task) task.add_done_callback(_TASKS.discard) @event.listens_for(Session, "after_rollback") def _rolled_back(session: Session) -> None: session.info.pop("live_events", None) async def deliver(events: list[tuple[str, UUID, UUID | None]]) -> None: """Render each event once and send it to every connected account that may still see the thread.""" from app.modules.threads.service import ThreadService # the service imports announce from this module try: async with get_session_factory()(bind=get_autocommit_engine()) as db: service = ThreadService(db, get_storage()) for kind, thread_id, message_id in events: thread = await service.repo.get(thread_id) if thread is None: continue now = datetime.now(UTC) targets = [c for c in CONNECTIONS if c.expires_at > now and ( c.account_id in (thread.player_id, thread.coach_id) or thread_id in c.watched)] if not targets: continue data = await service.live_event(kind, thread, message_id) allowed: dict[UUID, bool] = {} for connection in targets: if connection.account_id not in allowed: # access can be lost after the socket opened account = await db.get(Account, connection.account_id) allowed[connection.account_id] = account is not None and await service.can_access( account, thread) if not allowed[connection.account_id]: connection.watched.discard(thread_id) continue try: await connection.send({"type": kind, "data": data}) except Exception: # a dead socket is removed by its own reader loop log.info("live: send to %s failed", connection.account_id) except Exception: log.exception("live: delivering %d event(s) failed", len(events)) async def idle() -> None: """Wait for deliveries in flight (tests, shutdown).""" while _TASKS: await asyncio.gather(*list(_TASKS))