average-architect-28889
07/28/2025, 6:54 AMtall-airline-16756
07/28/2025, 6:54 AMtall-airline-16756
07/28/2025, 6:56 AMasync def _close_http_ctx() -> None:
val = _ContextVar.get(None)
if val is not None:
logger.debug("http_session(): closing the httpclient ctx")
await val().close()
_ContextVar.set(None)
• WebSocket Connection Cleanup: Always close WebSocket connections in a finally block to ensure cleanup even if exceptions occur. For example: finally:
if ws is not None:
await ws.close()
• Graceful Task Cancellation: Use utility functions like utils.aio.gracefully_cancel() to properly cancel tasks and clean up resources. For example: finally:
await utils.aio.gracefully_cancel(*tasks, wait_reconnect_task)
tasks_group.cancel()
tasks_group.exception() # retrieve the exception
• Session Management: Centralize session management and ensure active sessions are closed properly. For example: async def _close_active_session(self) -> None:
async with self._session_lock:
if self._active_session:
try:
await self._active_session.close()
except Exception as e:
logger.warning(f"error closing session: {e}")
finally:
self._active_session = None
• Key Principles:
◦ Always use finally blocks for cleanup.
◦ Check for None before closing resources.
◦ Handle exceptions during cleanup to avoid masking original errors.
Implementing these patterns should help prevent unclosed client session and connector errors. If you need further assistance or have specific implementation questions, feel free to provide additional details about your setup.
Sources: livekit-plugins/livekit-plugins-azure/livekit/plugins/azure/stt.py