Fix StopAsyncIteration in parse_telephony_websocket

Handle WebSocket disconnections gracefully when telephony providers send
fewer messages than expected. Adds explicit StopAsyncIteration handling
for both first and second message retrieval.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
James Hush
2026-02-03 16:25:07 +08:00
parent 4c10ddb7bb
commit a627597bca

View File

@@ -147,20 +147,29 @@ async def parse_telephony_websocket(websocket: WebSocket):
try: try:
# First message # First message
try:
first_message_raw = await start_data.__anext__() first_message_raw = await start_data.__anext__()
logger.trace(f"First message: {first_message_raw}") logger.trace(f"First message: {first_message_raw}")
try: try:
first_message = json.loads(first_message_raw) first_message = json.loads(first_message_raw)
except json.JSONDecodeError: except json.JSONDecodeError:
first_message = {} first_message = {}
except StopAsyncIteration:
logger.error("WebSocket closed without sending any messages")
raise ValueError("WebSocket closed before receiving telephony handshake messages")
# Second message # Second message
try:
second_message_raw = await start_data.__anext__() second_message_raw = await start_data.__anext__()
logger.trace(f"Second message: {second_message_raw}") logger.trace(f"Second message: {second_message_raw}")
try: try:
second_message = json.loads(second_message_raw) second_message = json.loads(second_message_raw)
except json.JSONDecodeError: except json.JSONDecodeError:
second_message = {} second_message = {}
except StopAsyncIteration:
# Only one message received - use it for detection
logger.warning("Only received one WebSocket message, expected two")
second_message = {}
# Try auto-detection on both messages # Try auto-detection on both messages
detected_type_first = _detect_transport_type_from_message(first_message) detected_type_first = _detect_transport_type_from_message(first_message)