| 1 |
"""Central event bus.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import asyncio |
| 6 |
from collections.abc import Awaitable, Callable |
| 7 |
import contextlib |
| 8 |
import logging |
| 9 |
|
| 10 |
from ..exceptions import CloudError |
| 11 |
from .types import CloudEvent, CloudEventType |
| 12 |
|
| 13 |
_LOGGER = logging.getLogger(__name__) |
| 14 |
|
| 15 |
|
| 16 |
class EventBusError(CloudError): |
| 17 |
"""Exception raised for event bus errors.""" |
| 18 |
|
| 19 |
|
| 20 |
class CloudEventBus: |
| 21 |
"""Central event bus for all cloud events.""" |
| 22 |
|
| 23 |
def __init__(self) -> None: |
| 24 |
"""Initialize the event bus.""" |
| 25 |
self._subscribers: dict[ |
| 26 |
str, |
| 27 |
list[Callable[[CloudEvent], Awaitable[None]]], |
| 28 |
] = {k.value: [] for k in CloudEventType} |
| 29 |
|
| 30 |
def subscribe( |
| 31 |
self, |
| 32 |
*, |
| 33 |
event_type: CloudEventType | list[CloudEventType], |
| 34 |
handler: Callable[[CloudEvent], Awaitable[None]], |
| 35 |
) -> Callable[[], None]: |
| 36 |
"""Subscribe to an event type or list of event types.""" |
| 37 |
event_types = event_type if isinstance(event_type, list) else [event_type] |
| 38 |
|
| 39 |
for evt_type in event_types: |
| 40 |
if evt_type not in self._subscribers: |
| 41 |
raise EventBusError(f"Unknown event type: {evt_type}") |
| 42 |
self._subscribers[evt_type].append(handler) |
| 43 |
|
| 44 |
_LOGGER.debug("%s subscribed to %s", handler.__name__, event_types) |
| 45 |
|
| 46 |
def unsubscribe() -> None: |
| 47 |
"""Remove this subscription.""" |
| 48 |
for evt_type in event_types: |
| 49 |
with contextlib.suppress(ValueError): |
| 50 |
self._subscribers[evt_type].remove(handler) |
| 51 |
_LOGGER.debug("%s unsubscribed from %s", handler.__name__, event_types) |
| 52 |
|
| 53 |
return unsubscribe |
| 54 |
|
| 55 |
async def publish( |
| 56 |
self, |
| 57 |
event: CloudEvent, |
| 58 |
) -> None: |
| 59 |
"""Publish an event to all subscribers.""" |
| 60 |
event_type = event.type |
| 61 |
|
| 62 |
if event_type not in self._subscribers: |
| 63 |
return |
| 64 |
|
| 65 |
handlers = self._subscribers[event_type] |
| 66 |
|
| 67 |
if not handlers: |
| 68 |
_LOGGER.debug("No subscribers for event %s", event_type) |
| 69 |
return |
| 70 |
|
| 71 |
_LOGGER.debug("Publish %s to %d subscribers", event_type, len(handlers)) |
| 72 |
|
| 73 |
results = await asyncio.gather( |
| 74 |
*[handler(event) for handler in handlers], |
| 75 |
return_exceptions=True, |
| 76 |
) |
| 77 |
|
| 78 |
for handler, result in zip(handlers, results, strict=True): |
| 79 |
if isinstance(result, Exception): |
| 80 |
_LOGGER.error( |
| 81 |
"Error in event handler %s for event %s", |
| 82 |
handler.__name__, |
| 83 |
event_type, |
| 84 |
exc_info=result, |
| 85 |
) |