结合刚才的分析,进行修改问题:代码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
data: 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")
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__()
# 主处理逻辑
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 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()
# 导入 UI_CONFIG
try:
from core.ui_config import get_ui_config
# 获取UI配置对象
ui_config = get_ui_config()
# 使用配置值
theme = ui_config.get("theme", "dark")
language = ui_config.get("language", "zh-CN")
except ImportError as e:
logger.error(f"无法导入核心模块: {e}")
raise
最新发布