剥离无效事件系统并收口插件统计链路
- 删除未被实际消费的事件系统实现与相关发布逻辑 - 将插件调用统计改为在机器人主链路中直接埋点记录 - 重构统计收集插件初始化与记录方式,移除事件总线依赖 - 同步更新工程优化文档中的性能与链路治理描述
This commit is contained in:
@@ -1,62 +0,0 @@
|
||||
from loguru import logger
|
||||
from typing import Dict, List, Type, Callable, Any
|
||||
from threading import Lock
|
||||
|
||||
|
||||
class Event:
|
||||
"""事件基类"""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
for key, value in kwargs.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
|
||||
class EventManager:
|
||||
"""事件管理器,单例模式"""
|
||||
_instance = None
|
||||
_lock = Lock()
|
||||
|
||||
@classmethod
|
||||
def get_instance(cls):
|
||||
"""获取事件管理器实例"""
|
||||
if cls._instance is None:
|
||||
with cls._lock:
|
||||
if cls._instance is None:
|
||||
cls._instance = cls()
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
if EventManager._instance is not None:
|
||||
raise RuntimeError("EventManager 是单例类,请使用 get_instance() 方法获取实例")
|
||||
|
||||
self.handlers: Dict[Type[Event], List[Callable]] = {}
|
||||
self.LOG = logger
|
||||
|
||||
def register(self, event_type: Type[Event], handler: Callable) -> None:
|
||||
"""注册事件处理器"""
|
||||
if event_type not in self.handlers:
|
||||
self.handlers[event_type] = []
|
||||
|
||||
if handler not in self.handlers[event_type]:
|
||||
self.handlers[event_type].append(handler)
|
||||
self.LOG.debug(f"注册事件处理器: {event_type.__name__} -> {handler.__name__}")
|
||||
|
||||
def unregister(self, event_type: Type[Event], handler: Callable) -> None:
|
||||
"""取消注册事件处理器"""
|
||||
if event_type in self.handlers and handler in self.handlers[event_type]:
|
||||
self.handlers[event_type].remove(handler)
|
||||
self.LOG.debug(f"取消注册事件处理器: {event_type.__name__} -> {handler.__name__}")
|
||||
|
||||
def publish(self, event_type: Type[Event], event_data: Dict[str, Any] = None) -> None:
|
||||
"""发布事件"""
|
||||
if event_data is None:
|
||||
event_data = {}
|
||||
|
||||
event = event_type(**event_data)
|
||||
|
||||
if event_type in self.handlers:
|
||||
for handler in self.handlers[event_type]:
|
||||
try:
|
||||
handler(event)
|
||||
except Exception as e:
|
||||
self.LOG.error(f"事件处理器 {handler.__name__} 处理 {event_type.__name__} 事件出错: {e}")
|
||||
@@ -1,58 +0,0 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
|
||||
from base.event_system.event_manager import Event
|
||||
|
||||
|
||||
@dataclass
|
||||
class PluginCallStartEvent(Event):
|
||||
"""插件调用开始事件"""
|
||||
plugin_name: str # 插件名称
|
||||
command: str # 触发的命令
|
||||
full_command: str # 完整命令内容
|
||||
user_id: str # 用户ID
|
||||
group_id: Optional[str] = None # 群组ID,私聊为None
|
||||
is_group: bool = False # 是否群聊
|
||||
message: Dict[str, Any] = None # 原始消息内容
|
||||
timestamp: datetime = None # 事件时间戳
|
||||
|
||||
def __post_init__(self):
|
||||
if self.timestamp is None:
|
||||
self.timestamp = datetime.now()
|
||||
|
||||
|
||||
@dataclass
|
||||
class PluginCallEndEvent(Event):
|
||||
"""插件调用结束事件"""
|
||||
plugin_name: str # 插件名称
|
||||
command: str # 触发的命令
|
||||
user_id: str # 用户ID
|
||||
group_id: Optional[str] = None # 群组ID,私聊为None
|
||||
is_group: bool = False # 是否群聊
|
||||
process_result: bool = True # 处理结果:True成功,False失败
|
||||
result_message: Optional[str] = None # 处理结果消息
|
||||
process_time: int = 0 # 处理耗时(毫秒)
|
||||
timestamp: datetime = None # 事件时间戳
|
||||
|
||||
def __post_init__(self):
|
||||
if self.timestamp is None:
|
||||
self.timestamp = datetime.now()
|
||||
|
||||
|
||||
@dataclass
|
||||
class PluginCallErrorEvent(Event):
|
||||
"""插件调用错误事件"""
|
||||
plugin_name: str # 插件名称
|
||||
command: str # 触发的命令
|
||||
user_id: str # 用户ID
|
||||
group_id: Optional[str] # 群组ID,私聊为None
|
||||
is_group: bool # 是否群聊
|
||||
error_message: str # 错误信息
|
||||
stack_trace: Optional[str] = None # 堆栈跟踪
|
||||
process_time: int = 0 # 处理耗时(毫秒)
|
||||
timestamp: datetime = None # 事件时间戳
|
||||
|
||||
def __post_init__(self):
|
||||
if self.timestamp is None:
|
||||
self.timestamp = datetime.now()
|
||||
@@ -1,85 +0,0 @@
|
||||
from enum import Enum, auto
|
||||
from typing import Dict, Any, Callable, List
|
||||
import threading
|
||||
|
||||
|
||||
class EventType(Enum):
|
||||
"""事件类型枚举"""
|
||||
SYSTEM_STARTUP = auto()
|
||||
SYSTEM_SHUTDOWN = auto()
|
||||
PLUGIN_LOADED = auto()
|
||||
PLUGIN_UNLOADED = auto()
|
||||
MESSAGE_RECEIVED = auto()
|
||||
MESSAGE_PROCESSED = auto()
|
||||
CUSTOM_EVENT = auto()
|
||||
|
||||
|
||||
class EventSystem:
|
||||
"""事件系统,用于插件间通信"""
|
||||
_instance = None
|
||||
_lock = threading.Lock()
|
||||
|
||||
def __new__(cls):
|
||||
with cls._lock:
|
||||
if cls._instance is None:
|
||||
cls._instance = super(EventSystem, cls).__new__(cls)
|
||||
cls._instance._subscribers = {}
|
||||
cls._instance._initialized = False
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
if not self._initialized:
|
||||
self._subscribers = {}
|
||||
self._initialized = True
|
||||
|
||||
def subscribe(self, event_type: EventType, callback: Callable[[Dict[str, Any]], None]) -> None:
|
||||
"""
|
||||
订阅事件
|
||||
|
||||
Args:
|
||||
event_type: 事件类型
|
||||
callback: 回调函数,接收事件数据
|
||||
"""
|
||||
if event_type not in self._subscribers:
|
||||
self._subscribers[event_type] = []
|
||||
|
||||
if callback not in self._subscribers[event_type]:
|
||||
self._subscribers[event_type].append(callback)
|
||||
|
||||
def unsubscribe(self, event_type: EventType, callback: Callable[[Dict[str, Any]], None]) -> None:
|
||||
"""
|
||||
取消订阅事件
|
||||
|
||||
Args:
|
||||
event_type: 事件类型
|
||||
callback: 回调函数
|
||||
"""
|
||||
if event_type in self._subscribers and callback in self._subscribers[event_type]:
|
||||
self._subscribers[event_type].remove(callback)
|
||||
|
||||
def publish(self, event_type: EventType, data: Dict[str, Any]) -> None:
|
||||
"""
|
||||
发布事件
|
||||
|
||||
Args:
|
||||
event_type: 事件类型
|
||||
data: 事件数据
|
||||
"""
|
||||
if event_type in self._subscribers:
|
||||
for callback in self._subscribers[event_type]:
|
||||
try:
|
||||
callback(data)
|
||||
except Exception as e:
|
||||
print(f"事件处理错误: {e}")
|
||||
|
||||
def get_subscribers(self, event_type: EventType) -> List[Callable]:
|
||||
"""
|
||||
获取事件订阅者
|
||||
|
||||
Args:
|
||||
event_type: 事件类型
|
||||
|
||||
Returns:
|
||||
订阅者列表
|
||||
"""
|
||||
return self._subscribers.get(event_type, [])
|
||||
@@ -12,7 +12,6 @@ from base.plugin_common.plugin_interface import PluginInterface, PluginStatus
|
||||
from base.plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
from base.plugin_common.scheduled_plugin_interface import ScheduledPluginInterface
|
||||
from base.plugin_common.plugin_registry import PluginRegistry
|
||||
from base.plugin_common.event_system import EventSystem, EventType
|
||||
from utils.decorator.async_job import async_job
|
||||
from wechat_ipad import WechatAPIClient
|
||||
|
||||
@@ -431,9 +430,6 @@ class PluginManager:
|
||||
self._refresh_module_file_state(module_name)
|
||||
# self.LOG.info(f"PluginManager:添加模块映射 {module_name} -> {display_name}")
|
||||
|
||||
# 发布插件加载事件
|
||||
EventSystem().publish(EventType.PLUGIN_LOADED, {"plugin": plugin})
|
||||
|
||||
return plugin
|
||||
else:
|
||||
self.LOG.error(f"PluginManager:插件模块 {module_name} 的 get_plugin() 返回的不是有效的插件实例")
|
||||
@@ -483,9 +479,6 @@ class PluginManager:
|
||||
self._refresh_module_file_state(module_name)
|
||||
# self.LOG.info(f"PluginManager:添加模块映射 {module_name} -> {display_name}")
|
||||
|
||||
# 发布插件加载事件
|
||||
EventSystem().publish(EventType.PLUGIN_LOADED, {"plugin": plugin})
|
||||
|
||||
return plugin
|
||||
|
||||
except Exception as e:
|
||||
@@ -544,9 +537,6 @@ class PluginManager:
|
||||
# 移除插件实例
|
||||
del self.plugins[display_name]
|
||||
|
||||
# 发布插件卸载事件
|
||||
EventSystem().publish(EventType.PLUGIN_UNLOADED, {"plugin_name": display_name})
|
||||
|
||||
return True
|
||||
|
||||
def reload_plugin(self, name: str) -> Optional[PluginInterface]:
|
||||
|
||||
Reference in New Issue
Block a user