37 lines
1.3 KiB
Python
37 lines
1.3 KiB
Python
import asyncio
|
|
import logging
|
|
from typing import Callable, Dict, List, Any, Awaitable
|
|
|
|
logger = logging.getLogger("cs_agent")
|
|
|
|
class AsyncEventBus:
|
|
"""
|
|
异步事件总线:解耦业务触发与平台发送。
|
|
支持一个事件被多个订阅者监听。
|
|
"""
|
|
def __init__(self):
|
|
self._listeners: Dict[str, List[Callable[..., Awaitable[None]]]] = {}
|
|
|
|
def subscribe(self, event_type: str, callback: Callable[..., Awaitable[None]]):
|
|
"""订阅事件"""
|
|
if event_type not in self._listeners:
|
|
self._listeners[event_type] = []
|
|
self._listeners[event_type].append(callback)
|
|
logger.info(f"[EventBus] 新订阅者已注册到事件: {event_type}")
|
|
|
|
async def emit(self, event_type: str, **kwargs):
|
|
"""发布事件:异步广播给所有订阅者"""
|
|
if event_type not in self._listeners:
|
|
return
|
|
|
|
tasks = []
|
|
for callback in self._listeners[event_type]:
|
|
tasks.append(asyncio.create_task(callback(**kwargs)))
|
|
|
|
if tasks:
|
|
await asyncio.gather(*tasks, return_exceptions=True)
|
|
logger.info(f"[EventBus] 事件 {event_type} 已成功广播给 {len(tasks)} 个订阅者")
|
|
|
|
# 全局单例,所有模块共用这一个广播台
|
|
bus = AsyncEventBus()
|