32 lines
931 B
Python
32 lines
931 B
Python
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()
|