Dev (#55)
* 滚木
* feat: 重构核心架构,增强类型安全与插件管理
本次提交对核心模块进行了深度重构,引入 Pydantic 增强配置管理的类型安全性,并全面优化了插件管理系统。
主要变更详情:
1. 核心架构与配置
- 重构配置加载模块:引入 Pydantic 模型 (`core/config_models.py`),提供严格的配置项类型检查、验证及默认值管理。
- 统一模块结构:规范化模块导入路径,移除冗余的 `__init__.py` 文件,提升项目结构的清晰度。
- 性能优化:集成 Redis 缓存支持 (`RedisManager`),有效降低高频 API 调用开销,提升响应速度。
2. 插件系统升级
- 实现热重载机制:新增插件文件变更监听功能,支持开发过程中自动重载插件,提升开发效率。
- 优化生命周期管理:改进插件加载与卸载逻辑,支持精确卸载指定插件及其关联的命令、事件处理器和定时任务。
3. 功能特性增强
- 新增媒体 API:引入 `MediaAPI` 模块,封装图片、语音等富媒体资源的获取与处理接口。
- 完善权限体系:重构权限管理系统,实现管理员与操作员的分级控制,支持更细粒度的命令权限校验。
4. 代码质量与稳定性
- 全面类型修复:解决 `mypy` 静态类型检查发现的大量类型错误(包括 `CommandManager`、`EventFactory` 及 `Bot` API 签名不匹配问题)。
- 增强错误处理:优化消息处理管道的异常捕获机制,完善关键路径的日志记录,提升系统运行稳定性。
* feat: 添加测试用例并优化代码结构
refactor(permission_manager): 调整初始化顺序和逻辑
fix(admin_manager): 修复初始化逻辑和目录创建问题
feat(ws): 优化Bot实例初始化条件
feat(message): 增强MessageSegment功能并添加测试
feat(events): 支持字符串格式的消息解析
test: 添加核心功能测试用例
refactor(plugin_manager): 改进插件路径处理
style: 清理无用导入和代码
chore: 更新依赖项
* refactor(handler): 移除TYPE_CHECKING并直接导入Bot类
简化类型注解,直接导入Bot类而非使用TYPE_CHECKING条件导入,提高代码可读性和维护性
* fix(command_manager): 修复插件卸载时元信息移除不精确的问题
修复 CommandManager 中 unload_plugin 方法移除插件元信息时使用 startswith 导致可能误删其他插件的问题,改为精确匹配
同时调整相关测试用例验证精确匹配行为
* refactor: 清理未使用的导入和更新文档结构
docs: 添加config_models.py到项目结构文档
docs: 调整数据目录位置到core/data下
docs: 更新权限管理器文档描述
* 文档更新
* 更新thpic插件 支持一次返回多张图
* feat: 添加测试覆盖率并修复相关问题
refactor(redis_manager): 移除冗余的ConnectionError处理
refactor(event_handler): 优化Bot类型注解
refactor(factory): 移除未使用的GroupCardNoticeEvent
test: 添加全面的单元测试覆盖
- 添加test_import.py测试模块导入
- 添加test_debug.py测试插件加载调试
- 添加test_plugin_error.py测试错误处理
- 添加test_config_loader.py测试配置加载
- 添加test_redis_manager.py测试Redis管理
- 添加test_bot.py测试Bot功能
- 扩展test_models.py测试消息模型
- 添加test_plugin_manager_coverage.py测试插件管理
- 添加test_executor.py测试代码执行器
- 添加test_ws.py测试WebSocket
- 添加test_api.py测试API接口
- 添加test_core_managers.py测试核心管理模块
fix(plugin_manager): 修复插件加载日志变量问题
覆盖率已到达86%(忽略插件)
* 更新/help指令,现在会发送图片
* feat(help): 重构帮助系统为图片渲染模式
添加浏览器管理器和图片管理器,用于通过 Playwright 渲染帮助菜单为图片
重构命令管理器以支持图片缓存和同步功能
添加 HTML 模板用于帮助菜单渲染
* build: 更新依赖文件 requirements.txt
* build: 更新依赖文件
* feat: 添加性能优化和架构文档,更新依赖和核心模块
refactor(browser_manager): 实现页面池机制以提升性能
refactor(image_manager): 添加模板缓存并集成页面池
refactor(bili_parser): 迁移到异步HTTP请求并实现会话复用
docs: 新增性能优化、架构设计和最佳实践文档
chore: 更新requirements.txt添加新依赖
* docs: 更新文档内容并优化语言风格
重构所有文档内容,使用更简洁直接的语言风格
更新架构、插件开发、部署等核心文档
优化代码示例和图表说明
统一术语和格式规范
* docs: 更新文档内容,简化语言并修正格式
- 简化插件开发指南中的描述,移除冗余内容
- 调整部署文档中的Python版本说明
- 优化最佳实践文档的措辞和格式
- 更新性能优化文档,删除不准确的数据
- 重构核心概念文档,使用更简洁的语言
- 修正README中的项目描述和技术栈说明
- 更新快速上手文档,简化安装步骤
- 调整事件流转文档的描述方式
- 简化架构文档内容
- 更新指令处理文档,添加参数注入示例
- 优化单例管理器文档的表述
* refactor(core): 优化权限管理和事件模型
- 重构 AdminManager 和 PermissionManager 以 Redis 为主要数据源
- 为所有事件模型添加 slots=True 提升性能
- 更新文档说明 Mypyc 编译注意事项
- 清理测试和调试文件
- 移动静态资源到 web_static 目录
* feat: 添加模块编译脚本和导出依赖功能
refactor(events): 移除数据类的slots参数以提升兼容性
build: 更新requirements.txt依赖列表
* docs: 更新性能优化文档并修复命令管理器帮助输出
更新性能优化相关文档,详细说明 Python 3.14 JIT 编译器的使用方法和原理,补充与 Mypyc 的互补策略。同时修复命令管理器中帮助信息的输出方式,移除图片发送仅保留文本输出。
调整部署文档结构,明确两种性能优化方案(AOT 和 JIT)的配置方法和适用场景。完善架构文档中关于 JIT 的原理和启用方式说明。
* feat(help): 重构帮助菜单界面并优化样式
refactor(bili_parser): 修复 API 响应 content-type 问题
fix(command_manager): 添加帮助图片获取的错误处理
docs(deployment): 简化部署文档并移除 JIT 相关内容
* feat: 新增自动同意请求插件和API文档
docs: 更新文档结构和内容
* refactor(scripts): 重构并优化脚本文件结构
feat(scripts): 添加Python环境检查脚本
feat(scripts): 增强依赖导出脚本功能
perf(plugins/bili_parser): 优化B站解析器性能和代码结构
style(plugins/bili_parser): 统一代码风格和常量命名
* fix(scripts): 修复编码问题并添加错误追踪
在compile_machine_code.py中添加utf-8编码设置以避免潜在编码问题
添加traceback.print_exc()以在编译失败时打印完整错误堆栈
更新.gitignore以忽略config.toml文件
* feat(性能分析): 实现性能分析工具模块并添加相关测试
添加性能分析工具模块,包括时间测量、内存分析和性能统计功能
添加测试文件和示例配置,完善性能分析工具的使用场景
在工具模块中实现单例装饰器并导出到__init__.py
* feat(douyin_parser): 新增抖音视频解析插件
refactor(performance): 移除未使用的asyncio导入并优化性能测试
style(compile_modules): 修正字符串引号格式
chore: 删除废弃的编译脚本和临时文件
fix(bili_parser): 增强B站链接解析的健壮性
refactor(singleton): 重构单例模式实现
docs: 更新配置文件和事件模型注释
* feat: 添加抖音视频解析插件并优化代码结构
添加抖音视频解析插件,支持自动解析抖音分享链接并提取视频信息。优化现有代码结构,包括:
- 重构单例模式实现
- 移除未使用的导入和文件
- 修复性能测试脚本中的异步调用
- 优化消息事件模型中的权限常量定义
- 改进编译脚本的错误处理
- 增强B站解析插件的稳定性
同时清理了多个废弃脚本和临时文件,提升代码可维护性。
* 1
* Delete core/data/temp/help_menu.png
* fix(权限管理): 增强权限检查的类型安全并修复权限引用
修复权限检查中可能传入非Permission类型导致的错误,将echo插件的权限引用从MessageEvent.ADMIN迁移到Permission.ADMIN
* redis取消tls
* feat(github_parser): 添加GitHub仓库信息查询功能
- 新增github_parser插件,支持通过命令或自动解析链接查询GitHub仓库信息
- 添加github_repo.html模板用于渲染仓库信息图片
- 优化图片管理器支持高质量截图和CSS缩放
- 重构消息事件类权限常量定义方式
- 更新帮助页面样式为三列布局并优化响应式设计
* feat(web_parser): 新增通用web链接解析插件框架
refactor: 重构B站、抖音、GitHub解析器为模块化结构
fix(executor): 增强docker容器错误处理和回调稳定性
style(templates): 优化帮助页面和代码执行结果的样式
perf(web_parser): 添加API缓存和消息去重机制
docs: 更新插件元信息和注释
chore: 移除旧的独立解析器插件文件
* refactor(managers): 重构单例管理器实现并优化代码结构
feat(ws_pool): 新增 WebSocket 连接池实现
perf(json): 使用 orjson 替代标准 json 库提升性能
style: 清理未使用的导入和冗余代码
docs: 更新架构文档和开发规范
test: 添加 WebSocket 连接池测试用例
fix(plugins): 修复自动审批插件 API 调用参数格式
* docs: 修正架构描述从单线程改为多线程
更新开发标准文档,将架构描述从"单线程异步架构"修正为"多线程异步架构",以准确反映实际架构设计
* refactor(permission): 重构权限管理系统,合并管理员管理功能
- 将 admin_manager 功能整合到 permission_manager 中,统一管理
- 采用文件为主、Redis 为辅的架构,确保数据一致性
- 实现原子操作机制,防止数据损坏
- 更新文档说明新的权限管理机制
- 调整相关模块引用和编译配置
* feat: 添加直接发送视频/图片功能并优化临时目录处理
refactor(WS): 使用TYPE_CHECKING优化导入并延迟导入Bot类
refactor(image_manager): 使用系统临时目录替代自定义临时目录
feat(bili/douyin): 添加直接发送视频/图片功能
chore: 删除forward_test插件并添加furry插件
refactor(main): 移除JIT检查代码并优化插件重载逻辑
* refactor(插件管理): 将插件加载逻辑移回main函数
插件加载逻辑从core/managers/__init__.py移回main.py的main函数中执行,使初始化流程更清晰
你妈的循环导入
* refactor(web_parser): 优化URL提取和抖音解析器逻辑
重构URL提取逻辑,合并所有文本段处理分割链接并清理末尾标点
简化抖音解析器实现,移除冗余头部信息并改进URL验证
删除未使用的鸭子示例代码文件
* feat: 添加状态监控插件和Redis原子操作支持
- 新增 `/status` 指令,展示机器人运行状态和系统指标
- 实现Redis Lua脚本支持原子化计数器操作
- 添加消息收发统计功能
- 完善文档,包括插件开发和性能优化指南
- 重构WebSocket连接池,增加健康检查机制
- 移除旧版编译脚本,优化项目结构
* refactor(permission_manager): 移除合并冲突标记和未使用的装饰器
清理代码中的合并冲突标记(HEAD和分支标记)并删除未使用的require_admin装饰器函数,以保持代码整洁
* chore: 清理依赖和文档,优化消息事件类
- 移除不再使用的 psutil 依赖
- 删除文档中多余的进阶阅读部分
- 为消息事件类添加 ClassVar 类型导入并修复文件结尾格式
* fix: 移除重复的代码和文档内容
- 删除main.py中重复的sync_help_pic调用
- 删除plugin_manager.py中重复的__all__声明
- 清理performance.md中已移除的WebSocket连接池文档
* refactor(WS): 使用连接池上下文管理器简化连接管理
重构 WS 类中的连接获取和释放逻辑,使用 connection 上下文管理器确保连接正确释放。
同时改进消息处理循环中的异常处理和连接管理。
refactor(ws_pool): 增强连接池的健壮性和管理能力
1. 添加连接上下文管理器支持
2. 改进连接获取和释放逻辑,增加连接计数和锁保护
3. 优化连接健康检查和清理机制
4. 增强错误处理和日志记录
fix(bot_status): 增加系统信息获取和渲染的错误处理
1. 为系统信息获取添加超时和错误处理
2. 为Redis数据获取添加异常捕获
3. 为图片渲染添加异常处理
4. 改进日志记录和用户反馈
* refactor(compile_machine_code): 优化编译脚本并移除冗余日志
docs(getting-started): 删除中文依赖说明
refactor(image_manager): 简化base64图片生成逻辑
* refactor(api): 简化 dataclass 转换逻辑并添加好友/群列表缓存
移除冗余的 _safe_dataclass_from_dict 工具函数,直接使用 dataclass 的构造方法
添加 get_friend_list 和 get_group_list 方法的缓存支持
修复 get_version_info 的错误 API 调用
* Revert "refactor(WS): 使用连接池上下文管理器简化连接管理"
This reverts commit c851b49db9.
* refactor(websocket): 移除连接池模式并改进资源清理
移除 WebSocket 连接池实现,改为单连接模式以简化代码结构
在 main 函数中添加资源清理逻辑,确保程序退出时正确关闭所有资源
改进 base64 数据处理逻辑,支持递归处理嵌套结构中的敏感数据
呵呵线程池加WS是神人
---------
Co-authored-by: baby20162016 <2185823427@qq.com>
Co-authored-by: web vscode <youremail@example.com>
This commit is contained in:
284
core/WS.py
284
core/WS.py
@@ -32,7 +32,6 @@ from .utils.exceptions import (
|
|||||||
WebSocketError, WebSocketConnectionError
|
WebSocketError, WebSocketConnectionError
|
||||||
)
|
)
|
||||||
from .utils.error_codes import ErrorCode, create_error_response
|
from .utils.error_codes import ErrorCode, create_error_response
|
||||||
from .ws_pool import WSConnectionPool
|
|
||||||
|
|
||||||
|
|
||||||
class WS:
|
class WS:
|
||||||
@@ -40,14 +39,13 @@ class WS:
|
|||||||
WebSocket 客户端,负责与 OneBot v11 实现进行底层通信。
|
WebSocket 客户端,负责与 OneBot v11 实现进行底层通信。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, code_executor: Optional[CodeExecutor] = None, use_pool: bool = True) -> None:
|
def __init__(self, code_executor: Optional[CodeExecutor] = None) -> None:
|
||||||
"""
|
"""
|
||||||
初始化 WebSocket 客户端。
|
初始化 WebSocket 客户端。
|
||||||
|
|
||||||
从全局配置中读取 WebSocket URI、访问令牌(Token)和重连间隔。
|
从全局配置中读取 WebSocket URI、访问令牌(Token)和重连间隔。
|
||||||
|
|
||||||
:param code_executor: 代码执行器实例
|
:param code_executor: 代码执行器实例
|
||||||
:param use_pool: 是否使用连接池
|
|
||||||
"""
|
"""
|
||||||
# 读取参数
|
# 读取参数
|
||||||
cfg = global_config.napcat_ws
|
cfg = global_config.napcat_ws
|
||||||
@@ -61,8 +59,6 @@ class WS:
|
|||||||
self.bot: 'Bot' | None = None
|
self.bot: 'Bot' | None = None
|
||||||
self.self_id: int | None = None
|
self.self_id: int | None = None
|
||||||
self.code_executor = code_executor
|
self.code_executor = code_executor
|
||||||
self.use_pool = use_pool
|
|
||||||
self.pool: Optional[WSConnectionPool] = None
|
|
||||||
|
|
||||||
# 创建模块专用日志记录器
|
# 创建模块专用日志记录器
|
||||||
self.logger = ModuleLogger("WebSocket")
|
self.logger = ModuleLogger("WebSocket")
|
||||||
@@ -76,109 +72,39 @@ class WS:
|
|||||||
"""
|
"""
|
||||||
headers = {"Authorization": f"Bearer {self.token}"} if self.token else {}
|
headers = {"Authorization": f"Bearer {self.token}"} if self.token else {}
|
||||||
|
|
||||||
if self.use_pool:
|
|
||||||
# 使用连接池模式
|
|
||||||
self.pool = WSConnectionPool(pool_size=3)
|
|
||||||
await self.pool.initialize()
|
|
||||||
self.logger.success("WebSocket 连接池初始化完成")
|
|
||||||
|
|
||||||
# 启动连接池监听循环
|
|
||||||
await self._pool_listen_loop()
|
|
||||||
else:
|
|
||||||
# 单连接模式
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
self.logger.info(f"正在尝试连接至 NapCat: {self.url}")
|
|
||||||
async with websockets.connect(
|
|
||||||
self.url, additional_headers=headers
|
|
||||||
) as websocket_raw:
|
|
||||||
websocket = cast(WebSocketClientProtocol, websocket_raw)
|
|
||||||
self.ws = websocket
|
|
||||||
self.logger.success("连接成功!")
|
|
||||||
await self._listen_loop(websocket)
|
|
||||||
|
|
||||||
except (
|
|
||||||
websockets.exceptions.ConnectionClosed,
|
|
||||||
ConnectionRefusedError,
|
|
||||||
) as e:
|
|
||||||
conn_error = WebSocketConnectionError(
|
|
||||||
message=f"WebSocket连接失败: {str(e)}",
|
|
||||||
code=ErrorCode.WS_CONNECTION_FAILED,
|
|
||||||
original_error=e
|
|
||||||
)
|
|
||||||
self.logger.error(f"连接失败: {conn_error.message}")
|
|
||||||
self.logger.log_custom_exception(conn_error)
|
|
||||||
except Exception as e:
|
|
||||||
error = WebSocketError(
|
|
||||||
message=f"WebSocket运行异常: {str(e)}",
|
|
||||||
code=ErrorCode.WS_MESSAGE_ERROR,
|
|
||||||
original_error=e
|
|
||||||
)
|
|
||||||
self.logger.exception(f"运行异常: {error.message}")
|
|
||||||
self.logger.log_custom_exception(error)
|
|
||||||
|
|
||||||
self.logger.info(f"{self.reconnect_interval}秒后尝试重连...")
|
|
||||||
await asyncio.sleep(self.reconnect_interval)
|
|
||||||
|
|
||||||
async def _pool_listen_loop(self):
|
|
||||||
"""
|
|
||||||
连接池模式下的监听循环
|
|
||||||
"""
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
# 从连接池获取一个连接
|
self.logger.info(f"正在尝试连接至 NapCat: {self.url}")
|
||||||
# 使用 connection 上下文管理器确保释放
|
async with websockets.connect(
|
||||||
async with self.pool.connection() as conn:
|
self.url, additional_headers=headers
|
||||||
try:
|
) as websocket_raw:
|
||||||
# 监听连接上的消息
|
websocket = cast(WebSocketClientProtocol, websocket_raw)
|
||||||
async for message in conn.conn:
|
self.ws = websocket
|
||||||
await self._handle_message(message, conn)
|
self.logger.success("连接成功!")
|
||||||
except Exception as e:
|
await self._listen_loop(websocket)
|
||||||
self.logger.error(f"连接 {conn.conn_id} 监听异常: {e}")
|
|
||||||
|
except (
|
||||||
|
websockets.exceptions.ConnectionClosed,
|
||||||
|
ConnectionRefusedError,
|
||||||
|
) as e:
|
||||||
|
conn_error = WebSocketConnectionError(
|
||||||
|
message=f"WebSocket连接失败: {str(e)}",
|
||||||
|
code=ErrorCode.WS_CONNECTION_FAILED,
|
||||||
|
original_error=e
|
||||||
|
)
|
||||||
|
self.logger.error(f"连接失败: {conn_error.message}")
|
||||||
|
self.logger.log_custom_exception(conn_error)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.error(f"连接池监听循环异常: {e}")
|
error = WebSocketError(
|
||||||
await asyncio.sleep(self.reconnect_interval)
|
message=f"WebSocket运行异常: {str(e)}",
|
||||||
|
code=ErrorCode.WS_MESSAGE_ERROR,
|
||||||
|
original_error=e
|
||||||
|
)
|
||||||
|
self.logger.exception(f"运行异常: {error.message}")
|
||||||
|
self.logger.log_custom_exception(error)
|
||||||
|
|
||||||
async def _handle_message(self, message: str, conn):
|
self.logger.info(f"{self.reconnect_interval}秒后尝试重连...")
|
||||||
"""
|
await asyncio.sleep(self.reconnect_interval)
|
||||||
处理从连接池获取的消息
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
data = orjson.loads(message)
|
|
||||||
|
|
||||||
# 1. 处理 API 响应
|
|
||||||
# 如果消息中包含 echo 字段,说明是 API 调用的响应
|
|
||||||
echo_id = data.get("echo")
|
|
||||||
if echo_id and echo_id in self._pending_requests:
|
|
||||||
future = self._pending_requests.pop(echo_id)
|
|
||||||
if not future.done():
|
|
||||||
future.set_result(data)
|
|
||||||
return
|
|
||||||
|
|
||||||
# 2. 处理上报事件
|
|
||||||
# 如果消息中包含 post_type 字段,说明是 OneBot 上报的事件
|
|
||||||
if "post_type" in data:
|
|
||||||
# 使用 create_task 异步执行,避免阻塞 WebSocket 接收循环
|
|
||||||
asyncio.create_task(self.on_event(data))
|
|
||||||
|
|
||||||
except orjson.JSONDecodeError as e:
|
|
||||||
error = WebSocketError(
|
|
||||||
message=f"JSON解析失败: {str(e)}",
|
|
||||||
code=ErrorCode.WS_MESSAGE_ERROR,
|
|
||||||
original_error=e
|
|
||||||
)
|
|
||||||
self.logger.error(f"解析消息异常: {error.message}")
|
|
||||||
# 如果message是bytes类型,需要先解码
|
|
||||||
decoded_message = message.decode('utf-8') if isinstance(message, bytes) else message
|
|
||||||
self.logger.debug(f"原始消息: {decoded_message}")
|
|
||||||
except Exception as e:
|
|
||||||
error = WebSocketError(
|
|
||||||
message=f"处理消息异常: {str(e)}",
|
|
||||||
code=ErrorCode.WS_MESSAGE_ERROR,
|
|
||||||
original_error=e
|
|
||||||
)
|
|
||||||
self.logger.exception(f"解析消息异常: {error.message}")
|
|
||||||
self.logger.log_custom_exception(error)
|
|
||||||
|
|
||||||
async def _listen_loop(self, websocket_connection: WebSocketClientProtocol) -> None:
|
async def _listen_loop(self, websocket_connection: WebSocketClientProtocol) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -295,6 +221,23 @@ class WS:
|
|||||||
)
|
)
|
||||||
self.logger.log_custom_exception(error)
|
self.logger.log_custom_exception(error)
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
"""
|
||||||
|
关闭 WebSocket 客户端,释放资源。
|
||||||
|
"""
|
||||||
|
self.logger.info("正在关闭 WebSocket 客户端...")
|
||||||
|
|
||||||
|
if self.ws:
|
||||||
|
await self.ws.close()
|
||||||
|
|
||||||
|
# 取消所有挂起的请求
|
||||||
|
for future in self._pending_requests.values():
|
||||||
|
if not future.done():
|
||||||
|
future.cancel()
|
||||||
|
self._pending_requests.clear()
|
||||||
|
|
||||||
|
self.logger.success("WebSocket 客户端已关闭")
|
||||||
|
|
||||||
async def call_api(self, action: str, params: Optional[Dict[Any, Any]] = None) -> Dict[Any, Any]:
|
async def call_api(self, action: str, params: Optional[Dict[Any, Any]] = None) -> Dict[Any, Any]:
|
||||||
"""
|
"""
|
||||||
向 OneBot v11 实现端发送一个 API 请求。
|
向 OneBot v11 实现端发送一个 API 请求。
|
||||||
@@ -310,102 +253,47 @@ class WS:
|
|||||||
dict: OneBot API 的响应数据。如果超时或连接断开,则返回一个
|
dict: OneBot API 的响应数据。如果超时或连接断开,则返回一个
|
||||||
表示失败的字典。
|
表示失败的字典。
|
||||||
"""
|
"""
|
||||||
if self.use_pool:
|
if not self.ws:
|
||||||
# 使用连接池模式
|
self.logger.error("调用 API 失败: WebSocket 未初始化")
|
||||||
if not self.pool:
|
return create_error_response(
|
||||||
self.logger.error("调用 API 失败: WebSocket 连接池未初始化")
|
code=ErrorCode.WS_DISCONNECTED,
|
||||||
return create_error_response(
|
message="WebSocket未初始化",
|
||||||
code=ErrorCode.WS_DISCONNECTED,
|
data={"action": action, "params": params}
|
||||||
message="WebSocket连接池未初始化",
|
)
|
||||||
data={"action": action, "params": params}
|
|
||||||
)
|
|
||||||
|
|
||||||
# 从连接池获取一个连接
|
from websockets.protocol import State
|
||||||
try:
|
|
||||||
async with self.pool.connection() as conn:
|
|
||||||
echo_id = str(uuid.uuid4())
|
|
||||||
payload = {"action": action, "params": params or {}, "echo": echo_id}
|
|
||||||
|
|
||||||
await conn.send(orjson.dumps(payload))
|
if getattr(self.ws, "state", None) is not State.OPEN:
|
||||||
|
self.logger.error("调用 API 失败: WebSocket 连接未打开")
|
||||||
|
return create_error_response(
|
||||||
|
code=ErrorCode.WS_DISCONNECTED,
|
||||||
|
message="WebSocket连接未打开",
|
||||||
|
data={"action": action, "params": params}
|
||||||
|
)
|
||||||
|
|
||||||
# 在当前连接上等待特定 echo 的响应,并设置超时
|
echo_id = str(uuid.uuid4())
|
||||||
try:
|
payload = {"action": action, "params": params or {}, "echo": echo_id}
|
||||||
async def wait_for_response():
|
|
||||||
async for message in conn.conn:
|
|
||||||
data = orjson.loads(message)
|
|
||||||
|
|
||||||
# 检查是否是我们要的响应
|
loop = asyncio.get_running_loop()
|
||||||
if data.get("echo") == echo_id:
|
future = loop.create_future()
|
||||||
return data
|
self._pending_requests[echo_id] = future
|
||||||
|
|
||||||
# 如果不是,可能是事件,需要分发
|
try:
|
||||||
if "post_type" in data:
|
await self.ws.send(orjson.dumps(payload))
|
||||||
asyncio.create_task(self.on_event(data))
|
return await asyncio.wait_for(future, timeout=30.0)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
return await asyncio.wait_for(wait_for_response(), timeout=30.0)
|
self._pending_requests.pop(echo_id, None)
|
||||||
|
self.logger.warning(f"API 调用超时: action={action}, params={params}")
|
||||||
except asyncio.TimeoutError:
|
return create_error_response(
|
||||||
raise # 重新抛出超时异常
|
code=ErrorCode.TIMEOUT_ERROR,
|
||||||
except Exception as e:
|
message="API调用超时",
|
||||||
raise WebSocketError(f"在等待API响应时连接出错: {e}")
|
data={"action": action, "params": params}
|
||||||
|
)
|
||||||
except asyncio.TimeoutError:
|
except Exception as e:
|
||||||
self.logger.warning(f"API 调用超时: action={action}, params={params}")
|
self._pending_requests.pop(echo_id, None)
|
||||||
return create_error_response(
|
self.logger.exception(f"API 调用异常: action={action}, error={str(e)}")
|
||||||
code=ErrorCode.TIMEOUT_ERROR,
|
return create_error_response(
|
||||||
message="API调用超时",
|
code=ErrorCode.WS_MESSAGE_ERROR,
|
||||||
data={"action": action, "params": params}
|
message=f"API调用异常: {str(e)}",
|
||||||
)
|
data={"action": action, "params": params}
|
||||||
except Exception as e:
|
)
|
||||||
self.logger.exception(f"API 调用异常: action={action}, error={str(e)}")
|
|
||||||
return create_error_response(
|
|
||||||
code=ErrorCode.WS_MESSAGE_ERROR,
|
|
||||||
message=f"API调用异常: {str(e)}",
|
|
||||||
data={"action": action, "params": params}
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
# 单连接模式
|
|
||||||
if not self.ws:
|
|
||||||
self.logger.error("调用 API 失败: WebSocket 未初始化")
|
|
||||||
return create_error_response(
|
|
||||||
code=ErrorCode.WS_DISCONNECTED,
|
|
||||||
message="WebSocket未初始化",
|
|
||||||
data={"action": action, "params": params}
|
|
||||||
)
|
|
||||||
|
|
||||||
from websockets.protocol import State
|
|
||||||
|
|
||||||
if getattr(self.ws, "state", None) is not State.OPEN:
|
|
||||||
self.logger.error("调用 API 失败: WebSocket 连接未打开")
|
|
||||||
return create_error_response(
|
|
||||||
code=ErrorCode.WS_DISCONNECTED,
|
|
||||||
message="WebSocket连接未打开",
|
|
||||||
data={"action": action, "params": params}
|
|
||||||
)
|
|
||||||
|
|
||||||
echo_id = str(uuid.uuid4())
|
|
||||||
payload = {"action": action, "params": params or {}, "echo": echo_id}
|
|
||||||
|
|
||||||
loop = asyncio.get_running_loop()
|
|
||||||
future = loop.create_future()
|
|
||||||
self._pending_requests[echo_id] = future
|
|
||||||
|
|
||||||
try:
|
|
||||||
await self.ws.send(orjson.dumps(payload))
|
|
||||||
return await asyncio.wait_for(future, timeout=30.0)
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
self._pending_requests.pop(echo_id, None)
|
|
||||||
self.logger.warning(f"API 调用超时: action={action}, params={params}")
|
|
||||||
return create_error_response(
|
|
||||||
code=ErrorCode.TIMEOUT_ERROR,
|
|
||||||
message="API调用超时",
|
|
||||||
data={"action": action, "params": params}
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
self._pending_requests.pop(echo_id, None)
|
|
||||||
self.logger.exception(f"API 调用异常: action={action}, error={str(e)}")
|
|
||||||
return create_error_response(
|
|
||||||
code=ErrorCode.WS_MESSAGE_ERROR,
|
|
||||||
message=f"API调用异常: {str(e)}",
|
|
||||||
data={"action": action, "params": params}
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -38,15 +38,26 @@ class BaseAPI:
|
|||||||
try:
|
try:
|
||||||
# 日志记录前,对敏感或过长的参数进行处理
|
# 日志记录前,对敏感或过长的参数进行处理
|
||||||
log_params = copy.deepcopy(params)
|
log_params = copy.deepcopy(params)
|
||||||
if 'message' in log_params:
|
|
||||||
if isinstance(log_params['message'], list):
|
# 处理各种可能包含base64数据的字段
|
||||||
for segment in log_params['message']:
|
def truncate_base64_recursive(obj):
|
||||||
if segment.get('type') == 'image' and 'file' in segment.get('data', {}):
|
"""递归处理可能包含base64数据的对象"""
|
||||||
file_data = segment['data']['file']
|
if isinstance(obj, dict):
|
||||||
if file_data.startswith('data:image/'):
|
for key, value in obj.items():
|
||||||
segment['data']['file'] = f"{file_data[:50]}... (base64 truncated)"
|
if isinstance(value, str):
|
||||||
elif isinstance(log_params['message'], str) and log_params['message'].startswith('data:image/'):
|
if value.startswith('data:image/') or value.startswith('data:video/') or value.startswith('data:audio/'):
|
||||||
log_params['message'] = f"{log_params['message'][:50]}... (base64 truncated)"
|
obj[key] = f"{value[:50]}... (base64 truncated)"
|
||||||
|
elif len(value) > 100 and ('/' in value[:50] and '+' in value[:50] and '=' in value[-10:]):
|
||||||
|
# 检查是否是base64编码的字符串
|
||||||
|
obj[key] = f"{value[:50]}... (base64-like truncated)"
|
||||||
|
elif isinstance(value, (dict, list)):
|
||||||
|
truncate_base64_recursive(value)
|
||||||
|
elif isinstance(obj, list):
|
||||||
|
for item in obj:
|
||||||
|
if isinstance(item, (dict, list)):
|
||||||
|
truncate_base64_recursive(item)
|
||||||
|
|
||||||
|
truncate_base64_recursive(log_params)
|
||||||
|
|
||||||
# 如果是发送消息的动作,则原子化地增加发送消息总数
|
# 如果是发送消息的动作,则原子化地增加发送消息总数
|
||||||
if action in ["send_private_msg", "send_group_msg", "send_msg"]:
|
if action in ["send_private_msg", "send_group_msg", "send_msg"]:
|
||||||
@@ -62,8 +73,13 @@ class BaseAPI:
|
|||||||
logger.error(f"发送消息计数失败: {e}")
|
logger.error(f"发送消息计数失败: {e}")
|
||||||
|
|
||||||
logger.debug(f"调用API -> action: {action}, params: {log_params}")
|
logger.debug(f"调用API -> action: {action}, params: {log_params}")
|
||||||
|
|
||||||
response = await self._ws.call_api(action, params)
|
response = await self._ws.call_api(action, params)
|
||||||
logger.debug(f"API响应 <- {response}")
|
|
||||||
|
# 对响应也做类似的处理
|
||||||
|
log_response = copy.deepcopy(response)
|
||||||
|
truncate_base64_recursive(log_response)
|
||||||
|
logger.debug(f"API响应 <- {log_response}")
|
||||||
|
|
||||||
if response.get("status") == "failed":
|
if response.get("status") == "failed":
|
||||||
logger.warning(f"API调用失败: {response}")
|
logger.warning(f"API调用失败: {response}")
|
||||||
|
|||||||
328
core/ws_pool.py
328
core/ws_pool.py
@@ -1,328 +0,0 @@
|
|||||||
"""
|
|
||||||
WebSocket 连接池模块
|
|
||||||
|
|
||||||
该模块实现了 WebSocket 连接池功能,用于管理多个 WebSocket 连接,
|
|
||||||
提高并发处理能力和连接复用效率。
|
|
||||||
"""
|
|
||||||
import asyncio
|
|
||||||
import websockets
|
|
||||||
from websockets.legacy.client import WebSocketClientProtocol
|
|
||||||
from typing import Optional, Dict, Any, cast, Union, AsyncGenerator
|
|
||||||
import uuid
|
|
||||||
from loguru import logger
|
|
||||||
import contextlib
|
|
||||||
|
|
||||||
from .config_loader import global_config
|
|
||||||
from .utils.exceptions import WebSocketError, WebSocketConnectionError
|
|
||||||
|
|
||||||
|
|
||||||
class WSConnection:
|
|
||||||
"""
|
|
||||||
WebSocket 连接包装类
|
|
||||||
|
|
||||||
封装单个 WebSocket 连接的状态和操作
|
|
||||||
"""
|
|
||||||
def __init__(self, conn: WebSocketClientProtocol, conn_id: str):
|
|
||||||
self.conn = conn
|
|
||||||
self.conn_id = conn_id
|
|
||||||
self.last_used = asyncio.get_event_loop().time()
|
|
||||||
self.is_active = True
|
|
||||||
self._pending_requests: Dict[str, asyncio.Future] = {}
|
|
||||||
|
|
||||||
async def send(self, data: Union[Dict[Any, Any], bytes]):
|
|
||||||
"""
|
|
||||||
发送数据到 WebSocket 连接
|
|
||||||
"""
|
|
||||||
if not self.is_active:
|
|
||||||
raise WebSocketError(f"连接 {self.conn_id} 已关闭")
|
|
||||||
|
|
||||||
try:
|
|
||||||
await self.conn.send(data)
|
|
||||||
self.last_used = asyncio.get_event_loop().time()
|
|
||||||
except Exception as e:
|
|
||||||
self.is_active = False
|
|
||||||
raise WebSocketError(f"发送数据失败: {e}")
|
|
||||||
|
|
||||||
async def recv(self):
|
|
||||||
"""
|
|
||||||
从 WebSocket 连接接收数据
|
|
||||||
"""
|
|
||||||
if not self.is_active:
|
|
||||||
raise WebSocketError(f"连接 {self.conn_id} 已关闭")
|
|
||||||
|
|
||||||
try:
|
|
||||||
data = await self.conn.recv()
|
|
||||||
self.last_used = asyncio.get_event_loop().time()
|
|
||||||
return data
|
|
||||||
except Exception as e:
|
|
||||||
self.is_active = False
|
|
||||||
raise WebSocketError(f"接收数据失败: {e}")
|
|
||||||
|
|
||||||
async def ping(self, timeout: int = 5) -> bool:
|
|
||||||
"""
|
|
||||||
对 WebSocket 连接执行 ping-pong 健康检查
|
|
||||||
"""
|
|
||||||
if not self.is_active:
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
# 使用 wait_for 包装 ping
|
|
||||||
pong_waiter = await self.conn.ping()
|
|
||||||
await asyncio.wait_for(pong_waiter, timeout=timeout)
|
|
||||||
return True
|
|
||||||
except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed, Exception):
|
|
||||||
self.is_active = False
|
|
||||||
return False
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
"""
|
|
||||||
关闭 WebSocket 连接
|
|
||||||
"""
|
|
||||||
if self.is_active:
|
|
||||||
self.is_active = False
|
|
||||||
try:
|
|
||||||
await self.conn.close()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class WSConnectionPool:
|
|
||||||
"""
|
|
||||||
WebSocket 连接池
|
|
||||||
|
|
||||||
管理多个 WebSocket 连接,提供连接的获取、释放和回收功能
|
|
||||||
"""
|
|
||||||
def __init__(self, pool_size: int = 3, max_idle_time: int = 300):
|
|
||||||
"""
|
|
||||||
初始化连接池
|
|
||||||
|
|
||||||
:param pool_size: 连接池大小
|
|
||||||
:param max_idle_time: 连接最大空闲时间(秒)
|
|
||||||
"""
|
|
||||||
self.pool_size = pool_size
|
|
||||||
self.max_idle_time = max_idle_time
|
|
||||||
self.pool: asyncio.Queue[WSConnection] = asyncio.Queue(maxsize=pool_size)
|
|
||||||
self._closed = False
|
|
||||||
self._cleanup_task: Optional[asyncio.Task] = None
|
|
||||||
self._current_size = 0 # 当前管理的连接数(包括池中和借出的)
|
|
||||||
self._lock = asyncio.Lock() # 用于保护 _current_size 的修改
|
|
||||||
|
|
||||||
# 从全局配置读取参数
|
|
||||||
self.url = global_config.napcat_ws.uri
|
|
||||||
self.token = global_config.napcat_ws.token
|
|
||||||
self.reconnect_interval = global_config.napcat_ws.reconnect_interval
|
|
||||||
|
|
||||||
logger.info(f"WebSocket 连接池初始化完成,大小: {pool_size}")
|
|
||||||
|
|
||||||
async def initialize(self):
|
|
||||||
"""
|
|
||||||
初始化连接池,创建初始连接
|
|
||||||
"""
|
|
||||||
if self._closed:
|
|
||||||
raise WebSocketError("连接池已关闭")
|
|
||||||
|
|
||||||
# 启动连接清理任务
|
|
||||||
self._cleanup_task = asyncio.create_task(self._cleanup_idle_connections())
|
|
||||||
|
|
||||||
# 预热连接池
|
|
||||||
for _ in range(self.pool_size):
|
|
||||||
try:
|
|
||||||
conn = await self._create_connection()
|
|
||||||
await self.pool.put(conn)
|
|
||||||
async with self._lock:
|
|
||||||
self._current_size += 1
|
|
||||||
logger.info(f"WebSocket 连接 {conn.conn_id} 已创建并加入连接池")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"创建初始连接失败: {e}")
|
|
||||||
# 初始连接失败不抛出异常,允许后续动态创建
|
|
||||||
|
|
||||||
async def _create_connection(self) -> WSConnection:
|
|
||||||
"""
|
|
||||||
创建新的 WebSocket 连接
|
|
||||||
"""
|
|
||||||
headers = {"Authorization": f"Bearer {self.token}"} if self.token else {}
|
|
||||||
|
|
||||||
try:
|
|
||||||
conn_id = str(uuid.uuid4())
|
|
||||||
websocket_raw = await websockets.connect(
|
|
||||||
self.url, additional_headers=headers
|
|
||||||
)
|
|
||||||
websocket = cast(WebSocketClientProtocol, websocket_raw)
|
|
||||||
|
|
||||||
conn = WSConnection(websocket, conn_id)
|
|
||||||
logger.info(f"WebSocket 连接 {conn_id} 已建立")
|
|
||||||
return conn
|
|
||||||
except Exception as e:
|
|
||||||
raise WebSocketConnectionError(f"创建 WebSocket 连接失败: {e}")
|
|
||||||
|
|
||||||
@contextlib.asynccontextmanager
|
|
||||||
async def connection(self) -> AsyncGenerator[WSConnection, None]:
|
|
||||||
"""
|
|
||||||
获取连接的上下文管理器
|
|
||||||
"""
|
|
||||||
conn = await self.get_connection()
|
|
||||||
try:
|
|
||||||
yield conn
|
|
||||||
finally:
|
|
||||||
await self.release_connection(conn)
|
|
||||||
|
|
||||||
async def get_connection(self) -> WSConnection:
|
|
||||||
"""
|
|
||||||
从连接池获取一个健康的连接,包含健康检查。
|
|
||||||
"""
|
|
||||||
if self._closed:
|
|
||||||
raise WebSocketError("连接池已关闭")
|
|
||||||
|
|
||||||
start_time = asyncio.get_event_loop().time()
|
|
||||||
timeout = 10 # 获取连接的总超时时间
|
|
||||||
|
|
||||||
while True:
|
|
||||||
if asyncio.get_event_loop().time() - start_time > timeout:
|
|
||||||
raise WebSocketError("获取连接超时")
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 1. 尝试从池中获取
|
|
||||||
conn = self.pool.get_nowait()
|
|
||||||
|
|
||||||
# 健康检查
|
|
||||||
if await conn.ping():
|
|
||||||
logger.debug(f"连接 {conn.conn_id} 健康检查通过")
|
|
||||||
return conn
|
|
||||||
else:
|
|
||||||
logger.warning(f"连接 {conn.conn_id} 健康检查失败,丢弃")
|
|
||||||
await conn.close()
|
|
||||||
async with self._lock:
|
|
||||||
self._current_size -= 1
|
|
||||||
# 继续循环,尝试获取下一个或创建新的
|
|
||||||
continue
|
|
||||||
|
|
||||||
except asyncio.QueueEmpty:
|
|
||||||
# 池为空,检查是否可以创建新连接
|
|
||||||
async with self._lock:
|
|
||||||
if self._current_size < self.pool_size:
|
|
||||||
# 有配额,创建新连接
|
|
||||||
self._current_size += 1 # 先占位
|
|
||||||
create_new = True
|
|
||||||
else:
|
|
||||||
create_new = False
|
|
||||||
|
|
||||||
if create_new:
|
|
||||||
try:
|
|
||||||
conn = await self._create_connection()
|
|
||||||
return conn
|
|
||||||
except Exception as e:
|
|
||||||
async with self._lock:
|
|
||||||
self._current_size -= 1 # 回滚占位
|
|
||||||
logger.error(f"创建新连接失败: {e}")
|
|
||||||
await asyncio.sleep(1) # 避免快速失败循环
|
|
||||||
continue
|
|
||||||
else:
|
|
||||||
# 没有配额,等待池中有可用连接
|
|
||||||
try:
|
|
||||||
conn = await asyncio.wait_for(self.pool.get(), timeout=1.0)
|
|
||||||
# 获取到了,进行健康检查(在下一次循环中处理,或者这里直接处理)
|
|
||||||
# 为了代码复用,我们把 conn 放回去(或者直接用),这里直接用
|
|
||||||
if await conn.ping():
|
|
||||||
return conn
|
|
||||||
else:
|
|
||||||
await conn.close()
|
|
||||||
async with self._lock:
|
|
||||||
self._current_size -= 1
|
|
||||||
continue
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
continue
|
|
||||||
|
|
||||||
async def release_connection(self, conn: WSConnection):
|
|
||||||
"""
|
|
||||||
释放连接回连接池
|
|
||||||
"""
|
|
||||||
if self._closed:
|
|
||||||
await conn.close()
|
|
||||||
return
|
|
||||||
|
|
||||||
if not conn.is_active:
|
|
||||||
logger.warning(f"连接 {conn.conn_id} 已失效,不返回连接池")
|
|
||||||
await conn.close()
|
|
||||||
async with self._lock:
|
|
||||||
self._current_size -= 1
|
|
||||||
return
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 尝试放回池中
|
|
||||||
self.pool.put_nowait(conn)
|
|
||||||
logger.debug(f"连接 {conn.conn_id} 已返回连接池")
|
|
||||||
except asyncio.QueueFull:
|
|
||||||
# 理论上不应该发生,除非 _current_size 逻辑有误
|
|
||||||
logger.warning(f"连接池已满,关闭多余连接 {conn.conn_id}")
|
|
||||||
await conn.close()
|
|
||||||
async with self._lock:
|
|
||||||
self._current_size -= 1
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"释放连接失败: {e}")
|
|
||||||
await conn.close()
|
|
||||||
async with self._lock:
|
|
||||||
self._current_size -= 1
|
|
||||||
|
|
||||||
async def _cleanup_idle_connections(self):
|
|
||||||
"""
|
|
||||||
清理空闲连接任务
|
|
||||||
"""
|
|
||||||
while not self._closed:
|
|
||||||
await asyncio.sleep(60) # 每分钟检查一次
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 我们不替换队列,而是取出检查再放回
|
|
||||||
# 这样比较安全,但可能会暂时清空池子
|
|
||||||
# 更好的做法是只检查队头的连接
|
|
||||||
|
|
||||||
# 获取当前队列大小
|
|
||||||
qsize = self.pool.qsize()
|
|
||||||
for _ in range(qsize):
|
|
||||||
try:
|
|
||||||
conn = self.pool.get_nowait()
|
|
||||||
except asyncio.QueueEmpty:
|
|
||||||
break
|
|
||||||
|
|
||||||
current_time = asyncio.get_event_loop().time()
|
|
||||||
if current_time - conn.last_used > self.max_idle_time:
|
|
||||||
logger.info(f"清理空闲连接 {conn.conn_id}")
|
|
||||||
await conn.close()
|
|
||||||
async with self._lock:
|
|
||||||
self._current_size -= 1
|
|
||||||
else:
|
|
||||||
# 还没过期,放回去
|
|
||||||
try:
|
|
||||||
self.pool.put_nowait(conn)
|
|
||||||
except asyncio.QueueFull:
|
|
||||||
# 竞争条件下可能满了
|
|
||||||
await conn.close()
|
|
||||||
async with self._lock:
|
|
||||||
self._current_size -= 1
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"清理空闲连接失败: {e}")
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
"""
|
|
||||||
关闭连接池
|
|
||||||
"""
|
|
||||||
if self._closed:
|
|
||||||
return
|
|
||||||
|
|
||||||
self._closed = True
|
|
||||||
|
|
||||||
# 停止清理任务
|
|
||||||
if self._cleanup_task:
|
|
||||||
self._cleanup_task.cancel()
|
|
||||||
try:
|
|
||||||
await self._cleanup_task
|
|
||||||
except asyncio.CancelledError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# 关闭所有连接
|
|
||||||
while not self.pool.empty():
|
|
||||||
try:
|
|
||||||
conn = self.pool.get_nowait()
|
|
||||||
await conn.close()
|
|
||||||
except asyncio.QueueEmpty:
|
|
||||||
break
|
|
||||||
|
|
||||||
logger.info("WebSocket 连接池已关闭")
|
|
||||||
21
main.py
21
main.py
@@ -158,12 +158,13 @@ async def main():
|
|||||||
else:
|
else:
|
||||||
logger.warning(f"插件目录不存在 {plugin_path}")
|
logger.warning(f"插件目录不存在 {plugin_path}")
|
||||||
|
|
||||||
|
websocket_client = None
|
||||||
try:
|
try:
|
||||||
# 初始化代码执行器
|
# 初始化代码执行器
|
||||||
code_executor = initialize_executor(config)
|
code_executor = initialize_executor(config)
|
||||||
|
|
||||||
# 使用连接池模式初始化 WebSocket 客户端
|
# 初始化 WebSocket 客户端
|
||||||
websocket_client = WS(code_executor=code_executor, use_pool=True)
|
websocket_client = WS(code_executor=code_executor)
|
||||||
|
|
||||||
# 启动代码执行器的后台 worker
|
# 启动代码执行器的后台 worker
|
||||||
logger.debug("[Main] 检查是否需要启动代码执行 Worker...")
|
logger.debug("[Main] 检查是否需要启动代码执行 Worker...")
|
||||||
@@ -174,11 +175,22 @@ async def main():
|
|||||||
logger.warning("[Main] 未启动代码执行 Worker,因为 Docker 客户端未初始化或连接失败。")
|
logger.warning("[Main] 未启动代码执行 Worker,因为 Docker 客户端未初始化或连接失败。")
|
||||||
|
|
||||||
await websocket_client.connect()
|
await websocket_client.connect()
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
logger.info("主任务被取消,正在停止...")
|
||||||
finally:
|
finally:
|
||||||
|
logger.info("正在清理资源...")
|
||||||
if observer.is_alive():
|
if observer.is_alive():
|
||||||
observer.stop()
|
observer.stop()
|
||||||
observer.join()
|
observer.join()
|
||||||
|
|
||||||
|
if websocket_client:
|
||||||
|
await websocket_client.close()
|
||||||
|
|
||||||
|
# 关闭浏览器管理器
|
||||||
|
await browser_manager.shutdown()
|
||||||
|
|
||||||
|
logger.success("资源清理完成,程序退出。")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
"""
|
"""
|
||||||
@@ -193,8 +205,9 @@ if __name__ == "__main__":
|
|||||||
try:
|
try:
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
main_logger.info("程序已被用户中断")
|
# 捕获 KeyboardInterrupt,不做任何操作,让 asyncio.run 正常结束
|
||||||
exit(0)
|
# 这样 main 函数中的 finally 块会被执行
|
||||||
|
pass
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
main_logger.exception("程序发生未处理的全局异常")
|
main_logger.exception("程序发生未处理的全局异常")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user