fix: manage WebRTC pipeline shutdown

This commit is contained in:
Xin Wang
2026-08-05 13:48:29 +08:00
parent 10bea48d72
commit 16156028c9
6 changed files with 253 additions and 9 deletions
+15
View File
@@ -169,6 +169,21 @@ class ConversationRecorder:
logger.error(f"保存对话文本失败,不影响本次通话: {exc}")
async def finish(self, *, status: str = "completed") -> None:
"""Finish the session even if the owning pipeline is being cancelled."""
finish_task = asyncio.create_task(
self._finish(status=status),
name=f"conversation-recorder-finish:{self.session_id}",
)
try:
await asyncio.shield(finish_task)
except asyncio.CancelledError:
# Shield prevents an interrupted pipeline cleanup from abandoning a
# checked-out asyncpg connection. Preserve cancellation only after
# the short database cleanup has returned the connection.
await asyncio.shield(finish_task)
raise
async def _finish(self, *, status: str) -> None:
async with self._lock:
try:
async with SessionLocal() as db:
+15 -2
View File
@@ -810,14 +810,22 @@ async def run_pipeline(
)
runner = WorkerRunner(handle_sigint=False)
run_status = "completed"
can_finalize_recorder = True
try:
await runner.add_workers(worker)
await runner.run()
except GeneratorExit:
# A coroutine being synchronously closed cannot perform async cleanup.
# The WebRTC route now prevents this by retaining every pipeline task;
# keep this guard so a future unmanaged caller cannot corrupt asyncpg.
run_status = "failed"
can_finalize_recorder = False
raise
except Exception:
run_status = "failed"
raise
finally:
if recorder:
if recorder and can_finalize_recorder:
await recorder.finish(status=run_status)
logger.info("管线已结束")
@@ -971,13 +979,18 @@ async def run_realtime_pipeline(
)
runner = WorkerRunner(handle_sigint=False)
run_status = "completed"
can_finalize_recorder = True
try:
await runner.add_workers(worker)
await runner.run()
except GeneratorExit:
run_status = "failed"
can_finalize_recorder = False
raise
except Exception:
run_status = "failed"
raise
finally:
if recorder:
if recorder and can_finalize_recorder:
await recorder.finish(status=run_status)
logger.info("Realtime 管线已结束")