| 17 | |
| 18 | |
| 19 | class EventBus: |
| 20 | def __init__(self) -> None: |
| 21 | self._subscribers: set[asyncio.Queue[dict[str, Any]]] = set() |
| 22 | self._lock = asyncio.Lock() |
| 23 | |
| 24 | async def subscribe(self) -> asyncio.Queue[dict[str, Any]]: |
| 25 | queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=QUEUE_MAX) |
| 26 | async with self._lock: |
| 27 | self._subscribers.add(queue) |
| 28 | return queue |
| 29 | |
| 30 | async def unsubscribe(self, queue: asyncio.Queue[dict[str, Any]]) -> None: |
| 31 | async with self._lock: |
| 32 | self._subscribers.discard(queue) |
| 33 | |
| 34 | def publish(self, event: dict[str, Any]) -> None: |
| 35 | """Non-blocking fan-out. Safe to call from any async context.""" |
| 36 | for queue in list(self._subscribers): |
| 37 | try: |
| 38 | queue.put_nowait(event) |
| 39 | except asyncio.QueueFull: |
| 40 | try: |
| 41 | queue.put_nowait({"type": "dropped", "reason": "queue_full"}) |
| 42 | except asyncio.QueueFull: |
| 43 | pass |
| 44 | except Exception: |
| 45 | log.exception("event publish failed") |
| 46 | |
| 47 | @property |
| 48 | def subscriber_count(self) -> int: |
| 49 | return len(self._subscribers) |
| 50 | |
| 51 | |
| 52 | _bus: EventBus | None = None |