diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index e7b853d31..72f53fae9 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -45,6 +45,7 @@ from core.utils.prompt_manager import PromptManager from core.utils.voiceprint_provider import VoiceprintProvider from core.utils.util import get_system_error_response from core.utils import textUtils +from core.connection_initialization import wait_for_bind_status TAG = __name__ @@ -346,12 +347,15 @@ class ConnectionHandler: """消息路由""" # 检查是否已经获取到真实的绑定状态 if not self.bind_completed_event.is_set(): - # 还没有获取到真实状态,等待直到获取到真实状态或超时 - try: - await asyncio.wait_for(self.bind_completed_event.wait(), timeout=1) - except asyncio.TimeoutError: - # 超时仍未获取到真实状态,丢弃消息 - await self._discard_message_with_bind_prompt() + # 高并发下差异化配置查询可能超过 1 秒。hello 是一次性消息, + # 不能在初始化尚未完成时静默丢弃,否则客户端会一直等待 hello 响应。 + if not await wait_for_bind_status(self.bind_completed_event, self.config): + self.logger.bind(tag=TAG).warning( + "等待设备绑定状态超时,关闭连接以便客户端重试" + ) + await self.websocket.close( + code=1013, reason="device configuration is still initializing" + ) return # 已经获取到真实状态,检查是否需要绑定 @@ -837,8 +841,7 @@ class ConnectionHandler: f"{time.time() - begin_time} 秒,异步获取差异化配置成功: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}" ) self.need_bind = False - self.bind_completed_event.set() - except DeviceNotFoundException as e: + except DeviceNotFoundException: self.need_bind = True private_config = {} except DeviceBindException as e: @@ -849,6 +852,10 @@ class ConnectionHandler: self.need_bind = True self.logger.bind(tag=TAG).error(f"异步获取差异化配置失败: {e}") private_config = {} + finally: + # 该事件表示“绑定状态已知”,与后续模块初始化分离。 + # 异常和需要绑定的分支也必须唤醒正在等待的首条消息。 + self.bind_completed_event.set() init_llm, init_tts, init_memory, init_intent = ( False, diff --git a/main/xiaozhi-server/core/connection_initialization.py b/main/xiaozhi-server/core/connection_initialization.py new file mode 100644 index 000000000..281faaa80 --- /dev/null +++ b/main/xiaozhi-server/core/connection_initialization.py @@ -0,0 +1,32 @@ +import asyncio + + +DEFAULT_BIND_STATUS_TIMEOUT_SECONDS = 10.0 +MIN_BIND_STATUS_TIMEOUT_SECONDS = 1.0 +MAX_BIND_STATUS_TIMEOUT_SECONDS = 60.0 + + +def bind_status_timeout_seconds(config) -> float: + """返回等待设备绑定状态的有界超时时间。""" + try: + raw = config.get("server", {}).get( + "bind_status_timeout_seconds", DEFAULT_BIND_STATUS_TIMEOUT_SECONDS + ) + timeout = float(raw) + except (AttributeError, TypeError, ValueError): + timeout = DEFAULT_BIND_STATUS_TIMEOUT_SECONDS + return min( + max(timeout, MIN_BIND_STATUS_TIMEOUT_SECONDS), + MAX_BIND_STATUS_TIMEOUT_SECONDS, + ) + + +async def wait_for_bind_status(event: asyncio.Event, config) -> bool: + """等待绑定状态就绪,超时时返回 False。""" + try: + await asyncio.wait_for( + event.wait(), timeout=bind_status_timeout_seconds(config) + ) + except asyncio.TimeoutError: + return False + return True diff --git a/main/xiaozhi-server/tests/test_connection_initialization.py b/main/xiaozhi-server/tests/test_connection_initialization.py new file mode 100644 index 000000000..c9798c65c --- /dev/null +++ b/main/xiaozhi-server/tests/test_connection_initialization.py @@ -0,0 +1,55 @@ +import asyncio +import unittest + +from core.connection_initialization import ( + DEFAULT_BIND_STATUS_TIMEOUT_SECONDS, + bind_status_timeout_seconds, + wait_for_bind_status, +) + + +class ConnectionInitializationTest(unittest.IsolatedAsyncioTestCase): + async def test_waits_for_status_beyond_legacy_one_second_gate(self): + event = asyncio.Event() + + async def complete_later(): + await asyncio.sleep(1.05) + event.set() + + task = asyncio.create_task(complete_later()) + try: + ready = await wait_for_bind_status(event, {"server": {}}) + finally: + await task + + self.assertTrue(ready) + + async def test_returns_false_when_bounded_wait_expires(self): + event = asyncio.Event() + + ready = await wait_for_bind_status( + event, {"server": {"bind_status_timeout_seconds": 0}} + ) + + self.assertFalse(ready) + + def test_timeout_uses_safe_default_and_bounds(self): + self.assertEqual( + bind_status_timeout_seconds({}), DEFAULT_BIND_STATUS_TIMEOUT_SECONDS + ) + self.assertEqual( + bind_status_timeout_seconds( + {"server": {"bind_status_timeout_seconds": "invalid"}} + ), + DEFAULT_BIND_STATUS_TIMEOUT_SECONDS, + ) + self.assertEqual( + bind_status_timeout_seconds( + {"server": {"bind_status_timeout_seconds": 999}} + ), + 60.0, + ) + + +if __name__ == "__main__": + unittest.main()