feat: 添加多线程架构支持并优化性能
实现线程管理器以支持高并发场景,添加GIL-free模式提升Python 3.14下的多线程性能 新增B站API集成和本地文件服务器功能,改进镜像插件支持GIF处理 更新文档说明多线程架构和GIL-free模式的使用方法
This commit is contained in:
33
core/ws.py
33
core/ws.py
@@ -15,6 +15,7 @@ import asyncio
|
||||
import orjson
|
||||
from typing import TYPE_CHECKING, Any, Dict, Optional, cast
|
||||
import uuid
|
||||
import threading
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .bot import Bot
|
||||
@@ -59,6 +60,9 @@ class WS:
|
||||
self.self_id: int | None = None
|
||||
self.code_executor = code_executor
|
||||
|
||||
# 线程安全锁
|
||||
self._pending_requests_lock = threading.RLock()
|
||||
|
||||
# 创建模块专用日志记录器
|
||||
self.logger = ModuleLogger("WebSocket")
|
||||
|
||||
@@ -123,9 +127,10 @@ class WS:
|
||||
# 如果消息中包含 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)
|
||||
with self._pending_requests_lock:
|
||||
future = self._pending_requests.pop(echo_id)
|
||||
if not future.done():
|
||||
future.set_result(data)
|
||||
continue
|
||||
|
||||
# 2. 处理上报事件
|
||||
@@ -229,12 +234,13 @@ class WS:
|
||||
|
||||
if self.ws:
|
||||
await self.ws.close()
|
||||
|
||||
|
||||
# 取消所有挂起的请求
|
||||
for future in self._pending_requests.values():
|
||||
if not future.done():
|
||||
future.cancel()
|
||||
self._pending_requests.clear()
|
||||
with self._pending_requests_lock:
|
||||
for future in self._pending_requests.values():
|
||||
if not future.done():
|
||||
future.cancel()
|
||||
self._pending_requests.clear()
|
||||
|
||||
self.logger.success("WebSocket 客户端已关闭")
|
||||
|
||||
@@ -276,13 +282,15 @@ class WS:
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
future = loop.create_future()
|
||||
self._pending_requests[echo_id] = future
|
||||
|
||||
with self._pending_requests_lock:
|
||||
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)
|
||||
with self._pending_requests_lock:
|
||||
self._pending_requests.pop(echo_id, None)
|
||||
self.logger.warning(f"API 调用超时: action={action}, params={params}")
|
||||
return create_error_response(
|
||||
code=ErrorCode.TIMEOUT_ERROR,
|
||||
@@ -290,7 +298,8 @@ class WS:
|
||||
data={"action": action, "params": params}
|
||||
)
|
||||
except Exception as e:
|
||||
self._pending_requests.pop(echo_id, None)
|
||||
with self._pending_requests_lock:
|
||||
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,
|
||||
|
||||
Reference in New Issue
Block a user