Coverage for src/taipanstack/utils/cache.py: 100%
124 statements
« prev ^ index » next coverage.py v7.15.1, created at 2026-11-23 17:43 +0000
« prev ^ index » next coverage.py v7.15.1, created at 2026-11-23 17:43 +0000
1"""
2Intelligent Cache decorator.
4Provides in-memory caching that respects the Result monad and TTL,
5ignoring caching for Err() results.
6"""
8import asyncio
9import functools
10import inspect
11import math
12import time
13from collections.abc import Awaitable, Callable
14from typing import ParamSpec, Protocol, TypeAlias, TypeVar, cast, overload
16from taipanstack.core.result import Ok, Result
18P = ParamSpec("P")
19T = TypeVar("T")
20E = TypeVar("E", bound=Exception)
22MAX_CACHE_KEY_DEPTH = 50
24CacheKey: TypeAlias = tuple[object, ...]
25CacheValue: TypeAlias = tuple[float, object]
26CacheDict: TypeAlias = dict[CacheKey, CacheValue]
29def _check_cache(
30 cache_key: CacheKey,
31 cache: CacheDict,
32 now: float,
33) -> tuple[bool, object]:
34 if cache_key in cache:
35 expiry, value = cache[cache_key]
36 if now < expiry:
37 # Move to end to mark as recently used
38 cache[cache_key] = cache.pop(cache_key)
39 return True, value
40 del cache[cache_key]
41 return False, None
44def _update_cache(
45 cache_key: CacheKey,
46 result: Result[T, E],
47 cache: CacheDict,
48 max_size: int,
49 now: float,
50 ttl: float,
51) -> None:
52 if isinstance(result, Ok):
53 if len(cache) >= max_size:
54 # Evict least recently used (first item)
55 lru_key = next(iter(cache))
56 del cache[lru_key]
57 cache[cache_key] = (now + ttl, result.ok_value)
60def _hash_sequence(
61 val: tuple[object, ...] | list[object], depth: int
62) -> tuple[object, ...]:
63 return tuple(_make_hashable(item, depth) for item in val)
66def _hash_dict(val: dict[object, object], depth: int) -> tuple[object, ...]:
67 items = [
68 (_make_hashable(k, depth), _make_hashable(v, depth)) for k, v in val.items()
69 ]
70 items.sort(key=lambda item: (type(item[0]).__name__, repr(item[0]))) # type: ignore[misc]
71 return tuple(items)
74def _hash_set(val: set[object], depth: int) -> frozenset[object]:
75 return frozenset(_make_hashable(item, depth) for item in val)
78def _dispatch_hashable(val: object, depth: int) -> object:
79 if isinstance(val, (tuple, list)):
80 return _hash_sequence(val, depth + 1)
81 if isinstance(val, dict):
82 return _hash_dict(val, depth + 1)
83 if isinstance(val, set):
84 return _hash_set(val, depth + 1)
85 hash(val)
86 return val
89def _make_hashable(val: object, depth: int = 0) -> object:
90 if depth > MAX_CACHE_KEY_DEPTH:
91 msg = f"Cache key too deeply nested (max depth {MAX_CACHE_KEY_DEPTH})"
92 raise ValueError(msg)
94 return _dispatch_hashable(val, depth)
97def _get_cache_key(
98 func_name: str,
99 args: tuple[object, ...],
100 kwargs: dict[str, object],
101) -> CacheKey:
102 hashable_args = tuple(_make_hashable(arg) for arg in args)
103 hashable_kwargs = tuple(
104 sorted((k, _make_hashable(v)) for k, v in kwargs.items()),
105 )
106 return (func_name, hashable_args, hashable_kwargs)
109def _is_valid_ttl_type(ttl: float) -> bool:
110 return isinstance(ttl, (int, float)) and not isinstance(ttl, bool)
113def _is_valid_ttl_value(ttl: float) -> bool:
114 return math.isfinite(ttl) and ttl >= 0
117def _validate_ttl(ttl: float) -> None:
118 if not _is_valid_ttl_type(ttl) or not _is_valid_ttl_value(ttl):
119 raise ValueError("ttl must be a finite non-negative number")
122def _validate_max_size(max_size: int) -> None:
123 if not isinstance(max_size, int) or isinstance(max_size, bool) or max_size <= 0:
124 raise ValueError("max_size must be a positive integer")
127def _validate_ttl_max_size(ttl: float, max_size: int) -> None:
128 _validate_ttl(ttl)
129 _validate_max_size(max_size)
132def _get_or_create_lock(
133 cache_key: CacheKey,
134 locks: dict[CacheKey, asyncio.Lock],
135 lock_waiters: dict[CacheKey, int],
136) -> asyncio.Lock:
137 if cache_key not in locks:
138 locks[cache_key] = asyncio.Lock()
139 lock_waiters[cache_key] = 0
141 lock_waiters[cache_key] += 1
142 return locks[cache_key]
145def _release_lock(
146 cache_key: CacheKey,
147 locks: dict[CacheKey, asyncio.Lock],
148 lock_waiters: dict[CacheKey, int],
149) -> None:
150 lock_waiters[cache_key] -= 1
151 if lock_waiters[cache_key] == 0:
152 locks.pop(cache_key, None)
153 lock_waiters.pop(cache_key, None)
156def _execute_cached_async_wrapper(
157 func: Callable[P, Awaitable[Result[T, E]]],
158 cache: CacheDict,
159 locks: dict[CacheKey, asyncio.Lock],
160 lock_waiters: dict[CacheKey, int],
161 max_size: int,
162 ttl: float,
163) -> Callable[P, Awaitable[Result[T, E]]]:
164 @functools.wraps(func)
165 async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> Result[T, E]:
166 cache_key = _get_cache_key(
167 cast(str, getattr(func, "__name__", "unknown")),
168 cast(tuple[object, ...], args),
169 cast(dict[str, object], kwargs),
170 )
172 # Check cache before acquiring lock
173 now = time.monotonic()
174 hit, value = _check_cache(cache_key, cache, now)
175 if hit:
176 return Ok(cast(T, value))
178 lock = _get_or_create_lock(cache_key, locks, lock_waiters)
180 try:
181 async with lock:
182 # Double-check cache after acquiring lock
183 now = time.monotonic()
184 hit, value = _check_cache(cache_key, cache, now)
185 if hit:
186 return Ok(cast(T, value))
188 result = await func(*args, **kwargs)
190 _update_cache(cache_key, result, cache, max_size, now, ttl)
191 return result
192 finally:
193 _release_lock(cache_key, locks, lock_waiters)
195 return async_wrapper
198def _execute_cached_sync_wrapper(
199 func: Callable[P, Result[T, E]],
200 cache: CacheDict,
201 max_size: int,
202 ttl: float,
203) -> Callable[P, Result[T, E]]:
204 @functools.wraps(func)
205 def sync_wrapper(*args: P.args, **kwargs: P.kwargs) -> Result[T, E]:
206 cache_key = _get_cache_key(
207 cast(str, getattr(func, "__name__", "unknown")),
208 cast(tuple[object, ...], args),
209 cast(dict[str, object], kwargs),
210 )
211 now = time.monotonic()
213 hit, value = _check_cache(cache_key, cache, now)
214 if hit:
215 return Ok(cast(T, value))
217 result = func(*args, **kwargs)
219 _update_cache(cache_key, result, cache, max_size, now, ttl)
220 return result
222 return sync_wrapper
225class CacheDecorator(Protocol):
226 """Protocol for the cache decorator."""
228 @overload
229 def __call__(
230 self,
231 func: Callable[P, Result[T, E]],
232 ) -> Callable[P, Result[T, E]]: ...
234 @overload
235 def __call__(
236 self,
237 func: Callable[P, Awaitable[Result[T, E]]],
238 ) -> Callable[P, Awaitable[Result[T, E]]]: ...
241def cached(ttl: float, max_size: int = 1024) -> CacheDecorator:
242 """Cache the Ok() results of a function for a given TTL.
244 Err() results are not cached. Supports both async and sync functions.
245 Implements LRU (Least Recently Used) eviction when max_size is reached.
247 Args:
248 ttl: Time to live in seconds.
249 max_size: Maximum number of elements to store in the cache.
251 Returns:
252 Decorator function.
254 """
255 _validate_ttl_max_size(ttl, max_size)
257 _cache: CacheDict = {}
258 _locks: dict[CacheKey, asyncio.Lock] = {}
259 _lock_waiters: dict[CacheKey, int] = {}
261 def decorator(
262 func: Callable[P, Result[T, E]] | Callable[P, Awaitable[Result[T, E]]],
263 ) -> Callable[P, Result[T, E]] | Callable[P, Awaitable[Result[T, E]]]:
264 if inspect.iscoroutinefunction(func):
265 func_coro = cast(Callable[P, Awaitable[Result[T, E]]], func)
266 return _execute_cached_async_wrapper(
267 func_coro, _cache, _locks, _lock_waiters, max_size, ttl
268 )
270 func_sync = cast(Callable[P, Result[T, E]], func)
271 return _execute_cached_sync_wrapper(func_sync, _cache, max_size, ttl)
273 return cast(CacheDecorator, decorator)