import asyncio import hashlib import logging import tempfile from pathlib import Path from typing import Optional logger = logging.getLogger(__name__) DEFAULT_MAX_CACHE_BYTES = 500 * 1024 * 1024 # max 500 MB DEFAULT_MAX_CACHE_FILES = 1000 # Max 1000 files in cache DEFAULT_CACHE_DIR = ".tts_cache" class CacheError(Exception): """Base exception for cache issues.""" class CacheIOError(CacheError): """Raised when reading or writing to cache fails.""" class TTSCache: """Simple in-disk audio cache with atomic writes, LRU eviction, and request locks.""" def __init__( self, cache_dir: str = DEFAULT_CACHE_DIR, max_bytes: int = DEFAULT_MAX_CACHE_BYTES, max_files: Optional[int] = DEFAULT_MAX_CACHE_FILES, ): self.cache_dir = Path(cache_dir) self.max_bytes = max_bytes self.max_files = max_files # In-memory locks to prevent multiple concurrent tasks from writing/fetching the same key self._key_locks: dict[str, asyncio.Lock] = {} self._global_lock = asyncio.Lock() @classmethod async def create( cls, cache_dir: str = DEFAULT_CACHE_DIR, max_bytes: int = DEFAULT_MAX_CACHE_BYTES, max_files: Optional[int] = DEFAULT_MAX_CACHE_FILES, ) -> "TTSCache": """Async factory method to ensure the cache directory exists.""" instance = cls(cache_dir, max_bytes=max_bytes, max_files=max_files) try: await asyncio.to_thread( instance.cache_dir.mkdir, parents=True, exist_ok=True ) logger.info("TTSCache directory ready at: %s", instance.cache_dir.resolve()) except (PermissionError, OSError) as e: logger.critical( "Failed to create cache directory [%s]: %s", instance.cache_dir, e ) raise CacheIOError(f"Cannot initialize cache directory: {e}") from e return instance def _generate_key( self, text: str, voice_id: str, output_format: str, model_id: str = "", stability: float = 0.5, similarity_boost: float = 0.75, ) -> str: raw_payload = ( f"{text.strip()}|{voice_id}|{output_format}|" f"{model_id}|{stability:.2f}|{similarity_boost:.2f}" ) return hashlib.sha256(raw_payload.encode("utf-8")).hexdigest() def get_extension(self, output_format: str) -> str: fmt = output_format.lower() if "pcm" in fmt: return "pcm" if "wav" in fmt: return "wav" return "mp3" async def get_lock(self, key: str) -> asyncio.Lock: """Retrieves or creates a dedicated asyncio.Lock for a given cache key.""" async with self._global_lock: if key not in self._key_locks: self._key_locks[key] = asyncio.Lock() return self._key_locks[key] async def get( self, text: str, voice_id: str, output_format: str, model_id: str = "", stability: float = 0.5, similarity_boost: float = 0.75, ) -> Optional[bytes]: """Retrieves cached audio bytes if available.""" key = self._generate_key( text, voice_id, output_format, model_id, stability, similarity_boost ) ext = self.get_extension(output_format) file_path = self.cache_dir / f"{key}.{ext}" try: exists = await asyncio.to_thread(file_path.exists) if exists: # Update timestamp for LRU tracking await asyncio.to_thread(file_path.touch, exist_ok=True) data = await asyncio.to_thread(file_path.read_bytes) logger.debug("Cache HIT [%s]", key[:8]) return data except (PermissionError, FileNotFoundError) as e: logger.warning("File access issue during cache read [%s]: %s", file_path, e) except OSError as e: logger.error("OS error reading cache file [%s]: %s", file_path, e) logger.debug("Cache MISS [%s]", key[:8]) return None async def put( self, text: str, voice_id: str, output_format: str, audio_data: bytes, model_id: str = "", stability: float = 0.5, similarity_boost: float = 0.75, ) -> None: """Saves audio bytes atomically into the disk cache and triggers LRU cleanup.""" if not audio_data: logger.warning("Attempted to cache empty bytes. Skipping.") return key = self._generate_key( text, voice_id, output_format, model_id, stability, similarity_boost ) ext = self.get_extension(output_format) file_path = self.cache_dir / f"{key}.{ext}" 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, prefix=f".tmp_{key}_", suffix=f".{ext}", delete=False, ) as tmp_file: tmp_file.write(audio_data) tmp_path = Path(tmp_file.name) tmp_path.replace(file_path) await asyncio.to_thread(_atomic_write) logger.info("Cached audio [%s] (%d bytes)", key[:8], len(audio_data)) except (PermissionError, OSError) as e: logger.error("Failed atomic write to cache [%s]: %s", file_path, e) raise CacheIOError(f"Failed to write audio cache: {e}") from e # Cleanup LRU asynchronously await asyncio.to_thread(self._evict_lru) def _evict_lru(self) -> None: """Removes the least recently accessed files when limits are breached.""" try: files = [ f for f in self.cache_dir.iterdir() if f.is_file() and not f.name.startswith(".tmp_") ] except (PermissionError, OSError) as e: logger.error("Failed to inspect cache directory for LRU eviction: %s", e) return total_size = sum(f.stat().st_size for f in files) total_count = len(files) if total_size <= self.max_bytes and ( self.max_files is None or total_count <= self.max_files ): return # Sort files by access time ascending (oldest first) files.sort(key=lambda f: f.stat().st_atime) for f in files: if total_size <= self.max_bytes and ( self.max_files is None or total_count <= self.max_files ): break try: f_size = f.stat().st_size f.unlink(missing_ok=True) total_size -= f_size total_count -= 1 logger.info("Evicted LRU file: %s (%d bytes)", f.name, f_size) except OSError as e: logger.warning("Failed to evict file %s: %s", f, e)