diff --git a/.github/dependabot.yml b/.github/dependabot.yml index af9906389..26db4f3c3 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -3,4 +3,40 @@ updates: - package-ecosystem: pip directory: /main/xiaozhi-server schedule: - interval: weekly \ No newline at end of file + interval: monthly + open-pull-requests-limit: 5 + groups: + ai-services: + patterns: + - "openai*" + - "google-generativeai" + - "dashscope" + - "baidu-aip" + - "cozepy" + - "markitdown" + - "mem0ai" + - "powermem" + ai-models: + patterns: + - "funasr" + - "vosk" + - "silero_vad" + - "opuslib_next" + - "sherpa_onnx" + - "modelscope" + web-stack: + patterns: + - "httpx" + - "aiohttp" + - "aiohttp_cors" + - "requests" + - "pysocks" + everything-else: + patterns: + - "*" + ignore: + - dependency-name: "torch" + - dependency-name: "torchaudio" + - dependency-name: "numpy" + - dependency-name: "portalocker" + - dependency-name: "websockets" diff --git a/main/manager-web/src/router/index.js b/main/manager-web/src/router/index.js index ad9381204..a4fc63015 100644 --- a/main/manager-web/src/router/index.js +++ b/main/manager-web/src/router/index.js @@ -81,10 +81,6 @@ const routes = [ name: 'ParamsManagement', component: function () { return import('../views/ParamsManagement.vue') - }, - meta: { - requiresAuth: true, - title: 'Parameter Management' } }, { @@ -92,22 +88,13 @@ const routes = [ name: 'KnowledgeBaseManagement', component: function () { return import('../views/KnowledgeBaseManagement.vue') - }, - meta: { - requiresAuth: true, - title: 'Knowledge Base' } }, - { path: '/server-side-management', name: 'ServerSideManager', component: function () { return import('../views/ServerSideManager.vue') - }, - meta: { - requiresAuth: true, - title: 'Server Management' } }, { @@ -115,10 +102,6 @@ const routes = [ name: 'OtaManagement', component: function () { return import('../views/OtaManagement.vue') - }, - meta: { - requiresAuth: true, - title: 'OTA Management' } }, { @@ -126,10 +109,6 @@ const routes = [ name: 'VoiceResourceManagement', component: function () { return import('../views/VoiceResourceManagement.vue') - }, - meta: { - requiresAuth: true, - title: 'Voice Resource' } }, { @@ -137,10 +116,6 @@ const routes = [ name: 'VoiceCloneManagement', component: function () { return import('../views/VoiceCloneManagement.vue') - }, - meta: { - requiresAuth: true, - title: 'Voice Clone' } }, { @@ -165,7 +140,7 @@ const routes = [ return import('../views/AgentTemplateManagement.vue') } }, - // Add template quick config route + // Add template quick-config route { path: '/template-quick-config', name: 'TemplateQuickConfig', @@ -173,16 +148,12 @@ const routes = [ return import('../views/TemplateQuickConfig.vue') } }, - // Function config page route + // Feature configuration page route { path: '/feature-management', name: 'FeatureManagement', component: function () { return import('../views/FeatureManagement.vue') - }, - meta: { - requiresAuth: true, - title: 'Feature Configuration' } }, // Replacement word management @@ -191,22 +162,14 @@ const routes = [ name: 'ReplacementWordManagement', component: function () { return import('../views/ReplacementWordManagement.vue') - }, - meta: { - requiresAuth: true, - title: 'Replacement Word Management' } }, - // Contacts management page route + // Address book management page route { path: '/address-book-management', name: 'AddressBookManagement', component: function () { return import('../views/AddressBookManagement.vue') - }, - meta: { - requiresAuth: true, - title: 'Address Book Management' } }, ] @@ -215,12 +178,12 @@ const router = new VueRouter({ routes }) -// Globally handle duplicate navigation by refreshing the page +// Handle duplicate navigation globally by refreshing the page const originalPush = VueRouter.prototype.push VueRouter.prototype.push = function push(location) { return originalPush.call(this, location).catch(err => { if (err.name === 'NavigationDuplicated') { - // If duplicate navigation, refresh page + // If duplicate navigation, refresh the page window.location.reload() } else { // Throw other errors normally @@ -229,21 +192,27 @@ VueRouter.prototype.push = function push(location) { }) } -// Routes requiring login -const protectedRoutes = ['home', 'RoleConfig', 'DeviceManagement', 'UserManagement', 'ModelConfig', 'KnowledgeBaseManagement', 'KnowledgeFileUpload', 'AddressBookManagement'] +// Whitelist of routes accessible without login +const anonRouteNames = new Set(['login', 'Register', 'RetrievePassword', 'welcome']) -// Route Guard +// Route guard router.beforeEach((to, from, next) => { - // Check if the route requires protection - if (protectedRoutes.includes(to.name)) { - // Get token from localStorage - const token = localStorage.getItem('token') - if (!token) { - // Not logged in, redirecting to login page - next({ name: 'login', query: { redirect: to.fullPath } }) - return - } + const token = localStorage.getItem('token'); + const isAnonRoute = anonRouteNames.has(to.name); + + if (isAnonRoute && token) { + next({ name: 'home', replace: true }) + return } + + if (!isAnonRoute && !token) { + next({ + name: 'login', + replace: true + }) + return + } + next() }) diff --git a/main/xiaozhi-server/config/manage_api_client.py b/main/xiaozhi-server/config/manage_api_client.py index be7fc7639..7852a35cb 100644 --- a/main/xiaozhi-server/config/manage_api_client.py +++ b/main/xiaozhi-server/config/manage_api_client.py @@ -1,13 +1,18 @@ import os import base64 +import asyncio import functools import threading +import traceback from typing import Optional, Dict import httpx TAG = __name__ +# _retry_wait slice granularity: after safe_close we finish within ~100ms; polling overhead is negligible +_RETRY_WAIT_SLICE = 0.1 + class DeviceNotFoundException(Exception): pass @@ -16,18 +21,21 @@ class DeviceNotFoundException(Exception): class DeviceBindException(Exception): def __init__(self, bind_code): self.bind_code = bind_code - super().__init__(f"Device bind error, bind code: {bind_code}") + super().__init__(f"Device binding exception, Binding code: {bind_code}") + + +class ManageApiShutdownError(Exception): + """Terminal error raised when safe_close interrupts a retry wait; __cause__ keeps the last failure reason.""" class ManageApiClient: _instance = None - _instance_lock = threading.Lock() - _async_clients = {} # One client per event loop + _instance_lock = threading.Lock() # guards reads/writes of _instance and _closed _secret = None - _closed = False # Set to True after safe_close(); no new connections will be created after closure. + _closed = False # set to True by safe_close(); no new connections are created after closing def __new__(cls, config): - """Singleton ensures a single global instance and supports config injection.""" + """Singleton pattern ensures a globally unique instance and supports passing config parameters.""" with cls._instance_lock: if cls._instance is None: cls._instance = super().__new__(cls) @@ -36,93 +44,97 @@ class ManageApiClient: @classmethod def _init_client(cls, config): - """Initialize configuration (client creation is deferred).""" + """Initialize configuration (lazy client creation)""" cls.config = config.get("manager-api") if not cls.config: - raise Exception("manager-api configuration is missing") + raise Exception("manager-api configuration error") if not cls.config.get("url") or not cls.config.get("secret"): - raise Exception("manager-api url or secret is invalid") + raise Exception("manager-api url or secret configuration error") if "your_" in cls.config.get("secret", "").lower(): - raise Exception("Please configure manager-api secret first") + raise Exception("Please configure the manager-api secret first") cls._secret = cls.config.get("secret") - cls.max_retries = cls.config.get("max_retries", 6) # Max retries - cls.retry_delay = cls.config.get("retry_delay", 10) # Initial retry delay (seconds) - # Defer AsyncClient creation until first use - cls._async_clients = {} + cls.max_retries = cls.config.get("max_retries", 6) # Maximum retry count + cls.retry_delay = cls.config.get("retry_delay", 10) # Initial retry delay(seconds) + # Do not create the AsyncClient here; defer creation until actually used cls._closed = False @classmethod - async def _ensure_async_client(cls): - """Ensure async client exists (one per event loop).""" - import asyncio + def _build_client(cls) -> httpx.AsyncClient: + """Build the AsyncClient dedicated to one business request (including its retries). - try: - loop = asyncio.get_running_loop() - loop_id = id(loop) - - with cls._instance_lock: - if cls._closed: - raise Exception("ManageApiClient is closed; no new HTTP client can be created") - if loop_id not in cls._async_clients: - limits = httpx.Limits(max_keepalive_connections=0) - 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: - # No running loop - raise Exception("Must be called from an async context") + Constraint: the caller closes it via ``async with`` inside the same loop; caching across requests is prohibited; construction happens outside the lock so concurrent requests do not block the event loop. + """ + with cls._instance_lock: + if cls._closed: + raise Exception("ManageApiClient is closed; no new HTTP client is created") + base_url = cls.config.get("url") + secret = cls._secret + timeout = cls.config.get("timeout", 30) + return httpx.AsyncClient( + base_url=base_url, + headers={ + "User-Agent": f"PythonClient/2.0 (PID:{os.getpid()})", + "Accept": "application/json", + "Authorization": "Bearer " + secret, + }, + timeout=timeout, + # Connection reuse is limited to this request; keepalive_expiry dynamically covers retry_delay, + # preventing pooled connections from expiring during retry waits. + limits=httpx.Limits( + max_keepalive_connections=1, + keepalive_expiry=max(30, cls.retry_delay + 5), + ), + trust_env=False, + # verify=True builds the TLS context on demand: httpcore mutates the passed-in + # context in place (unlocked), so a shared singleton would race on concurrent handshakes. + verify=True, + ) @classmethod - async def _async_request(cls, method: str, endpoint: str, **kwargs) -> Dict: - """Send a single async HTTP request and process the response.""" - # Ensure client exists - client = await cls._ensure_async_client() + async def _async_request( + cls, client: httpx.AsyncClient, method: str, endpoint: str, **kwargs + ) -> Dict: + """Execute a single request on the given client; release back to the connection pool immediately after reading the response.""" endpoint = endpoint.lstrip("/") response = None try: response = await client.request(method, endpoint, **kwargs) response.raise_for_status() - result = response.json() - - # Handle API business errors 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 error: {result.get('msg', 'Unknown error')}") - - # Return success data - return result.get("data") if result.get("code") == 0 else None + raise Exception(f"API returned an error: {result.get('msg', 'Unknown error')}") + return result.get("data") finally: - # Ensure response is closed (even on exceptions) if response is not None: - await response.aclose() + try: + await response.aclose() + except Exception: + # Constraint: release errors must be swallowed so they do not mask business exceptions or break retry logic + pass @classmethod def _should_retry(cls, exception: Exception) -> bool: - """Determine whether an exception should trigger retry.""" + """Determine if exception should be retried""" # Network-related errors if isinstance( exception, (httpx.ConnectError, httpx.TimeoutException, httpx.NetworkError) ): return True - # HTTP status errors + # RemoteProtocolError: only retry the "without sending a response" variant (request not + # sent, safe). Truncated variants may have been processed already; do not retry. + if isinstance(exception, httpx.RemoteProtocolError): + return "without sending a response" in str(exception) + + # HTTP status code error if isinstance(exception, httpx.HTTPStatusError): status_code = exception.response.status_code return status_code in [408, 429, 500, 502, 503, 504] @@ -130,93 +142,121 @@ class ManageApiClient: return False @classmethod - async def _execute_async_request(cls, method: str, endpoint: str, **kwargs) -> Dict: - """Async request executor with retries.""" - import asyncio + async def _retry_wait(cls): + """Retry wait interruptible by safe_close() (polls _closed every _RETRY_WAIT_SLICE seconds). - retry_count = 0 - - while retry_count <= cls.max_retries: - try: - # Execute request - return await cls._async_request(method, endpoint, **kwargs) - except Exception as e: - # Decide whether to retry - if retry_count < cls.max_retries and cls._should_retry(e): - retry_count += 1 - print( - f"{method} {endpoint} async request failed. Retrying in {cls.retry_delay:.1f}s (attempt {retry_count})" - ) - await asyncio.sleep(cls.retry_delay) - continue - else: - # No retry; re-raise - raise + Constraint: never sleep the full retry_delay in one shot, otherwise shutdown would + wait out the entire retry cycle. + """ + remaining = cls.retry_delay + while remaining > 0 and not cls._closed: + step = min(_RETRY_WAIT_SLICE, remaining) + await asyncio.sleep(step) + remaining -= step @classmethod - def _get_instance(cls): - """Thread-safely get singleton instance reference + async def _execute_async_request(cls, method: str, endpoint: str, **kwargs) -> Dict: + """Business request executor with a retry mechanism. - Callers should use the returned local reference instead of re-reading after null check - ManageApiClient._instance: even if safe_close() subsequently sets _instance - Set to None; the acquired reference still points to the original object, eliminating the "null check after, - Use TOCTOU race window where previous instance was nullified + Constraint: the client is built once for the whole retry sequence and closed via + ``async with``; safe_close does not cancel an in-flight attempt, it only interrupts + the retry wait (raising ManageApiShutdownError). + """ + client = cls._build_client() + async with client: + retry_count = 0 + + while retry_count <= cls.max_retries: + try: + # Execute asynchronous request + return await cls._async_request(client, method, endpoint, **kwargs) + except Exception as e: + # Determine if retry is needed + if retry_count < cls.max_retries and cls._should_retry(e): + retry_count += 1 + print( + f"{method} {endpoint} async request failed. Retrying in {cls.retry_delay:.1f}s (attempt {retry_count})" + ) + await cls._retry_wait() + if cls._closed: + # The terminal state must stay distinguishable: a bare raise would disguise the + # shutdown early-exit as network jitter and mask the offline signal + raise ManageApiShutdownError( + f"safe_close interrupted the retry wait: {e}") from e + continue + else: + # Do not retry, Throw exception directly + raise + + @classmethod + def _get_instance(cls) -> Optional["ManageApiClient"]: + """Thread-safely obtain a reference to the singleton instance. + + Constraint: callers keep the returned local reference; never re-read _instance after a null check (TOCTOU window). """ with cls._instance_lock: return cls._instance @classmethod def safe_close(cls): - """Safely close all async connection pools.""" - import asyncio + """Close entry point; in-flight requests release their clients inside their own event loops. + Already-started requests are not cancelled; pending retry waits are interrupted, + skipping the remaining retries (see _retry_wait). + """ 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): - """Inject a stable client instance and avoid shutdown races for API calls.""" + """Decorator: uniform singleton lookup, null check and exception fallback. + + - Fetches the instance once via _get_instance() and injects it as the decorated + function's first parameter, eliminating the TOCTOU race against safe_close(); + - If the instance is uninitialized or closed: raise an explicit exception when + raise_when_closed=True (startup paths), otherwise return None silently (daemon threads); + - When error_msg is set, request exceptions are caught, logged and None is returned; + when it is None, exceptions propagate to the caller. + """ + def decorator(func): @functools.wraps(func) async def wrapper(*args, **kwargs): instance = ManageApiClient._get_instance() if instance is None: if raise_when_closed: - raise Exception("ManageApiClient is not initialized or has been closed") + raise Exception("ManageApiClient is uninitialized or closed") return None if error_msg is None: return await func(instance, *args, **kwargs) try: return await func(instance, *args, **kwargs) - except Exception as exc: - print(f"{error_msg}: {exc}") + except Exception as e: + # Constraint: log the full stack trace for httpx/ValueError parsing failures (the + # message alone hides context); keep other paths to a one-line log + if isinstance(e, (httpx.HTTPError, ValueError)): + print(f"{error_msg}: {e}\n{traceback.format_exc()}") + else: + print(f"{error_msg}: {e}") return None + return wrapper + return decorator @api_guard(raise_when_closed=True) async def get_server_config(instance) -> Optional[Dict]: - """Fetch server base config.""" - return await instance._execute_async_request( - "POST", "/config/server-base" - ) + """Get server base configuration""" + return await instance._execute_async_request("POST", "/config/server-base") @api_guard(raise_when_closed=True) async def get_agent_models( instance, mac_address: str, client_id: str, selected_module: Dict ) -> Optional[Dict]: - """Fetch agent model config.""" + """Get agent model configuration""" return await instance._execute_async_request( "POST", "/config/agent-models", @@ -228,9 +268,9 @@ async def get_agent_models( ) -@api_guard("Failed to get correction words") +@api_guard("Failed to get replacement words") async def get_correct_words(instance, mac_address: str) -> Optional[Dict]: - """Fetch agent correction words.""" + """Get agent replacement words""" return await instance._execute_async_request( "POST", "/config/correct-words", json={"macAddress": mac_address} @@ -239,26 +279,32 @@ async def get_correct_words(instance, mac_address: str) -> Optional[Dict]: @api_guard("Failed to generate and save chat summary") async def generate_and_save_chat_summary(instance, session_id: str) -> Optional[Dict]: - """Generate and save chat summary.""" - return await instance._execute_async_request("POST", f"/agent/chat-summary/{session_id}/save") + """Generate and save chat summary (daemon thread; returns None silently when the service is closing).""" + return await instance._execute_async_request( + "POST", + f"/agent/chat-summary/{session_id}/save", + ) @api_guard("Failed to generate and save chat title") async def generate_and_save_chat_title(instance, session_id: str) -> Optional[Dict]: - """Generate and save a chat title.""" - return await instance._execute_async_request("POST", f"/agent/chat-title/{session_id}/generate") + """Generate and save chat title (daemon thread; returns None silently when the service is closing).""" + return await instance._execute_async_request( + "POST", + f"/agent/chat-title/{session_id}/generate", + ) @api_guard("TTS report failed") async def report( instance, mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time ) -> Optional[Dict]: - """Async chat history report.""" + """Report chat history asynchronously""" if not content: return None return await instance._execute_async_request( "POST", - f"/agent/chat-history/report", + "/agent/chat-history/report", json={ "macAddress": mac_address, "sessionId": session_id, @@ -272,9 +318,9 @@ async def report( ) -@api_guard("Address-book lookup failed") +@api_guard("Contact lookup failed") async def lookup_address_book(instance, caller_mac: str, nickname: str) -> Optional[Dict]: - """Look up a target device by nickname.""" + """Look up the target device by nickname""" return await instance._execute_async_request( "GET", f"/device/address-book/lookup?callerMac={caller_mac}&nickname={nickname}", diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index f46b88d1c..8a655f914 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -55,14 +55,25 @@ async def startToChat(conn: "ConnectionHandler", text): data = json.loads(text) if "speaker" in data and "content" in data: speaker_name = data["speaker"] - language_tag = data["language"] - actual_text = data["content"] + actual_content = data["content"] conn.logger.bind(tag=TAG).info( f"Parsed speaker information: {speaker_name}" ) - # Keep the original JSON payload for downstream use. - actual_text = text + # Keep the {"speaker":...} JSON only on the speaker's first + # appearance so the model greets them naturally once; later + # turns degrade to plain text so the recurring name does not + # push the model to keep addressing them every turn. + if speaker_name not in conn.introduced_speakers: + conn.introduced_speakers.add(speaker_name) + actual_text = text + else: + actual_text = actual_content + elif "content" in data: + # FunASR-style payloads return {"content","language","emotion"}: + # hand only the recognized text to the LLM, otherwise the raw + # JSON would enter the conversation history. + actual_text = data["content"] except (json.JSONDecodeError, KeyError): # Fall back to the original text if parsing fails. pass diff --git a/main/xiaozhi-server/core/providers/tts/edge.py b/main/xiaozhi-server/core/providers/tts/edge.py index ca8d2110e..21e10a515 100644 --- a/main/xiaozhi-server/core/providers/tts/edge.py +++ b/main/xiaozhi-server/core/providers/tts/edge.py @@ -1,6 +1,7 @@ import os import uuid import edge_tts +import edge_tts.communicate # 显式 import,下方要给本模块的 WSS_URL 重新赋值 from datetime import datetime from core.providers.tts.base import TTSProviderBase from config.logger import setup_logging @@ -8,6 +9,20 @@ from config.logger import setup_logging TAG = __name__ logger = setup_logging() +# 微软 2026-10 起对 legacy 消费者接口返回 403,edge-tts 7.2.8 仍走 +# speech.platform.bing.com 走不通。上游 PR rany2/edge-tts#491 切到 +# api.msedgeservices.com 修好,但 7.2.8 仍是 PyPI 最新版本,临时把 WSS_URL 顶住。 +# TODO(7.2.9): 升 edge-tts ≥ 7.2.9 后删掉这段 monkey patch。 +_NEW_WSS_URL = ( + "wss://api.msedgeservices.com/tts/cognitiveservices/websocket/v1" + f"?Ocp-Apim-Subscription-Key={edge_tts.constants.TRUSTED_CLIENT_TOKEN}" +) +# communicate.py 第 35 行 `from .constants import WSS_URL` 会在 import 时把 +# WSS_URL 复制成本模块局部名,只改 edge_tts.constants.WSS_URL 不会生效。 +# __stream() 走 LEGB 找的是 edge_tts.communicate.WSS_URL,所以这里两个都要改。 +edge_tts.constants.WSS_URL = _NEW_WSS_URL +edge_tts.communicate.WSS_URL = _NEW_WSS_URL + class TTSProvider(TTSProviderBase): TTS_PARAM_CONFIG = [ diff --git a/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py b/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py new file mode 100644 index 000000000..d3ee1bcd5 --- /dev/null +++ b/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py @@ -0,0 +1,208 @@ +"""ManageApiClient lifecycle regression tests: run directly with unittest; no app/model/network. + +Excluded from the pytest suite: the mock layer in tests/conftest.py (global patches of +asyncio.sleep and httpx.AsyncClient at import time) conflicts with the timing assertions +and MockTransport injection in this file; __test__ = False keeps pytest from collecting it, +so run it directly with unittest. +Usage: python -B tests/test_manage_api_client_lifecycle.py -v +""" +__test__ = False + +import asyncio +from concurrent.futures import ThreadPoolExecutor +import gc +import importlib.util +import os +from pathlib import Path +import unittest +from unittest.mock import patch +import weakref + +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_reuses_client_until_request_ends(self): + """Retries reuse the same client (same pooled keep-alive connection) and it is + closed only after the whole business request finishes: the client lifecycle is + aligned with the business request, not with a single attempt.""" + async def handle(request): + if len(self.requests) == 1: + return httpx.Response(503) + # the first client is still serving the second attempt (not closed early) + self.assertFalse(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), 1) + self.assertTrue(self.clients[0].is_closed) + + async def test_timeout_exhaustion_reuses_client_until_request_ends(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), 1) + self.assertTrue(self.clients[0].is_closed) + + async def test_remote_protocol_error_without_response_triggers_retry(self): + """Stale keep-alive case: the response never started, so retrying is safe.""" + async def handle(request): + if len(self.requests) == 1: + raise httpx.RemoteProtocolError( + 'Server disconnected without sending a response.', + request=request) + 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.requests), 2) + + async def test_remote_protocol_error_incomplete_body_not_retried(self): + """Response truncated mid-flight: the server likely already processed the request, + so retrying the non-idempotent POST would duplicate it; must fail directly.""" + async def handle(request): + raise httpx.RemoteProtocolError( + 'Peer closed connection without sending complete message body ' + '(discarded 10 of 100 read bytes)', request=request) + with self.transport(handle), self.assertRaises(httpx.RemoteProtocolError): + await self.cls._execute_async_request('POST', '/report') + self.assertEqual(len(self.requests), 1) + + 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)) + with self.assertRaisesRegex(Exception, 'is closed'): + await self.cls._execute_async_request('POST', '/report') + self.assertEqual(len(self.clients), 1) + + async def test_safe_close_interrupts_retry_backoff(self): + """safe_close interrupts the retry wait: the started attempt runs to completion, + no new attempt is issued, and it terminates with ManageApiShutdownError + (distinguishable from a retry-exhausted network error).""" + async def handle(request): + return httpx.Response(503) + original_delay = self.cls.retry_delay + self.cls.retry_delay = 5.0 # setUp default 0 would not show the interruption + try: + with self.transport(handle): + task = asyncio.create_task( + self.cls._execute_async_request('POST', '/report')) + await asyncio.sleep(0.2) # let it enter the retry wait + self.cls.safe_close() + with self.assertRaises(self.api.ManageApiShutdownError) as ctx: + await task + self.assertIsInstance(ctx.exception.__cause__, httpx.HTTPStatusError) + # only the first attempt: the retry wait was interrupted, no new attempt issued + self.assertEqual(len(self.clients), 1) + self.assertEqual(len(self.requests), 1) + finally: + self.cls.retry_delay = original_delay + + 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)) + # Cache regression guard: once the test drops its strong references the client must be + # GC-collectable; reintroducing any class-level cache (id(loop) dict / + # WeakKeyDictionary) would leave survivors > 0 + refs = [weakref.ref(c) for c in self.clients] + self.clients.clear() + gc.collect() + self.assertEqual(sum(ref() is not None for ref in refs), 0) + + +if __name__ == '__main__': + unittest.main()