diff --git a/app/main.py b/app/main.py index e188781..89cdb93 100644 --- a/app/main.py +++ b/app/main.py @@ -21,7 +21,7 @@ from fastapi.staticfiles import StaticFiles import httpx from openai import AsyncOpenAI -from app.tts_cache import TTSCache +from app.tts_cache import CacheIOError, TTSCache from app.knowledge import KnowledgeBase, format_knowledge_context, resolve_knowledge_dir load_dotenv() @@ -856,28 +856,29 @@ class VoiceSession: "similarity_boost": settings.elevenlabs_tts_similarity_boost, } - # Generate key & fetch lock dedicated ONLY to specific text/voice config key = tts_cache._generate_key(**cache_params) - lock = await tts_cache.get_lock(key) - async with lock: + # Clean context manager handles acquisition, locking, and resource release automatically + async with tts_cache.lock(key): # Check cache - cached_audio = await tts_cache.get(**cache_params) + try: + cached_audio = await tts_cache.get(**cache_params) + if cached_audio: + logger.info("Using cached TTS audio for text: %s", prepared_text[:30]) + await self.send_json( + { + "type": "tts_audio", + "audio": base64.b64encode(cached_audio).decode("ascii"), + "format": audio_format_label(output_format), + "sample_rate": audio_sample_rate(output_format), + "mime_type": audio_mime_type(output_format), + } + ) + return + except Exception as exc: + logger.warning("Failed to read TTS cache: %s", exc) - if cached_audio: - logger.info("Using cached TTS audio for text: %s", prepared_text[:30]) - await self.send_json( - { - "type": "tts_audio", - "audio": base64.b64encode(cached_audio).decode("ascii"), - "format": audio_format_label(output_format), - "sample_rate": audio_sample_rate(output_format), - "mime_type": audio_mime_type(output_format), - } - ) - return - - # Miss: Only ONE request per unique key executes the API call + # Miss (Executed only once across concurrent tasks for this key) logger.info( "Calling ElevenLabs HTTP TTS: model=%s voice_id=%s language=%s", settings.elevenlabs_tts_model, @@ -911,16 +912,19 @@ class VoiceSession: ) response.raise_for_status() - # Put in cache - await tts_cache.put(audio_data=response.content, **cache_params) + # Isolated write: I/O disk failures will not disrupt returning audio to user + try: + await tts_cache.put(audio_data=response.content, **cache_params) + except CacheIOError as exc: + logger.error("Failed to write TTS audio to cache: %s", exc) await self.send_json( { "type": "tts_audio", "audio": base64.b64encode(response.content).decode("ascii"), - "format": audio_format_label(settings.elevenlabs_tts_output_format), - "sample_rate": audio_sample_rate(settings.elevenlabs_tts_output_format), - "mime_type": audio_mime_type(settings.elevenlabs_tts_output_format), + "format": audio_format_label(output_format), + "sample_rate": audio_sample_rate(output_format), + "mime_type": audio_mime_type(output_format), } ) except httpx.HTTPStatusError as exc: @@ -929,7 +933,7 @@ class VoiceSession: f"ElevenLabs HTTP TTS error: {exc.response.status_code} {message}" ) except Exception as exc: - await self.send_tts_failed(f"ElevenLabs HTTP TTS error: {exc}") + await self.send_tts_failed(f"ElevenLabs HTTP TTS error: {exc}") async def stream_tts( self, diff --git a/app/tts_cache.py b/app/tts_cache.py index bf07953..bf1b033 100644 --- a/app/tts_cache.py +++ b/app/tts_cache.py @@ -2,6 +2,7 @@ import asyncio import hashlib import logging import tempfile +from contextlib import asynccontextmanager from pathlib import Path from typing import Optional @@ -88,6 +89,23 @@ class TTSCache: self._key_locks[key] = asyncio.Lock() return self._key_locks[key] + async def release_lock(self, key: str) -> None: + """Removes lock from dictionary if unreferenced.""" + async with self._global_lock: + lock = self._key_locks.get(key) + if lock and not lock.locked(): + self._key_locks.pop(key, None) + + @asynccontextmanager + async def lock(self, key: str): + """Context manager for key-level deduplication that cleans up lock resources safely.""" + lock_obj = await self.get_lock(key) + try: + async with lock_obj: + yield + finally: + await self.release_lock(key) + async def get( self, text: str, @@ -144,7 +162,6 @@ class TTSCache: try: await asyncio.to_thread(self.cache_dir.mkdir, parents=True, exist_ok=True) - # Atomic file write def _atomic_write(): with tempfile.NamedTemporaryFile( dir=self.cache_dir, @@ -186,7 +203,6 @@ class TTSCache: ): return - # Sort files by access time ascending (oldest first) files.sort(key=lambda f: f.stat().st_atime) for f in files: