-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbus.py
More file actions
47 lines (37 loc) · 1.56 KB
/
Copy pathbus.py
File metadata and controls
47 lines (37 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from functools import lru_cache
from src.shared.events.base import Event
from src.shared.events.handler import EventHandler
class EventBus:
"""
General-purpose event bus for publishing and subscribing to events.
Supports multiple handlers per event type.
"""
def __init__(self):
self._handlers: dict[str, list[EventHandler]] = {}
def subscribe(self, event_type: str, handler: EventHandler):
"""Register a handler for a specific event type"""
if event_type not in self._handlers:
self._handlers[event_type] = []
self._handlers[event_type].append(handler)
def unsubscribe(self, event_type: str, handler: EventHandler):
"""Remove a handler for a specific event type"""
if event_type in self._handlers:
self._handlers[event_type] = [
h for h in self._handlers[event_type] if h != handler
]
async def publish(self, event: Event):
"""Publish an event to all subscribed handlers"""
event_type = event.event_type
handlers = self._handlers.get(event_type, [])
for handler in handlers:
try:
await handler.handle(event)
except Exception as e:
# Log error but don't stop other handlers
print(
f"Error in handler {handler.__class__.__name__} for event {event_type}: {e}"
)
# In production, use proper logging and error tracking (Sentry, etc.)
@lru_cache
def get_event_bus() -> EventBus:
return EventBus()