fix(server): 修复临时事件循环结束后 HTTP 客户端未释放的问题 (#3416)

This commit is contained in:
Yanhan Ruan 2026-10-12 10:00:28 +08:00 committed by GitHub
parent c30c40bf56
commit ef1d24e40d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 235 additions and 70 deletions

View file

@ -22,7 +22,6 @@ class DeviceBindException(Exception):
class ManageApiClient:
_instance = None
_instance_lock = threading.Lock() # 保护 _instance 与 _closed 的读写
_async_clients = {} # 为每个事件循环存储独立的客户端
_secret = None
_closed = False # safe_close() 后置为 True,关闭后不再创建新连接
@ -52,72 +51,47 @@ class ManageApiClient:
cls.max_retries = cls.config.get("max_retries", 6) # 最大重试次数
cls.retry_delay = cls.config.get("retry_delay", 10) # 初始重试延迟(秒)
# 不在这里创建 AsyncClient,延迟到实际使用时创建
cls._async_clients = {}
cls._closed = False
@classmethod
async def _ensure_async_client(cls):
"""确保异步客户端已创建(为每个事件循环创建独立的客户端)"""
import asyncio
try:
loop = asyncio.get_running_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:
# 服务端可能主动关闭连接,httpx 连接池无法正确检测和清理
limits = httpx.Limits(
max_keepalive_connections=0, # 禁用 keep-alive,每次都新建连接
)
cls._async_clients[loop_id] = httpx.AsyncClient(
base_url=cls.config.get("url"),
headers={
"User-Agent": f"PythonClient/2.0 (PID:{os.getpid()})",
"Accept": "application/json",
"Authorization": "Bearer " + cls._secret,
},
timeout=cls.config.get("timeout", 30),
limits=limits, # 使用限制
trust_env=False,
)
return cls._async_clients[loop_id]
except RuntimeError:
# 如果没有运行中的事件循环,创建一个临时的
raise Exception("必须在异步上下文中调用")
"""创建请求专用客户端,避免临时事件循环的客户端永久累积。"""
with cls._instance_lock:
if cls._closed:
raise Exception("ManageApiClient已关闭,不再创建新的HTTP客户端")
return httpx.AsyncClient(
base_url=cls.config.get("url"),
headers={
"User-Agent": f"PythonClient/2.0 (PID:{os.getpid()})",
"Accept": "application/json",
"Authorization": "Bearer " + cls._secret,
},
timeout=cls.config.get("timeout", 30),
limits=httpx.Limits(max_keepalive_connections=0),
trust_env=False,
)
@classmethod
async def _async_request(cls, method: str, endpoint: str, **kwargs) -> Dict:
"""发送单次异步HTTP请求并处理响应"""
# 确保客户端已创建
"""客户端由本次请求持有,并在创建它的事件循环中关闭。"""
client = await cls._ensure_async_client()
endpoint = endpoint.lstrip("/")
response = None
try:
response = await client.request(method, endpoint, **kwargs)
response.raise_for_status()
result = response.json()
# 处理API返回的业务错误
if result.get("code") == 10041:
raise DeviceNotFoundException(result.get("msg"))
elif result.get("code") == 10042:
raise DeviceBindException(result.get("msg"))
elif result.get("code") != 0:
raise Exception(f"API返回错误: {result.get('msg', '未知错误')}")
# 返回成功数据
return result.get("data") if result.get("code") == 0 else None
finally:
# 确保响应被关闭(即使异常也会执行)
if response is not None:
await response.aclose()
async with client:
endpoint = endpoint.lstrip("/")
response = None
try:
response = await client.request(method, endpoint, **kwargs)
response.raise_for_status()
result = response.json()
if result.get("code") == 10041:
raise DeviceNotFoundException(result.get("msg"))
elif result.get("code") == 10042:
raise DeviceBindException(result.get("msg"))
elif result.get("code") != 0:
raise Exception(f"API返回错误: {result.get('msg', '未知错误')}")
return result.get("data") if result.get("code") == 0 else None
finally:
if response is not None:
await response.aclose()
@classmethod
def _should_retry(cls, exception: Exception) -> bool:
@ -173,21 +147,11 @@ class ManageApiClient:
@classmethod
def safe_close(cls):
"""安全关闭所有异步连接池"""
import asyncio
"""关闭请求入口;在途请求在各自事件循环中释放客户端。"""
with cls._instance_lock:
cls._closed = True
clients = list(cls._async_clients.values())
cls._async_clients.clear()
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):
"""装饰器:统一获取单例实例、判空与异常兜底

View file

@ -0,0 +1,62 @@
"""Offline reproduction: no real devices, credentials, HTTP server or model APIs.
Usage: python -B reproduce.py path/to/config/manage_api_client.py
Keeps CLOSED loop objects alive to avoid Python reusing their integer IDs.
This makes the cache-lifetime check deterministic; it is not an RSS benchmark.
"""
import asyncio
import gc
import importlib.util
import json
import sys
import weakref
from unittest.mock import patch
import httpx
def main():
spec = importlib.util.spec_from_file_location("client_under_test", sys.argv[1])
api = importlib.util.module_from_spec(spec)
spec.loader.exec_module(api)
cls = api.ManageApiClient
cls({"manager-api": {"url": "http://offline.invalid/xiaozhi",
"secret": "synthetic-test", "max_retries": 0}})
real_client = httpx.AsyncClient
refs, loops = [], []
def factory(**kwargs):
transport = httpx.MockTransport(
lambda request: httpx.Response(200, json={"code": 0, "data": True})
)
client = real_client(transport=transport, **kwargs)
refs.append(weakref.ref(client))
return client
try:
with patch.object(api.httpx, "AsyncClient", side_effect=factory):
for _ in range(100):
loop = asyncio.new_event_loop()
loops.append(loop)
try:
assert loop.run_until_complete(
cls._execute_async_request("POST", "/synthetic-report")
) is True
finally:
loop.close()
gc.collect()
retained = [ref() for ref in refs if ref() is not None]
print(json.dumps({
"requests_completed": 100,
"all_loops_closed": all(loop.is_closed() for loop in loops),
"cached_clients_after_gc": len(getattr(cls, "_async_clients", {})),
"live_clients_after_gc": len(retained),
"unclosed_clients_after_gc": sum(not client.is_closed for client in retained),
}, sort_keys=True))
finally:
cls.safe_close()
loops.clear()
if __name__ == "__main__":
main()

View file

@ -0,0 +1,139 @@
"""Run directly with unittest; no application/model dependencies or network."""
import asyncio
from concurrent.futures import ThreadPoolExecutor
import importlib.util
import os
from pathlib import Path
import unittest
from unittest.mock import patch
import httpx
class ManageApiClientLifecycleTest(unittest.IsolatedAsyncioTestCase):
def setUp(self):
source = Path(os.environ.get('CLIENT_UNDER_TEST', str(
Path(__file__).resolve().parents[1] / 'config/manage_api_client.py')))
spec = importlib.util.spec_from_file_location('_lifecycle_client', source)
self.api = importlib.util.module_from_spec(spec)
spec.loader.exec_module(self.api)
self.cls = self.api.ManageApiClient
self.cls({'manager-api': {'url': 'http://offline.invalid/xiaozhi',
'secret': 'synthetic-test', 'max_retries': 1, 'retry_delay': 0}})
self.clients = []
self.requests = []
self.real_client = httpx.AsyncClient
def transport(self, handler):
def factory(**kwargs):
async def handle(request):
self.requests.append(request)
return await handler(request)
client = self.real_client(transport=httpx.MockTransport(handle), **kwargs)
self.clients.append(client)
return client
return patch.object(self.api.httpx, 'AsyncClient', side_effect=factory)
async def asyncTearDown(self):
try:
self.assertTrue(all(c.is_closed for c in self.clients), 'client escaped its request')
finally:
for client in self.clients:
if not client.is_closed:
await client.aclose()
self.cls.safe_close()
async def test_success_preserves_url_headers_and_payload(self):
async def handle(request):
self.assertEqual(str(request.url), 'http://offline.invalid/xiaozhi/report')
self.assertEqual(request.headers['authorization'], 'Bearer synthetic-test')
self.assertEqual(request.content, b'{"value":123}')
return httpx.Response(200, json={'code': 0, 'data': {'ok': True}})
with self.transport(handle):
self.assertEqual(await self.cls._execute_async_request('POST', '/report',
json={'value': 123}), {'ok': True})
async def test_retry_closes_each_attempt(self):
async def handle(request):
if len(self.requests) == 1:
return httpx.Response(503)
self.assertTrue(self.clients[0].is_closed)
return httpx.Response(200, json={'code': 0, 'data': True})
with self.transport(handle):
self.assertTrue(await self.cls._execute_async_request('POST', '/report'))
self.assertEqual(len(self.clients), 2)
async def test_timeout_exhaustion_closes_all_attempts(self):
async def handle(request):
raise httpx.ReadTimeout('synthetic timeout', request=request)
with self.transport(handle), self.assertRaises(httpx.ReadTimeout):
await self.cls._execute_async_request('POST', '/report')
self.assertEqual(len(self.clients), 2)
async def test_nonretryable_http_error(self):
async def handle(request):
return httpx.Response(403)
with self.transport(handle), self.assertRaises(httpx.HTTPStatusError):
await self.cls._execute_async_request('POST', '/report')
self.assertEqual(len(self.clients), 1)
async def test_business_error_and_invalid_json_release_client(self):
for response, error in [
(httpx.Response(200, json={'code': 10041, 'msg': 'missing'}), self.api.DeviceNotFoundException),
(httpx.Response(200, json={'code': 10042, 'msg': 'bind'}), self.api.DeviceBindException),
(httpx.Response(200, content=b'not-json'), ValueError),
]:
async def handle(request):
return response
with self.transport(handle), self.assertRaises(error):
await self.cls._execute_async_request('POST', '/report')
self.assertTrue(self.clients[-1].is_closed)
self.assertEqual(len(self.clients), 3)
async def test_cancellation_does_not_close_concurrent_request(self):
entered = [asyncio.Event(), asyncio.Event()]
release = asyncio.Event()
async def handle(request):
index = len(self.requests) - 1
entered[index].set()
await release.wait()
return httpx.Response(200, json={'code': 0, 'data': True})
with self.transport(handle):
first = asyncio.create_task(self.cls._execute_async_request('POST', '/first'))
await asyncio.wait_for(entered[0].wait(), 2)
second = asyncio.create_task(self.cls._execute_async_request('POST', '/second'))
await asyncio.wait_for(entered[1].wait(), 2)
first.cancel()
with self.assertRaises(asyncio.CancelledError):
await first
self.assertTrue(self.clients[0].is_closed)
self.assertFalse(self.clients[1].is_closed)
release.set()
self.assertTrue(await asyncio.wait_for(second, 2))
async def test_shutdown_allows_inflight_cleanup_and_blocks_report_entry(self):
async def handle(request):
self.cls.safe_close()
return httpx.Response(200, json={'code': 0, 'data': True})
with self.transport(handle):
self.assertTrue(await self.api.report('device', 'session', 1, 'text', None, 0))
self.assertIsNone(await self.api.report('device', 'session', 1, 'later', None, 0))
if hasattr(self.cls, '_closed'):
with self.assertRaisesRegex(Exception, '已关闭'):
await self.cls._execute_async_request('POST', '/report')
self.assertEqual(len(self.clients), 1)
async def test_many_temporary_loops_leave_no_open_clients(self):
async def handle(request):
return httpx.Response(200, json={'code': 0, 'data': True})
def report_once(_):
return asyncio.run(self.cls._execute_async_request('POST', '/report'))
with self.transport(handle), ThreadPoolExecutor(max_workers=5) as pool:
results = list(pool.map(report_once, range(100)))
self.assertTrue(all(results))
self.assertEqual(len(self.clients), 100)
self.assertTrue(all(c.is_closed for c in self.clients))
if __name__ == '__main__':
unittest.main()