# core/event_center.py
import logging
import threading
import uuid
import time
from enum import Enum, auto
from typing import Dict, List, Callable, Optional, Any, Set, DefaultDict, Union, Tuple
from collections import defaultdict
from dataclasses import dataclass, field
from concurrent.futures import ThreadPoolExecutor
# 初始化日志
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
@dataclass
class Event:
"""事件数据类"""
event_type: Union[str, 'EventType']
source: str
target: Optional[str] = None
event_id: str = field(default_factory=lambda: str(uuid.uuid4()))
token: Optional[str] = None
Optional[Dict[str, Any]] = field(default_factory=dict)
timestamp: float = field(default_factory=time.time)
def __post_init__(self):
"""数据验证和类型转换"""
if isinstance(self.event_type, EventType):
self.event_type = self.event_type.name
if not isinstance(self.event_type, str) or not self.event_type:
raise ValueError("event_type 必须是非空字符串或EventType枚举")
if not isinstance(self.source, str) or not self.source:
raise ValueError("source 必须是非空字符串")
class EventType(Enum):
"""完整事件类型枚举"""
# 系统事件
SYSTEM_STARTUP = auto()
SYSTEM_SHUTDOWN = auto()
MODULE_READY = auto()
ERROR = auto()
TEST_EVENT = auto()
# 模块控制事件
MODULE_RUN = auto()
COMMAND = auto()
# 数据处理事件
DATA_SUBMIT = auto()
DATA_UPDATE = auto()
DATA_FREEZE = auto()
DATA_ORGANIZE = auto()
DATA_RESULT = auto()
# 分析结果事件
ANALYSIS_RESULT = auto()
INPUT_ANALYSIS_START = auto()
INPUT_ANALYSIS_END = auto()
COMBINATION_RESULT = auto()
COMBINATION_ANALYSIS_START = auto()
COMBINATION_ANALYSIS_END = auto()
FOLLOW_RESULT = auto()
FOLLOW_ANALYSIS_START = auto()
FOLLOW_ANALYSIS_UPDATE = auto()
TREND_ANALYSIS_RESULT = auto()
TREND_ANALYSIS_REQUEST = auto()
TREND_ANALYSIS_REPORT = auto()
NUMBER_GENERATION_RESULT = auto()
NUMBER_GENERATION_START = auto()
NUMBER_GENERATION_FINISH = auto()
# UI相关事件
UI_UPDATE = auto()
DIALOG_OPEN = auto()
DIALOG_CLOSE = auto()
REGISTER_UI = auto()
GET_RESULTS = auto()
# 状态事件
LOADING_PROGRESS = auto()
LOADING_COMPLETE = auto()
# 特定功能事件
EXCLUDE_NUMBERS = auto()
POOL_UPDATE = auto()
# 模块标识事件
INPUT = auto()
COMBINATION = auto()
FOLLOW = auto()
TREND = auto()
GENERATION = auto()
class EventCenter:
"""线程安全的事件中心(最终优化版)"""
_instance = None
_lock = threading.Lock()
_executor = ThreadPoolExecutor(max_workers=10, thread_name_prefix="EventWorker")
def __new__(cls):
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.__initialized = False
return cls._instance
def __init__(self):
"""初始化事件中心(单例模式)"""
if getattr(self, '__initialized', False):
return
self.__initialized = True
self._subscribers: DefaultDict[str, List[Tuple[Callable[[Event], None], Optional[str]]]] = defaultdict(list)
self._event_history: Dict[str, Event] = {}
self._pending_acks: Set[str] = set()
self._ack_timeout = 5.0
self._stats = {
'total_events': 0,
'failed_events': 0,
'delivered_events': 0
}
def subscribe(self, event_type: Union[str, EventType], handler: Callable[[Event], None],
token: Optional[str] = None) -> None:
"""订阅事件(支持token过滤)"""
event_type_str = event_type.name if isinstance(event_type, EventType) else str(event_type)
with self._lock:
self._subscribers[event_type_str].append((handler, token))
logger.debug(f"已订阅事件: {event_type_str}, token: {token}")
def unsubscribe(self, event_type: Union[str, EventType], handler: Callable[[Event], None]) -> bool:
"""取消订阅事件"""
event_type_str = event_type.name if isinstance(event_type, EventType) else str(event_type)
with self._lock:
if event_type_str not in self._subscribers:
return False
before = len(self._subscribers[event_type_str])
self._subscribers[event_type_str] = [(h, t) for h, t in self._subscribers[event_type_str] if h != handler]
removed = before != len(self._subscribers[event_type_str])
if removed:
logger.debug(f"已取消订阅: {event_type_str}")
return removed
def publish(self, event: Event, require_ack: bool = False, async_handle: bool = True) -> bool:
"""发布事件(支持同步/异步处理)"""
# 增强事件验证
try:
# 确保事件有必要的属性
if not hasattr(event, 'event_type') or not hasattr(event, 'source'):
raise AttributeError("事件缺少必要属性: event_type或source")
# 自动生成事件ID(如果缺失)
if not hasattr(event, 'event_id') or not event.event_id:
event.event_id = str(uuid.uuid4())
# 执行事件验证
if hasattr(event, '__post_init__'):
event.__post_init__()
else:
# 手动验证基本属性
if not isinstance(event.event_type, (str, EventType)):
raise TypeError("event_type必须是字符串或EventType")
if not isinstance(event.source, str) or not event.source:
raise ValueError("source必须是非空字符串")
except (ValueError, TypeError, AttributeError) as ex:
# 处理预期的验证错误
logger.error(f"事件验证失败: {ex}")
with self._lock:
self._stats['failed_events'] += 1
return False
except Exception as ex:
# 记录所有其他异常
logger.exception(f"事件验证过程中发生意外错误: {ex}")
with self._lock:
self._stats['failed_events'] += 1
return False
# 主事件处理逻辑
try:
with self._lock:
if event.event_id in self._event_history:
logger.warning(f"重复事件ID: {event.event_id}")
return False
self._event_history[event.event_id] * event
self._stats['total_events'] += 1
if require_ack:
self._pending_acks.add(event.event_id)
handlers = self._get_matching_handlers(event)
if not handlers:
logger.debug(f"没有处理器订阅: {event.event_type}")
return True
if async_handle:
self._executor.submit(self._dispatch_event, event, handlers, require_ack)
else:
self._dispatch_event(event, handlers, require_ack)
return True
except (KeyError, AttributeError) as ex:
# 处理内部数据结构错误
logger.error(f"内部数据结构错误: {ex}")
with self._lock:
self._stats['failed_events'] += 1
return False
except Exception as ex:
# 捕获所有其他异常
logger.exception(f"发布事件时发生未预期错误: {ex}")
with self._lock:
self._stats['failed_events'] += 1
return False
def _get_matching_handlers(self, event: Event) -> List[Callable[[Event], None]]:
"""获取匹配的事件处理器"""
event_type_str = event.event_type.name if isinstance(event.event_type, EventType) else event.event_type
with self._lock:
return [h for h, t in self._subscribers.get(event_type_str, []) if t is None or t == event.token]
def _dispatch_event(self, event: Event, handlers: List[Callable[[Event], None]], require_ack: bool) -> None:
"""分发事件到处理器"""
for handler in handlers:
try:
handler(event)
with self._lock:
self._stats['delivered_events'] += 1
logger.debug(f"事件处理成功: {str(event.event_id)[:8]}")
except Exception as ex:
logger.exception(f"处理器异常: {ex}")
if require_ack and event.target:
self._wait_for_ack(event)
def _wait_for_ack(self, event: Event) -> None:
"""等待事件确认"""
start = time.time()
while time.time() - start < self._ack_timeout:
with self._lock:
if event.event_id not in self._pending_acks:
return
time.sleep(0.05)
logger.warning(f"事件确认超时: {event.event_id[:8]}")
with self._lock:
if event.event_id in self._pending_acks:
self._pending_acks.remove(event.event_id)
def get_stats(self) -> Dict[str, int]:
"""获取事件中心统计信息"""
with self._lock:
return self._stats.copy()
def clear(self):
"""重置事件中心状态(测试专用)"""
with self._lock:
self._subscribers.clear()
self._event_history.clear()
self._pending_acks.clear()
self._stats = {
'total_events': 0,
'failed_events': 0,
'delivered_events': 0
}
# 全局单例实例
event_center = EventCenter()