fix(server): preserve hello during device config init

This commit is contained in:
WANG TAIRAN 2026-07-14 21:00:42 +08:00
parent ad3fb4d8c8
commit 3d47d2e9e1
3 changed files with 102 additions and 8 deletions

View file

@ -45,6 +45,7 @@ from core.utils.prompt_manager import PromptManager
from core.utils.voiceprint_provider import VoiceprintProvider from core.utils.voiceprint_provider import VoiceprintProvider
from core.utils.util import get_system_error_response from core.utils.util import get_system_error_response
from core.utils import textUtils from core.utils import textUtils
from core.connection_initialization import wait_for_bind_status
TAG = __name__ TAG = __name__
@ -346,12 +347,15 @@ class ConnectionHandler:
"""消息路由""" """消息路由"""
# 检查是否已经获取到真实的绑定状态 # 检查是否已经获取到真实的绑定状态
if not self.bind_completed_event.is_set(): if not self.bind_completed_event.is_set():
# 还没有获取到真实状态,等待直到获取到真实状态或超时 # 高并发下差异化配置查询可能超过 1 秒。hello 是一次性消息,
try: # 不能在初始化尚未完成时静默丢弃,否则客户端会一直等待 hello 响应。
await asyncio.wait_for(self.bind_completed_event.wait(), timeout=1) if not await wait_for_bind_status(self.bind_completed_event, self.config):
except asyncio.TimeoutError: self.logger.bind(tag=TAG).warning(
# 超时仍未获取到真实状态,丢弃消息 "等待设备绑定状态超时,关闭连接以便客户端重试"
await self._discard_message_with_bind_prompt() )
await self.websocket.close(
code=1013, reason="device configuration is still initializing"
)
return return
# 已经获取到真实状态,检查是否需要绑定 # 已经获取到真实状态,检查是否需要绑定
@ -837,8 +841,7 @@ class ConnectionHandler:
f"{time.time() - begin_time} 秒,异步获取差异化配置成功: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}" f"{time.time() - begin_time} 秒,异步获取差异化配置成功: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}"
) )
self.need_bind = False self.need_bind = False
self.bind_completed_event.set() except DeviceNotFoundException:
except DeviceNotFoundException as e:
self.need_bind = True self.need_bind = True
private_config = {} private_config = {}
except DeviceBindException as e: except DeviceBindException as e:
@ -849,6 +852,10 @@ class ConnectionHandler:
self.need_bind = True self.need_bind = True
self.logger.bind(tag=TAG).error(f"异步获取差异化配置失败: {e}") self.logger.bind(tag=TAG).error(f"异步获取差异化配置失败: {e}")
private_config = {} private_config = {}
finally:
# 该事件表示“绑定状态已知”,与后续模块初始化分离。
# 异常和需要绑定的分支也必须唤醒正在等待的首条消息。
self.bind_completed_event.set()
init_llm, init_tts, init_memory, init_intent = ( init_llm, init_tts, init_memory, init_intent = (
False, False,

View file

@ -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

View file

@ -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()