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

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

View file

@ -60,14 +60,16 @@ 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()
# 清空连接池后又有请求将新客户端写回。
with cls._instance_lock:
if cls._closed:
raise Exception("ManageApiClient已关闭,不再创建新的HTTP客户端")
if loop_id not in cls._async_clients: if loop_id not in cls._async_clients:
# 服务端可能主动关闭连接,httpx 连接池无法正确检测和清理 # 服务端可能主动关闭连接,httpx 连接池无法正确检测和清理
limits = httpx.Limits( limits = httpx.Limits(
@ -176,13 +178,15 @@ 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())
cls._async_clients.clear()
cls._instance = None
for client in clients:
try: try:
asyncio.run(client.aclose()) asyncio.run(client.aclose())
except Exception: except Exception:
pass pass
cls._async_clients.clear()
cls._instance = None
def api_guard(error_msg: str = None, raise_when_closed: bool = False): def api_guard(error_msg: str = None, raise_when_closed: bool = False):