from __future__ import annotations import asyncio import json from collections import deque from typing import Any class EventBus: """In-process fan-out for SSE clients.""" def __init__(self, history: int = 50) -> None: self._subs: set[asyncio.Queue] = set() self._history: deque[dict[str, Any]] = deque(maxlen=history) self._lock = asyncio.Lock() def publish_sync(self, event: dict[str, Any]) -> None: self._history.append(event) dead: list[asyncio.Queue] = [] for q in list(self._subs): try: q.put_nowait(event) except Exception: dead.append(q) for q in dead: self._subs.discard(q) async def subscribe(self) -> asyncio.Queue: q: asyncio.Queue = asyncio.Queue(maxsize=100) async with self._lock: self._subs.add(q) for item in self._history: try: q.put_nowait(item) except Exception: break return q async def unsubscribe(self, q: asyncio.Queue) -> None: async with self._lock: self._subs.discard(q) @staticmethod def encode(event: dict[str, Any]) -> str: payload = json.dumps(event, ensure_ascii=False, default=str) return f"data: {payload}\n\n" bus = EventBus()