refactor(websocket): 移除连接池模式并改进资源清理

移除 WebSocket 连接池实现,改为单连接模式以简化代码结构
在 main 函数中添加资源清理逻辑,确保程序退出时正确关闭所有资源
改进 base64 数据处理逻辑,支持递归处理嵌套结构中的敏感数据

呵呵线程池加WS是神人
This commit is contained in:
2026-01-23 18:24:59 +08:00
parent 38bb10ccd9
commit cd5875be24
4 changed files with 129 additions and 460 deletions

View File

@@ -38,15 +38,26 @@ class BaseAPI:
try:
# 日志记录前,对敏感或过长的参数进行处理
log_params = copy.deepcopy(params)
if 'message' in log_params:
if isinstance(log_params['message'], list):
for segment in log_params['message']:
if segment.get('type') == 'image' and 'file' in segment.get('data', {}):
file_data = segment['data']['file']
if file_data.startswith('data:image/'):
segment['data']['file'] = f"{file_data[:50]}... (base64 truncated)"
elif isinstance(log_params['message'], str) and log_params['message'].startswith('data:image/'):
log_params['message'] = f"{log_params['message'][:50]}... (base64 truncated)"
# 处理各种可能包含base64数据的字段
def truncate_base64_recursive(obj):
"""递归处理可能包含base64数据的对象"""
if isinstance(obj, dict):
for key, value in obj.items():
if isinstance(value, str):
if value.startswith('data:image/') or value.startswith('data:video/') or value.startswith('data:audio/'):
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"]:
@@ -62,8 +73,13 @@ class BaseAPI:
logger.error(f"发送消息计数失败: {e}")
logger.debug(f"调用API -> action: {action}, params: {log_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":
logger.warning(f"API调用失败: {response}")