""" services/cache.py ───────────────── Two-tier caching strategy: Tier 1 – In-memory LRU index (hash → S3 URL or local path, instant lookup). Tier 2 – Local disk cache at `settings.cache_dir` (survives process restarts, but NOT container restarts — intentional for ephemeral environments). Cache Key: MD5( LOWER(stripped_text) + "|" + voice_key + "|" + str(round(speed, 2)) ) This ensures identical audio requests return the same key regardless of minor whitespace differences. """ import hashlib import logging import os from collections import OrderedDict from pathlib import Path from typing import Optional from core.config import get_settings logger = logging.getLogger(__name__) def build_cache_key(text: str, voice_key: str, speed: float) -> str: """ Deterministically derive a cache key from the synthesis parameters. The key is an MD5 hex digest (32 chars) suitable for use as a filename or object-store key. """ normalised = f"{text.strip().lower()}|{voice_key}|{round(speed, 2)}" return hashlib.md5(normalised.encode("utf-8")).hexdigest() # ── In-memory LRU index ──────────────────────────────────────────────────────── class _LRUCache: """Thread-safe* LRU mapping of cache_key → resolved URL/path. * Safe for single-threaded asyncio use; wrap with asyncio.Lock if you switch to multi-threaded workers. """ def __init__(self, max_size: int) -> None: self._store: OrderedDict[str, str] = OrderedDict() self._max_size = max_size def get(self, key: str) -> Optional[str]: if key not in self._store: return None self._store.move_to_end(key) # mark as recently used return self._store[key] def put(self, key: str, value: str) -> None: if key in self._store: self._store.move_to_end(key) self._store[key] = value if len(self._store) > self._max_size: evicted_key, _ = self._store.popitem(last=False) logger.debug("LRU evicted: %s", evicted_key) def __len__(self) -> int: return len(self._store) _lru: Optional[_LRUCache] = None def _get_lru() -> _LRUCache: global _lru if _lru is None: settings = get_settings() _lru = _LRUCache(max_size=settings.cache_max_entries) return _lru # ── Disk-cache helpers ───────────────────────────────────────────────────────── def _cache_dir() -> Path: settings = get_settings() path = Path(settings.cache_dir) path.mkdir(parents=True, exist_ok=True) return path def get_local_path(cache_key: str) -> Path: return _cache_dir() / f"{cache_key}.wav" # ── Public API ───────────────────────────────────────────────────────────────── def cache_lookup(cache_key: str) -> Optional[str]: """ Check both cache tiers for a previously generated audio artefact. Returns: A URL string (S3/CDN) or local file path string if found, else None. """ # Tier 1: in-memory LRU hit = _get_lru().get(cache_key) if hit: logger.debug("Cache HIT (memory): %s", cache_key) return hit # Tier 2: local disk local = get_local_path(cache_key) if local.exists(): logger.debug("Cache HIT (disk): %s", cache_key) _get_lru().put(cache_key, str(local)) return str(local) logger.debug("Cache MISS: %s", cache_key) return None def cache_store(cache_key: str, resolved_url: str, wav_bytes: Optional[bytes] = None) -> None: """ Persist a new cache entry. Args: cache_key: MD5 hex from build_cache_key(). resolved_url: Public URL (S3/CDN) or local path to store. wav_bytes: If provided, also write to local disk cache (Tier 2). """ _get_lru().put(cache_key, resolved_url) if wav_bytes is not None: local = get_local_path(cache_key) try: local.write_bytes(wav_bytes) logger.debug("Cache written to disk: %s", local) except OSError as exc: logger.warning("Failed to write disk cache for %s: %s", cache_key, exc) def cache_stats() -> dict: """Return diagnostic statistics for the /health endpoint.""" lru = _get_lru() disk_count = sum(1 for _ in _cache_dir().glob("*.wav")) return { "memory_entries": len(lru), "disk_entries": disk_count, "cache_dir": str(_cache_dir()), }