"""Two-tier deterministic image cache: local disk (LRU by size) then the store backend (cache/maps/…). Rendering is serialised per key so concurrent identical requests render once. """ from __future__ import annotations import logging import os import threading import time from collections.abc import Callable from dataclasses import dataclass from pathlib import Path from wmb.store.backend import Backend from wmb.store.layout import image_cache_path log = logging.getLogger(__name__) @dataclass class CacheResult: key: str data: bytes source: str # "local" | "remote" | "render" elapsed_ms: int class ImageCache: def __init__(self, local_dir: Path, backend: Backend | None, max_bytes: int, remote_enabled: bool = True): self.dir = local_dir self.dir.mkdir(parents=True, exist_ok=True) self.backend = backend if remote_enabled else None self.max_bytes = max_bytes self._locks: dict[str, threading.Lock] = {} self._locks_guard = threading.Lock() self._last_evict = 0.0 def _path(self, key: str) -> Path: return self.dir / key[:2] / f"{key}.png" def _lock(self, key: str) -> threading.Lock: with self._locks_guard: return self._locks.setdefault(key, threading.Lock()) def get(self, key: str) -> bytes | None: p = self._path(key) if p.is_file(): try: os.utime(p, None) return p.read_bytes() except OSError: return None return None def get_or_render(self, key: str, render: Callable[[], bytes]) -> CacheResult: t0 = time.monotonic() data = self.get(key) if data is not None: return CacheResult(key, data, "local", int((time.monotonic() - t0) * 1000)) with self._lock(key): data = self.get(key) if data is not None: return CacheResult(key, data, "local", int((time.monotonic() - t0) * 1000)) if self.backend is not None: try: remote = self.backend.read_bytes(image_cache_path(key)) except Exception as e: # remote cache must never break rendering log.warning("remote cache read failed: %s", e) remote = None if remote: self._store_local(key, remote) return CacheResult(key, remote, "remote", int((time.monotonic() - t0) * 1000)) data = render() self._store_local(key, data) if self.backend is not None: threading.Thread(target=self._store_remote, args=(key, data), daemon=True).start() return CacheResult(key, data, "render", int((time.monotonic() - t0) * 1000)) def _store_local(self, key: str, data: bytes) -> None: p = self._path(key) p.parent.mkdir(parents=True, exist_ok=True) tmp = p.with_suffix(f".{os.getpid()}.tmp") tmp.write_bytes(data) os.replace(tmp, p) if time.monotonic() - self._last_evict > 60: self._last_evict = time.monotonic() threading.Thread(target=self.evict, daemon=True).start() def _store_remote(self, key: str, data: bytes) -> None: try: self.backend.write_bytes(image_cache_path(key), data) # type: ignore[union-attr] except Exception as e: log.warning("remote cache write failed: %s", e) def evict(self) -> int: files = [] for p in self.dir.rglob("*.png"): try: st = p.stat() files.append((st.st_atime, st.st_size, p)) except OSError: continue total = sum(s for _, s, _ in files) freed = 0 for _, size, p in sorted(files): if total - freed <= self.max_bytes: break try: p.unlink() freed += size except OSError: pass return freed def stats(self) -> dict: n, total = 0, 0 for p in self.dir.rglob("*.png"): try: total += p.stat().st_size n += 1 except OSError: pass return {"files": n, "bytes": total, "max_bytes": self.max_bytes, "remote": self.backend is not None}