Files
LastRecc/lastrecc/cache.py
T

60 lines
1.6 KiB
Python

from __future__ import annotations
import hashlib
import json
import os
import tempfile
import time
from pathlib import Path
from typing import Any
def load_json(path: Path, default: Any = None) -> Any:
try:
with path.open(encoding="utf-8") as handle:
return json.load(handle)
except (FileNotFoundError, json.JSONDecodeError, OSError):
return default
def save_json(path: Path, data: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".", suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(data, handle, ensure_ascii=False, indent=1)
os.replace(tmp, path)
finally:
try:
os.unlink(tmp)
except FileNotFoundError:
pass
def is_fresh(path: Path, ttl_seconds: float) -> bool:
try:
return time.time() - path.stat().st_mtime < ttl_seconds
except OSError:
return False
class JsonCache:
"""Small file cache keyed by a stable hash of the request."""
def __init__(self, directory: Path, ttl_seconds: float = 7 * 24 * 3600):
self.directory = directory
self.ttl_seconds = ttl_seconds
def _path(self, key: str) -> Path:
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()
return self.directory / f"{digest}.json"
def get(self, key: str) -> Any:
path = self._path(key)
if not is_fresh(path, self.ttl_seconds):
return None
return load_json(path)
def set(self, key: str, value: Any) -> None:
save_json(self._path(key), value)