|
| 1 | +import functools |
| 2 | +import hashlib |
| 3 | +import inspect |
| 4 | +import json |
| 5 | +from abc import ABC, abstractmethod |
| 6 | +from typing import Any, Optional |
| 7 | + |
| 8 | +from pydantic import BaseModel |
| 9 | + |
| 10 | + |
| 11 | +class CacheInterface(ABC): |
| 12 | + @abstractmethod |
| 13 | + def get(self, key: str) -> Any: |
| 14 | + pass |
| 15 | + |
| 16 | + @abstractmethod |
| 17 | + def set(self, key: str, value) -> None: |
| 18 | + pass |
| 19 | + |
| 20 | + @abstractmethod |
| 21 | + def has_key(self, key: str) -> bool: |
| 22 | + pass |
| 23 | + |
| 24 | + |
| 25 | +class DiskCacheBackend(CacheInterface): |
| 26 | + def __init__(self, cache_dir: str = ".cache"): |
| 27 | + try: |
| 28 | + from diskcache import Cache |
| 29 | + except ImportError: |
| 30 | + raise ImportError( |
| 31 | + "For using the diskcache backend, please install it with `pip install diskcache`." |
| 32 | + ) |
| 33 | + |
| 34 | + self.cache = Cache(cache_dir) |
| 35 | + |
| 36 | + def get(self, key: str) -> Any: |
| 37 | + return self.cache.get(key) |
| 38 | + |
| 39 | + def set(self, key: str, value) -> None: |
| 40 | + self.cache.set(key, value) |
| 41 | + |
| 42 | + def has_key(self, key: str) -> bool: |
| 43 | + return key in self.cache |
| 44 | + |
| 45 | + def __del__(self): |
| 46 | + if hasattr(self, "cache"): |
| 47 | + self.cache.close() |
| 48 | + |
| 49 | + |
| 50 | +def _make_hashable(o): |
| 51 | + if isinstance(o, (tuple, list)): |
| 52 | + return tuple(_make_hashable(e) for e in o) |
| 53 | + elif isinstance(o, dict): |
| 54 | + return tuple(sorted((k, _make_hashable(v)) for k, v in o.items())) |
| 55 | + elif isinstance(o, set): |
| 56 | + return tuple(sorted(_make_hashable(e) for e in o)) |
| 57 | + elif isinstance(o, BaseModel): |
| 58 | + return _make_hashable(o.model_dump()) |
| 59 | + else: |
| 60 | + return o |
| 61 | + |
| 62 | + |
| 63 | +EXCLUDE_KEYS = ["callbacks"] |
| 64 | + |
| 65 | + |
| 66 | +def _generate_cache_key(func, args, kwargs): |
| 67 | + if inspect.ismethod(func): |
| 68 | + args = args[1:] |
| 69 | + |
| 70 | + filtered_kwargs = {k: v for k, v in kwargs.items() if k not in EXCLUDE_KEYS} |
| 71 | + |
| 72 | + key_data = { |
| 73 | + "function": func.__qualname__, |
| 74 | + "args": _make_hashable(args), |
| 75 | + "kwargs": _make_hashable(filtered_kwargs), |
| 76 | + } |
| 77 | + |
| 78 | + key_string = json.dumps(key_data, sort_keys=True, default=str) |
| 79 | + cache_key = hashlib.sha256(key_string.encode("utf-8")).hexdigest() |
| 80 | + return cache_key |
| 81 | + |
| 82 | + |
| 83 | +def cacher(cache_backend: Optional[CacheInterface] = None): |
| 84 | + def decorator(func): |
| 85 | + if cache_backend is None: |
| 86 | + return func |
| 87 | + |
| 88 | + # hack to make pyright happy |
| 89 | + backend: CacheInterface = cache_backend |
| 90 | + |
| 91 | + is_async = inspect.iscoroutinefunction(func) |
| 92 | + |
| 93 | + @functools.wraps(func) |
| 94 | + async def async_wrapper(*args, **kwargs): |
| 95 | + cache_key = _generate_cache_key(func, args, kwargs) |
| 96 | + |
| 97 | + if backend.has_key(cache_key): |
| 98 | + return backend.get(cache_key) |
| 99 | + |
| 100 | + result = await func(*args, **kwargs) |
| 101 | + backend.set(cache_key, result) |
| 102 | + return result |
| 103 | + |
| 104 | + @functools.wraps(func) |
| 105 | + def sync_wrapper(*args, **kwargs): |
| 106 | + cache_key = _generate_cache_key(func, args, kwargs) |
| 107 | + |
| 108 | + if backend.has_key(cache_key): |
| 109 | + return backend.get(cache_key) |
| 110 | + |
| 111 | + result = func(*args, **kwargs) |
| 112 | + backend.set(cache_key, result) |
| 113 | + return result |
| 114 | + |
| 115 | + return async_wrapper if is_async else sync_wrapper |
| 116 | + |
| 117 | + return decorator |
0 commit comments