"""TTL-кэш снимка панели. При ошибке панели отдаёт устаревший снимок.""" from __future__ import annotations import threading import time from typing import Any, Callable from .remnawave import RemnawaveError MIN_REFRESH_INTERVAL = 5.0 # ?refresh=1 не чаще, чем раз в 5 секунд class SnapshotCache: def __init__(self, loader: Callable[[], Any], ttl: float): self._loader = loader self._ttl = ttl self._lock = threading.Lock() self._value: Any = None self._at = 0.0 def get(self, force: bool = False) -> tuple[Any, dict]: with self._lock: age = time.monotonic() - self._at fresh = self._value is not None and age < self._ttl if force and age < MIN_REFRESH_INTERVAL: force = False if fresh and not force: return self._value, {"cached": True, "stale": False, "ageSeconds": round(age, 1)} try: self._value = self._loader() self._at = time.monotonic() return self._value, {"cached": False, "stale": False, "ageSeconds": 0.0} except RemnawaveError as e: if self._value is None: raise return self._value, {"cached": True, "stale": True, "ageSeconds": round(age, 1), "lastError": e.message}