feat(events): minimal asyncio pub/sub bus

This commit is contained in:
ai-chess
2026-05-14 23:13:13 +03:00
parent 8eca3a16de
commit c6c75138e8
+31
View File
@@ -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()