"""SSE-события (realtime) для фронтенда.""" from __future__ import annotations import asyncio from fastapi import APIRouter, Depends, Request from fastapi.responses import StreamingResponse from ..auth import current_login from ..sse import broker router = APIRouter(prefix="/api", tags=["events"]) @router.get("/events") async def events(request: Request, _: str = Depends(current_login)): async def stream(): q = await broker.subscribe() try: while True: if await request.is_disconnected(): break try: yield await asyncio.wait_for(q.get(), timeout=15) except asyncio.TimeoutError: yield ": ping\n\n" finally: await broker.unsubscribe(q) return StreamingResponse( stream(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no", }, )