Coverage for /Users/les/Projects/crackerjack/crackerjack/services/cache.py: 0%
200 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1import hashlib
2import json
3import time
4import typing as t
5from dataclasses import asdict, dataclass, field
6from pathlib import Path
8from crackerjack.models.task import HookResult
11@dataclass
12class CacheEntry:
13 key: str
14 value: t.Any
15 created_at: float = field(default_factory=time.time)
16 accessed_at: float = field(default_factory=time.time)
17 ttl_seconds: int = 3600
18 access_count: int = 0
20 @property
21 def is_expired(self) -> bool:
22 return (time.time() - self.created_at) > self.ttl_seconds
24 @property
25 def age_seconds(self) -> int:
26 return int(time.time() - self.created_at)
28 def touch(self) -> None:
29 self.accessed_at = time.time()
30 self.access_count += 1
32 def to_dict(self) -> dict[str, t.Any]:
33 return asdict(self)
35 @classmethod
36 def from_dict(cls, data: dict[str, t.Any]) -> "CacheEntry":
37 return cls(**data)
40@dataclass
41class CacheStats:
42 hits: int = 0
43 misses: int = 0
44 evictions: int = 0
45 total_entries: int = 0
46 total_size_bytes: int = 0
48 @property
49 def hit_rate(self) -> float:
50 total = self.hits + self.misses
51 return (self.hits / total * 100) if total > 0 else 0.0
53 def to_dict(self) -> dict[str, t.Any]:
54 return {
55 "hits": self.hits,
56 "misses": self.misses,
57 "evictions": self.evictions,
58 "total_entries": self.total_entries,
59 "hit_rate_percent": round(self.hit_rate, 2),
60 "total_size_mb": round(self.total_size_bytes / 1024 / 1024, 2),
61 }
64class InMemoryCache:
65 def __init__(self, max_entries: int = 1000, default_ttl: int = 3600) -> None:
66 self.max_entries = max_entries
67 self.default_ttl = default_ttl
68 self._cache: dict[str, CacheEntry] = {}
69 self.stats = CacheStats()
71 def get(self, key: str) -> t.Any | None:
72 entry = self._cache.get(key)
74 if entry is None:
75 self.stats.misses += 1
76 return None
78 if entry.is_expired:
79 del self._cache[key]
80 self.stats.misses += 1
81 self.stats.evictions += 1
82 return None
84 entry.touch()
85 self.stats.hits += 1
86 return entry.value
88 def set(self, key: str, value: t.Any, ttl_seconds: int | None = None) -> None:
89 if ttl_seconds is None:
90 ttl_seconds = self.default_ttl
92 if len(self._cache) >= self.max_entries:
93 self._evict_lru()
95 self._cache[key] = CacheEntry(
96 key=key,
97 value=value,
98 ttl_seconds=ttl_seconds,
99 )
101 self.stats.total_entries = len(self._cache)
103 def invalidate(self, key: str) -> bool:
104 if key in self._cache:
105 del self._cache[key]
106 self.stats.total_entries = len(self._cache)
107 return True
108 return False
110 def clear(self) -> None:
111 evicted = len(self._cache)
112 self._cache.clear()
113 self.stats.evictions += evicted
114 self.stats.total_entries = 0
116 def cleanup_expired(self) -> int:
117 expired_keys = [key for key, entry in self._cache.items() if entry.is_expired]
119 for key in expired_keys:
120 del self._cache[key]
122 self.stats.evictions += len(expired_keys)
123 self.stats.total_entries = len(self._cache)
124 return len(expired_keys)
126 def _evict_lru(self) -> None:
127 if not self._cache:
128 return
130 lru_key = min(self._cache.keys(), key=lambda k: self._cache[k].accessed_at)
132 del self._cache[lru_key]
133 self.stats.evictions += 1
136class FileCache:
137 def __init__(self, cache_dir: Path, namespace: str = "crackerjack") -> None:
138 self.cache_dir = cache_dir / namespace
139 self.cache_dir.mkdir(parents=True, exist_ok=True)
140 self.stats = CacheStats()
142 def get(self, key: str) -> t.Any | None:
143 cache_file = self._get_cache_file(key)
145 if not cache_file.exists():
146 self.stats.misses += 1
147 return None
149 try:
150 with cache_file.open(encoding="utf-8") as f:
151 data = json.load(f)
152 entry = CacheEntry.from_dict(data)
154 if entry.is_expired:
155 cache_file.unlink(missing_ok=True)
156 self.stats.misses += 1
157 self.stats.evictions += 1
158 return None
160 entry.touch()
162 with cache_file.open("w", encoding="utf-8") as f:
163 json.dump(entry.to_dict(), f)
165 self.stats.hits += 1
166 return entry.value
168 except (json.JSONDecodeError, FileNotFoundError, OSError, KeyError):
169 self.stats.misses += 1
170 cache_file.unlink(missing_ok=True)
171 return None
173 def set(self, key: str, value: t.Any, ttl_seconds: int = 3600) -> None:
174 cache_file = self._get_cache_file(key)
176 entry = CacheEntry(
177 key=key,
178 value=value,
179 ttl_seconds=ttl_seconds,
180 )
182 try:
183 with cache_file.open("w", encoding="utf-8") as f:
184 json.dump(entry.to_dict(), f)
185 except (json.JSONDecodeError, OSError, KeyError):
186 pass
188 def invalidate(self, key: str) -> bool:
189 cache_file = self._get_cache_file(key)
190 if cache_file.exists():
191 cache_file.unlink()
192 return True
193 return False
195 def clear(self) -> None:
196 for cache_file in self.cache_dir.glob("*.cache"):
197 cache_file.unlink(missing_ok=True)
199 def cleanup_expired(self) -> int:
200 removed = 0
201 for cache_file in self.cache_dir.glob("*.cache"):
202 try:
203 with cache_file.open(encoding="utf-8") as f:
204 data = json.load(f)
205 entry = CacheEntry.from_dict(data)
207 if entry.is_expired:
208 cache_file.unlink()
209 removed += 1
210 except (json.JSONDecodeError, FileNotFoundError, OSError, KeyError):
211 cache_file.unlink(missing_ok=True)
212 removed += 1
214 self.stats.evictions += removed
215 return removed
217 def _get_cache_file(self, key: str) -> Path:
218 safe_key = hashlib.md5(key.encode(), usedforsecurity=False).hexdigest()
219 return self.cache_dir / f"{safe_key}.cache"
222class CrackerjackCache:
223 def __init__(
224 self,
225 cache_dir: Path | None = None,
226 enable_disk_cache: bool = True,
227 ) -> None:
228 self.cache_dir = cache_dir or Path.cwd() / ".crackerjack_cache"
229 self.enable_disk_cache = enable_disk_cache
231 self.hook_results_cache = InMemoryCache(max_entries=500, default_ttl=1800)
232 self.file_hash_cache = InMemoryCache(max_entries=2000)
233 self.config_cache = InMemoryCache(max_entries=100, default_ttl=7200)
235 if enable_disk_cache:
236 self.disk_cache = FileCache(self.cache_dir)
238 def get_hook_result(
239 self,
240 hook_name: str,
241 file_hashes: list[str],
242 ) -> HookResult | None:
243 cache_key = self._get_hook_cache_key(hook_name, file_hashes)
244 return self.hook_results_cache.get(cache_key)
246 def set_hook_result(
247 self,
248 hook_name: str,
249 file_hashes: list[str],
250 result: HookResult,
251 ) -> None:
252 cache_key = self._get_hook_cache_key(hook_name, file_hashes)
253 self.hook_results_cache.set(cache_key, result, ttl_seconds=1800)
255 def get_file_hash(self, file_path: Path) -> str | None:
256 stat = file_path.stat()
257 cache_key = f"file_hash: {file_path}: {stat.st_mtime}: {stat.st_size}"
258 return self.file_hash_cache.get(cache_key)
260 def set_file_hash(self, file_path: Path, file_hash: str) -> None:
261 stat = file_path.stat()
262 cache_key = f"file_hash: {file_path}: {stat.st_mtime}: {stat.st_size}"
263 self.file_hash_cache.set(cache_key, file_hash, ttl_seconds=3600)
265 def get_config_data(self, config_key: str) -> t.Any | None:
266 return self.config_cache.get(f"config: {config_key}")
268 def set_config_data(self, config_key: str, data: t.Any) -> None:
269 self.config_cache.set(f"config: {config_key}", data, ttl_seconds=7200)
271 def invalidate_hook_cache(self, hook_name: str | None = None) -> None:
272 if hook_name:
273 keys_to_remove = [
274 key
275 for key in self.hook_results_cache._cache
276 if key.startswith(f"hook_result: {hook_name}: ")
277 ]
278 for key in keys_to_remove:
279 self.hook_results_cache.invalidate(key)
280 else:
281 self.hook_results_cache.clear()
283 def cleanup_all(self) -> dict[str, int]:
284 results = {
285 "hook_results": self.hook_results_cache.cleanup_expired(),
286 "file_hashes": self.file_hash_cache.cleanup_expired(),
287 "config": self.config_cache.cleanup_expired(),
288 }
290 if self.enable_disk_cache:
291 results["disk_cache"] = self.disk_cache.cleanup_expired()
293 return results
295 def get_cache_stats(self) -> dict[str, t.Any]:
296 stats = {
297 "hook_results": self.hook_results_cache.stats.to_dict(),
298 "file_hashes": self.file_hash_cache.stats.to_dict(),
299 "config": self.config_cache.stats.to_dict(),
300 }
302 if self.enable_disk_cache:
303 stats["disk_cache"] = self.disk_cache.stats.to_dict()
305 return stats
307 def _get_hook_cache_key(self, hook_name: str, file_hashes: list[str]) -> str:
308 hash_signature = hashlib.md5(
309 ", ".join(sorted(file_hashes)).encode(),
310 usedforsecurity=False,
311 ).hexdigest()
312 return f"hook_result: {hook_name}: {hash_signature}"