import time
import threading
from typing import Callable, Any, Optional, Tuple, Dict
class CacheEntry:
"""
Internal representation of a cached item with value and freshness stamp.
"""
def __init__(self, value: Any, stamp: float):
self.value = value
self.stamp = stamp
class BoundedStalenessCache:
"""
A thread-safe cache enforcing bounded staleness using timestamps (stamps).
- Data is considered fresh if (current_time - entry_stamp) <= max_staleness.
- Supports synchronous refresh on read (if stale), manual refresh controls,
and invalidation.
- Loader function fetches fresh data and optionally provides an external stamp.
If loader returns only `value`, current time is used as stamp.
Example usage:
def loader(key: str) -> Tuple[Any, float]:
time.sleep(0.1) # Simulate slow fetch
return f"Fresh value for {key}", time.time()
cache = BoundedStalenessCache(max_staleness=5.0)
cache.set_loader(loader)
print(cache.get("test")) # Fetches fresh
print(cache.get("test")) # Serves cached (fresh)
time.sleep(6) # Now stale
print(cache.get("test")) # Refetches fresh
"""
def __init__(self, max_staleness: float = 60.0):
"""
:param max_staleness: Maximum allowed staleness in seconds.
"""
self.max_staleness = max_staleness
self._cache: Dict[str, CacheEntry] = {}
self._lock = threading.Lock()
self._loader: Optional[Callable[[str], Any]] = None
def set_loader(self, loader: Callable[[str], Any]) -> None:
"""
Register the loader function.
Loader can return:
- `value` (uses current time as stamp), or
- `(value, stamp)` where stamp is a monotonic timestamp/float.
"""
self._loader = loader
def get(self, key: str, force_refresh: bool = False) -> Any:
"""
Get value for key.
- Serves cached value if fresh (staleness <= max_staleness).
- Refreshes synchronously if stale or force_refresh=True.
- Raises ValueError if no loader set.
"""
if self._loader is None:
raise ValueError("Loader not set. Call set_loader() first.")
with self._lock:
now = time.time()
if key not in self._cache:
return self._load(key, now)
entry = self._cache[key]
staleness = now - entry.stamp
if force_refresh or staleness > self.max_staleness:
return self._load(key, now)
return entry.value
def _load(self, key: str, now: float) -> Any:
"""Internal: Load fresh value via loader and cache it."""
loaded = self._loader(key)
if isinstance(loaded, tuple) and len(loaded) == 2:
value, stamp = loaded
else:
value = loaded
stamp = now
self._cache[key] = CacheEntry(value, stamp)
return value
def refresh(self, key: str) -> None:
"""
Manually refresh a specific key (synchronous).
"""
self.get(key, force_refresh=True)
def invalidate(self, key: str) -> None:
"""
Remove key from cache (forces refresh on next get).
"""
with self._lock:
self._cache.pop(key, None)
def refresh_all(self) -> None:
"""
Manually refresh all cached keys (synchronous).
"""
with self._lock:
keys = list(self._cache.keys())
for key in keys:
self.refresh(key)
def clear(self) -> None:
"""
Clear entire cache.
"""
with self._lock:
self._cache.clear()
def stats(self) -> Dict[str, Any]:
"""
Get cache stats (thread-safe snapshot).
"""
with self._lock:
now = time.time()
stats = {
'size': len(self._cache),
'max_staleness': self.max_staleness,
}
stale_count = 0
for key, entry in self._cache.items():
staleness = now - entry.stamp
if staleness > self.max_staleness:
stale_count += 1
stats['stale_count'] = stale_count
return stats
Key Features
Bounded Staleness: Reads serve data if current_time - stamp <= max_staleness. Otherwise, refreshes automatically.
Stamps: Each entry stores a stamp (timestamp). Supports external stamps from loader or falls back to time.time().
Refresh Controls:
force_refresh in get() for eager refresh.
refresh(key): Manual sync refresh.
invalidate(key): Drop entry.
refresh_all(): Refresh everything.
clear(): Wipe cache.
Thread-Safe: Uses threading.Lock for concurrent access.
This implementation is production-ready for basic use cases, extensible for background refreshes (e.g., via concurrent.futures), or distributed stamps (e.g., logical clocks).