|
| 1 | +"""Event bus implementation for runtime events.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import logging |
| 5 | +from typing import Any, Callable, TypeVar |
| 6 | + |
| 7 | +logger = logging.getLogger(__name__) |
| 8 | + |
| 9 | +T = TypeVar("T") |
| 10 | + |
| 11 | + |
| 12 | +class EventBus: |
| 13 | + """Event bus for publishing and subscribing to events.""" |
| 14 | + |
| 15 | + def __init__(self) -> None: |
| 16 | + """Initialize a new EventBus instance.""" |
| 17 | + self._subscribers: dict[str, list[Callable[[Any], Any]]] = {} |
| 18 | + self._running_tasks: set[asyncio.Task[Any]] = set() |
| 19 | + |
| 20 | + def subscribe(self, topic: str, handler: Callable[[Any], Any]) -> None: |
| 21 | + """Subscribe a handler method/function to a topic. |
| 22 | +
|
| 23 | + Args: |
| 24 | + topic: The topic name to subscribe to. |
| 25 | + handler: The async handler method/function that will handle events for this topic. |
| 26 | + """ |
| 27 | + if topic not in self._subscribers: |
| 28 | + self._subscribers[topic] = [] |
| 29 | + self._subscribers[topic].append(handler) |
| 30 | + logger.debug(f"Handler registered for topic: {topic}") |
| 31 | + |
| 32 | + def unsubscribe(self, topic: str, handler: Callable[[Any], Any]) -> None: |
| 33 | + """Unsubscribe a handler from a topic. |
| 34 | +
|
| 35 | + Args: |
| 36 | + topic: The topic name to unsubscribe from. |
| 37 | + handler: The handler to remove. |
| 38 | + """ |
| 39 | + if topic in self._subscribers: |
| 40 | + try: |
| 41 | + self._subscribers[topic].remove(handler) |
| 42 | + if not self._subscribers[topic]: |
| 43 | + del self._subscribers[topic] |
| 44 | + logger.debug(f"Handler unregistered from topic: {topic}") |
| 45 | + except ValueError: |
| 46 | + logger.warning(f"Handler not found for topic: {topic}") |
| 47 | + |
| 48 | + def _cleanup_completed_tasks(self) -> None: |
| 49 | + completed_tasks = {task for task in self._running_tasks if task.done()} |
| 50 | + self._running_tasks -= completed_tasks |
| 51 | + |
| 52 | + async def publish( |
| 53 | + self, topic: str, payload: T, wait_for_completion: bool = True |
| 54 | + ) -> None: |
| 55 | + """Publish an event to all handlers of a topic. |
| 56 | +
|
| 57 | + Args: |
| 58 | + topic: The topic name to publish to. |
| 59 | + payload: The event payload to publish. |
| 60 | + wait_for_completion: Whether to wait for the event to be processed. |
| 61 | + """ |
| 62 | + if topic not in self._subscribers: |
| 63 | + logger.debug(f"No handlers for topic: {topic}") |
| 64 | + return |
| 65 | + |
| 66 | + self._cleanup_completed_tasks() |
| 67 | + |
| 68 | + tasks = [] |
| 69 | + for subscriber in self._subscribers[topic]: |
| 70 | + try: |
| 71 | + task = asyncio.create_task(subscriber(payload)) |
| 72 | + tasks.append(task) |
| 73 | + self._running_tasks.add(task) |
| 74 | + except Exception as e: |
| 75 | + logger.error(f"Error creating task for subscriber {subscriber}: {e}") |
| 76 | + |
| 77 | + if tasks and wait_for_completion: |
| 78 | + try: |
| 79 | + await asyncio.gather(*tasks, return_exceptions=True) |
| 80 | + except Exception as e: |
| 81 | + logger.error(f"Error during event processing for topic {topic}: {e}") |
| 82 | + finally: |
| 83 | + # Clean up the tasks we just waited for |
| 84 | + for task in tasks: |
| 85 | + self._running_tasks.discard(task) |
| 86 | + |
| 87 | + def get_running_tasks_count(self) -> int: |
| 88 | + """Get the number of currently running subscriber tasks. |
| 89 | +
|
| 90 | + Returns: |
| 91 | + Number of running tasks. |
| 92 | + """ |
| 93 | + self._cleanup_completed_tasks() |
| 94 | + return len(self._running_tasks) |
| 95 | + |
| 96 | + async def wait_for_all(self, timeout: float | None = None) -> None: |
| 97 | + """Wait for all currently running subscriber tasks to complete. |
| 98 | +
|
| 99 | + Args: |
| 100 | + timeout: Maximum time to wait in seconds. If None, waits indefinitely. |
| 101 | + """ |
| 102 | + self._cleanup_completed_tasks() |
| 103 | + |
| 104 | + if not self._running_tasks: |
| 105 | + logger.debug("No running tasks to wait for") |
| 106 | + return |
| 107 | + |
| 108 | + logger.debug( |
| 109 | + f"Waiting for {len(self._running_tasks)} EventBus tasks to complete..." |
| 110 | + ) |
| 111 | + |
| 112 | + try: |
| 113 | + tasks_to_wait = list(self._running_tasks) |
| 114 | + |
| 115 | + if timeout: |
| 116 | + await asyncio.wait_for( |
| 117 | + asyncio.gather(*tasks_to_wait, return_exceptions=True), |
| 118 | + timeout=timeout, |
| 119 | + ) |
| 120 | + else: |
| 121 | + await asyncio.gather(*tasks_to_wait, return_exceptions=True) |
| 122 | + |
| 123 | + logger.debug("All EventBus tasks completed") |
| 124 | + |
| 125 | + except asyncio.TimeoutError: |
| 126 | + logger.warning(f"Timeout waiting for EventBus tasks after {timeout}s") |
| 127 | + for task in tasks_to_wait: |
| 128 | + if not task.done(): |
| 129 | + task.cancel() |
| 130 | + except Exception as e: |
| 131 | + logger.error(f"Error waiting for EventBus tasks: {e}") |
| 132 | + finally: |
| 133 | + self._cleanup_completed_tasks() |
| 134 | + |
| 135 | + def get_subscribers_count(self, topic: str) -> int: |
| 136 | + """Get the number of subscribers for a topic. |
| 137 | +
|
| 138 | + Args: |
| 139 | + topic: The topic name. |
| 140 | +
|
| 141 | + Returns: |
| 142 | + Number of handlers for the topic. |
| 143 | + """ |
| 144 | + return len(self._subscribers.get(topic, [])) |
| 145 | + |
| 146 | + def clear_subscribers(self, topic: str | None = None) -> None: |
| 147 | + """Clear subscribers for a topic or all topics. |
| 148 | +
|
| 149 | + Args: |
| 150 | + topic: The topic to clear. If None, clears all topics. |
| 151 | + """ |
| 152 | + if topic is None: |
| 153 | + self._subscribers.clear() |
| 154 | + logger.debug("All handlers cleared") |
| 155 | + elif topic in self._subscribers: |
| 156 | + del self._subscribers[topic] |
| 157 | + logger.debug(f"Handlers cleared for topic: {topic}") |
0 commit comments