"""Persistência local: idempotência por requestId (PRIMARY KEY no SQLite) e cache de áudio em disco. - `requests_v2`: (keyId, requestId) → chave de cache. O PRIMARY KEY do banco é quem garante a idempotência. O `keyId` faz parte da chave: o mesmo `requestId` vindo de duas chaves de serviço (homologação e produção) são dois pedidos distintos, e uma chave não enxerga nem colide com a amarração da outra. - `transcribe_requests_v2`: (keyId, idempotencyKey) → hash do conteúdo, mesma regra. - As tabelas da versão anterior (`requests`, `transcribe_requests`, sem `keyId`) ficam no arquivo, intocadas: esta versão não lê nem apaga, para a imagem anterior continuar funcionando sobre o mesmo `/data` se o deploy for revertido. As amarrações antigas não migram (não têm dono conhecido); um retry de pedido anterior ao deploy vira pedido novo e cai no cache por conteúdo, que é compartilhado e devolve o mesmo áudio. - `cache`: chave → arquivo .ogg, com LRU por `last_used_at` e teto em MB. Nenhum texto é gravado — só hashes. """ from __future__ import annotations import os import sqlite3 import threading import time from dataclasses import dataclass from pathlib import Path @dataclass(frozen=True) class CachedAudio: cache_key: str path: Path duration_ms: int sha256: str size: int class Store: def __init__(self, data_dir: Path, cache_max_mb: int, idempotency_ttl_h: int): self.cache_dir = data_dir / "cache" self.cache_dir.mkdir(parents=True, exist_ok=True) self._max_bytes = cache_max_mb * 1024 * 1024 self._ttl_s = idempotency_ttl_h * 3600 self._lock = threading.Lock() self._last_tick = 0 self._db = sqlite3.connect(data_dir / "voice.sqlite3", check_same_thread=False, isolation_level=None) self._db.execute("PRAGMA journal_mode=WAL") self._db.executescript( """ CREATE TABLE IF NOT EXISTS requests_v2 ( key_id TEXT NOT NULL, request_id TEXT NOT NULL, cache_key TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (key_id, request_id) ); CREATE TABLE IF NOT EXISTS cache ( cache_key TEXT PRIMARY KEY, size INTEGER NOT NULL, duration_ms INTEGER NOT NULL, sha256 TEXT NOT NULL, created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL -- time.time_ns() ); CREATE INDEX IF NOT EXISTS cache_lru ON cache(last_used_at); -- Transcrição: (keyId, idempotencyKey) → hash do (áudio, idioma, motor). O texto NUNCA vai ao disco. CREATE TABLE IF NOT EXISTS transcribe_requests_v2 ( key_id TEXT NOT NULL, idempotency_key TEXT NOT NULL, content_key TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (key_id, idempotency_key) ); """ ) # ---------- idempotência ---------- def bind_request(self, key_id: str, request_id: str, cache_key: str) -> tuple[bool, str]: """Grava (keyId, requestId)→chave. Devolve (é_novo, chave_gravada). Corrida resolvida pelo PRIMARY KEY.""" now = int(time.time()) with self._lock: self._db.execute("DELETE FROM requests_v2 WHERE created_at < ?", (now - self._ttl_s,)) try: self._db.execute( "INSERT INTO requests_v2(key_id, request_id, cache_key, created_at) VALUES (?, ?, ?, ?)", (key_id, request_id, cache_key, now), ) return True, cache_key except sqlite3.IntegrityError: row = self._db.execute( "SELECT cache_key FROM requests_v2 WHERE key_id = ? AND request_id = ?", (key_id, request_id) ).fetchone() return False, row[0] def bind_transcription(self, key_id: str, idempotency_key: str, content_key: str) -> tuple[bool, str]: """Mesmo papel do `bind_request`, para a transcrição. Corrida resolvida pelo PRIMARY KEY.""" now = int(time.time()) with self._lock: self._db.execute("DELETE FROM transcribe_requests_v2 WHERE created_at < ?", (now - self._ttl_s,)) try: self._db.execute( "INSERT INTO transcribe_requests_v2(key_id, idempotency_key, content_key, created_at)" " VALUES (?, ?, ?, ?)", (key_id, idempotency_key, content_key, now), ) return True, content_key except sqlite3.IntegrityError: row = self._db.execute( "SELECT content_key FROM transcribe_requests_v2 WHERE key_id = ? AND idempotency_key = ?", (key_id, idempotency_key), ).fetchone() return False, row[0] # ---------- cache ---------- def _path(self, cache_key: str) -> Path: return self.cache_dir / cache_key[:2] / f"{cache_key}.ogg" def get(self, cache_key: str) -> CachedAudio | None: with self._lock: row = self._db.execute( "SELECT size, duration_ms, sha256 FROM cache WHERE cache_key = ?", (cache_key,) ).fetchone() if row is None: return None path = self._path(cache_key) if not path.is_file(): self._db.execute("DELETE FROM cache WHERE cache_key = ?", (cache_key,)) return None self._db.execute( "UPDATE cache SET last_used_at = ? WHERE cache_key = ?", (self._tick(), cache_key) ) return CachedAudio(cache_key, path, row[1], row[2], row[0]) def _tick(self) -> int: """Relógio do LRU estritamente crescente. No Windows o time_ns() anda em passos de ~1 ms e dois acessos seguidos empatavam (o LRU expulsava o arquivo errado). Chame com self._lock.""" self._last_tick = max(time.time_ns(), self._last_tick + 1) return self._last_tick def put(self, cache_key: str, audio: bytes, duration_ms: int, sha256: str) -> CachedAudio: path = self._path(cache_key) path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(f".{os.getpid()}.{threading.get_ident()}.tmp") tmp.write_bytes(audio) os.replace(tmp, path) # escrita atômica with self._lock: now = self._tick() self._db.execute( "INSERT OR REPLACE INTO cache(cache_key, size, duration_ms, sha256, created_at, last_used_at)" " VALUES (?, ?, ?, ?, ?, ?)", (cache_key, len(audio), duration_ms, sha256, now, now), ) self._evict_locked() return CachedAudio(cache_key, path, duration_ms, sha256, len(audio)) def _evict_locked(self) -> None: total = self._db.execute("SELECT COALESCE(SUM(size), 0) FROM cache").fetchone()[0] if total <= self._max_bytes: return for key, size in self._db.execute( "SELECT cache_key, size FROM cache ORDER BY last_used_at ASC" ).fetchall(): if total <= self._max_bytes: break self._path(key).unlink(missing_ok=True) self._db.execute("DELETE FROM cache WHERE cache_key = ?", (key,)) total -= size def stats(self) -> dict[str, int]: with self._lock: entries, size = self._db.execute("SELECT COUNT(*), COALESCE(SUM(size), 0) FROM cache").fetchone() return {"entries": entries, "bytes": size} def close(self) -> None: self._db.close()