refactor: enhance TTSCache with context manager for lock handling and improve error logging

This commit is contained in:
2026-09-23 18:16:55 +05:00
parent a910b206fe
commit 7d8bba7745
2 changed files with 47 additions and 27 deletions
+18 -2
View File
@@ -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: