from __future__ import annotations import asyncio import json from threading import Lock from typing import Any # Clients reconnect after this delay if the stream drops (SSE ``retry:``). SSE_RETRY_MS = 5_000 # A comment line keeps proxies and browsers from timing out a quiet stream. SSE_KEEPALIVE_SECONDS = 15.0 class Subscription: """One connected SSE client: an asyncio queue bound to its event loop.""" __slots__ = ("loop", "queue") def __init__(self, loop: asyncio.AbstractEventLoop, max_queue_size: int) -> None: self.loop = loop self.queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=max_queue_size) def offer(self, payload: dict[str, Any]) -> None: """Enqueue on the owning loop; drop the oldest wakeup when full.""" if self.queue.full(): try: self.queue.get_nowait() except asyncio.QueueEmpty: pass try: self.queue.put_nowait(payload) except asyncio.QueueFull: pass class EventBus: """Small bounded fan-out bus used by the SSE endpoint. Persistence is handled by SQLite; this bus only wakes currently connected clients. Each client owns an ``asyncio.Queue`` so a waiting stream costs no thread: previously every open browser tab parked one default-executor thread in ``queue.get``, which starved ``asyncio.to_thread`` work such as the observation loop. ``publish`` is safe from worker threads and from the event loop; delivery is scheduled with ``call_soon_threadsafe``. """ def __init__(self, max_queue_size: int = 100) -> None: self.max_queue_size = max_queue_size self._subscribers: set[Subscription] = set() self._lock = Lock() self._revision = 0 @property def revision(self) -> int: """Monotonic count of published events; read caches compare it.""" with self._lock: return self._revision def subscribe(self) -> Subscription: subscription = Subscription(asyncio.get_running_loop(), self.max_queue_size) with self._lock: self._subscribers.add(subscription) return subscription def unsubscribe(self, subscription: Subscription) -> None: with self._lock: self._subscribers.discard(subscription) @property def subscriber_count(self) -> int: with self._lock: return len(self._subscribers) def publish(self, payload: dict[str, Any]) -> None: with self._lock: self._revision += 1 subscribers = tuple(self._subscribers) for subscription in subscribers: try: subscription.loop.call_soon_threadsafe(subscription.offer, payload) except RuntimeError: # The client's loop has closed (shutdown); it can no longer # receive anything, so forget it. self.unsubscribe(subscription) event_bus = EventBus() def sse_payload(payload: dict[str, Any]) -> str: event_type = str(payload.get("event_type", "update")) return f"event: {event_type}\ndata: {json.dumps(payload, default=str)}\n\n" async def next_event( subscription: Subscription, timeout: float = SSE_KEEPALIVE_SECONDS ) -> dict[str, Any] | None: try: return await asyncio.wait_for(subscription.queue.get(), timeout) except TimeoutError: return None