From c6c75138e8f054eacaaf118f587e33e17d59f95c Mon Sep 17 00:00:00 2001 From: ai-chess Date: Thu, 14 May 2026 23:13:13 +0300 Subject: [PATCH] feat(events): minimal asyncio pub/sub bus --- src/ai_chess/events.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/ai_chess/events.py diff --git a/src/ai_chess/events.py b/src/ai_chess/events.py new file mode 100644 index 0000000..f0e614c --- /dev/null +++ b/src/ai_chess/events.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +import asyncio +from typing import Any, AsyncIterator + + +class EventBus: + def __init__(self) -> None: + self._subs: set[asyncio.Queue[dict[str, Any]]] = set() + + def subscribe(self) -> asyncio.Queue[dict[str, Any]]: + q: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=1024) + self._subs.add(q) + return q + + def unsubscribe(self, q: asyncio.Queue[dict[str, Any]]) -> None: + self._subs.discard(q) + + async def publish(self, event: dict[str, Any]) -> None: + dead: list[asyncio.Queue] = [] + for q in self._subs: + try: + q.put_nowait(event) + except asyncio.QueueFull: + dead.append(q) + for q in dead: + self._subs.discard(q) + + async def stream(self, q: asyncio.Queue[dict[str, Any]]) -> AsyncIterator[dict[str, Any]]: + while True: + yield await q.get()