|
| 1 | +import hashlib |
| 2 | +import logging |
| 3 | +import typing as t |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +import arrow |
| 7 | +from pydantic import BaseModel |
| 8 | + |
| 9 | +from .types import CacheBackend, CacheInvalidError, CacheMetadata, CacheOptions |
| 10 | + |
| 11 | +T = t.TypeVar("T", bound=BaseModel) |
| 12 | +K = t.TypeVar("K", bound=BaseModel) |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +class FileCacheBackend(CacheBackend): |
| 18 | + """A generic cache for pydantic models""" |
| 19 | + |
| 20 | + def __init__(self, cache_dir: str, default_options: CacheOptions): |
| 21 | + self.cache_dir = cache_dir |
| 22 | + self.default_options = default_options |
| 23 | + |
| 24 | + def store_object( |
| 25 | + self, key: str, value: BaseModel, override_options: CacheOptions | None = None |
| 26 | + ) -> None: |
| 27 | + """Store a single object in the cache |
| 28 | +
|
| 29 | + The file cache stores everything as a jsonl file. The first object in |
| 30 | + the file is the metadata, which contains the creation time and |
| 31 | + expiration time of the cache entry. |
| 32 | + """ |
| 33 | + |
| 34 | + # Ensure the cache directory exists |
| 35 | + self._ensure_cache_dir() |
| 36 | + # Create a file path based on the key |
| 37 | + file_path = self._cache_key_path(key) |
| 38 | + |
| 39 | + metadata = CacheMetadata( |
| 40 | + created_at=arrow.now().isoformat(), |
| 41 | + valid_until=( |
| 42 | + arrow.now().shift(seconds=self.default_options.ttl).isoformat() |
| 43 | + if self.default_options.ttl > 0 |
| 44 | + else None |
| 45 | + ), |
| 46 | + ) |
| 47 | + |
| 48 | + # Write the value to the file |
| 49 | + with open(file_path, "w") as f: |
| 50 | + f.write(metadata.model_dump_json() + "\n") |
| 51 | + f.write(value.model_dump_json()) |
| 52 | + |
| 53 | + def retrieve_object( |
| 54 | + self, |
| 55 | + key: str, |
| 56 | + model_type: type[T], |
| 57 | + override_options: CacheOptions | None = None, |
| 58 | + ) -> T: |
| 59 | + """Retrieve a single object from the cache""" |
| 60 | + self._ensure_cache_dir() |
| 61 | + file_path = self._cache_key_path(key) |
| 62 | + |
| 63 | + if not file_path.exists(): |
| 64 | + logger.debug( |
| 65 | + f"Cache file not found: {file_path}", extra={"file_path": file_path} |
| 66 | + ) |
| 67 | + raise CacheInvalidError(f"Cache file not found: {file_path}") |
| 68 | + |
| 69 | + with open(file_path, "r") as f: |
| 70 | + # Read the metadata and check if it is valid |
| 71 | + metadata = CacheMetadata.model_validate_json(f.readline().strip()) |
| 72 | + |
| 73 | + if not metadata.is_valid(override_options): |
| 74 | + logger.debug( |
| 75 | + f"Cache entry is invalid: {metadata}", extra={"metadata": metadata} |
| 76 | + ) |
| 77 | + raise CacheInvalidError(f"Cache entry is invalid: {metadata}") |
| 78 | + |
| 79 | + return model_type.model_validate_json(f.read()) |
| 80 | + |
| 81 | + def _cache_dir_path(self): |
| 82 | + """Get the cache directory path""" |
| 83 | + return Path(self.cache_dir) |
| 84 | + |
| 85 | + def _ensure_cache_dir(self): |
| 86 | + """Ensure the cache directory exists""" |
| 87 | + self._cache_dir_path().mkdir(parents=True, exist_ok=True) |
| 88 | + |
| 89 | + def _cache_key(self, key: str) -> str: |
| 90 | + """Generate a cache key from the pydantic model""" |
| 91 | + key_str = hashlib.sha256(key.encode()).hexdigest() |
| 92 | + return f"{key_str}.json" |
| 93 | + |
| 94 | + def _cache_key_path(self, key: str) -> Path: |
| 95 | + """Get the cache file path for a given key""" |
| 96 | + return self._cache_dir_path() / self._cache_key(key) |
0 commit comments