fix: 修复 ManageApiClient 关闭期间的连接池创建竞态

This commit is contained in:
3030332422 2026-09-07 11:14:50 +08:00
parent 82e3c1874f
commit 32cba36237

View file

@ -60,31 +60,33 @@ class ManageApiClient:
"""确保异步客户端已创建(为每个事件循环创建独立的客户端)""" """确保异步客户端已创建(为每个事件循环创建独立的客户端)"""
import asyncio import asyncio
if cls._closed:
raise Exception("ManageApiClient已关闭,不再创建新的HTTP客户端")
try: try:
loop = asyncio.get_running_loop() loop = asyncio.get_running_loop()
loop_id = id(loop) loop_id = id(loop)
# 为每个事件循环创建独立的客户端 # 检查关闭状态与创建连接池必须是同一个临界区,避免 safe_close()
if loop_id not in cls._async_clients: # 清空连接池后又有请求将新客户端写回。
# 服务端可能主动关闭连接,httpx 连接池无法正确检测和清理 with cls._instance_lock:
limits = httpx.Limits( if cls._closed:
max_keepalive_connections=0, # 禁用 keep-alive,每次都新建连接 raise Exception("ManageApiClient已关闭,不再创建新的HTTP客户端")
)
cls._async_clients[loop_id] = httpx.AsyncClient( if loop_id not in cls._async_clients:
base_url=cls.config.get("url"), # 服务端可能主动关闭连接,httpx 连接池无法正确检测和清理
headers={ limits = httpx.Limits(
"User-Agent": f"PythonClient/2.0 (PID:{os.getpid()})", max_keepalive_connections=0, # 禁用 keep-alive,每次都新建连接
"Accept": "application/json", )
"Authorization": "Bearer " + cls._secret, cls._async_clients[loop_id] = httpx.AsyncClient(
}, base_url=cls.config.get("url"),
timeout=cls.config.get("timeout", 30), headers={
limits=limits, # 使用限制 "User-Agent": f"PythonClient/2.0 (PID:{os.getpid()})",
trust_env=False, "Accept": "application/json",
) "Authorization": "Bearer " + cls._secret,
return cls._async_clients[loop_id] },
timeout=cls.config.get("timeout", 30),
limits=limits, # 使用限制
trust_env=False,
)
return cls._async_clients[loop_id]
except RuntimeError: except RuntimeError:
# 如果没有运行中的事件循环,创建一个临时的 # 如果没有运行中的事件循环,创建一个临时的
raise Exception("必须在异步上下文中调用") raise Exception("必须在异步上下文中调用")
@ -176,14 +178,16 @@ class ManageApiClient:
with cls._instance_lock: with cls._instance_lock:
cls._closed = True cls._closed = True
for client in list(cls._async_clients.values()): clients = list(cls._async_clients.values())
try:
asyncio.run(client.aclose())
except Exception:
pass
cls._async_clients.clear() cls._async_clients.clear()
cls._instance = None cls._instance = None
for client in clients:
try:
asyncio.run(client.aclose())
except Exception:
pass
def api_guard(error_msg: str = None, raise_when_closed: bool = False): def api_guard(error_msg: str = None, raise_when_closed: bool = False):
"""装饰器:统一获取单例实例、判空与异常兜底 """装饰器:统一获取单例实例、判空与异常兜底