recall-cache 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
recall/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """recall — smart caching for any function, simple as requests."""
2
+
3
+ from .cache import cache, CacheBackend, MemoryBackend, DiskBackend, RedisBackend
4
+
5
+ __all__ = ["cache", "CacheBackend", "MemoryBackend", "DiskBackend", "RedisBackend"]
6
+ __version__ = "0.1.0"
recall/cache.py ADDED
@@ -0,0 +1,217 @@
1
+ """Core cache decorator and backends for recall."""
2
+
3
+ import functools
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import pickle
8
+ import time
9
+ from abc import ABC, abstractmethod
10
+ from typing import Any, Callable, Optional, Union
11
+
12
+
13
+ class CacheBackend(ABC):
14
+ """Abstract base class for cache backends."""
15
+
16
+ @abstractmethod
17
+ def get(self, key: str) -> Optional[tuple[float, Any]]:
18
+ """Return (expire_time, value) or None."""
19
+ ...
20
+
21
+ @abstractmethod
22
+ def set(self, key: str, value: Any, ttl: float) -> None:
23
+ """Store value with TTL in seconds."""
24
+ ...
25
+
26
+ @abstractmethod
27
+ def delete(self, key: str) -> None:
28
+ """Delete a key."""
29
+ ...
30
+
31
+ @abstractmethod
32
+ def clear(self) -> None:
33
+ """Clear all cached values."""
34
+ ...
35
+
36
+
37
+ class MemoryBackend(CacheBackend):
38
+ """In-memory cache with TTL and maxsize (LRU eviction)."""
39
+
40
+ def __init__(self, maxsize: int = 1000):
41
+ self._cache: dict[str, tuple[float, Any]] = {}
42
+ self._access: dict[str, float] = {}
43
+ self.maxsize = maxsize
44
+
45
+ def get(self, key: str) -> Optional[tuple[float, Any]]:
46
+ if key in self._cache:
47
+ expire_time, value = self._cache[key]
48
+ if expire_time > time.time():
49
+ self._access[key] = time.time()
50
+ return (expire_time, value)
51
+ else:
52
+ del self._cache[key]
53
+ del self._access[key]
54
+ return None
55
+
56
+ def set(self, key: str, value: Any, ttl: float) -> None:
57
+ if len(self._cache) >= self.maxsize and key not in self._cache:
58
+ self._evict()
59
+ self._cache[key] = (time.time() + ttl, value)
60
+ self._access[key] = time.time()
61
+
62
+ def delete(self, key: str) -> None:
63
+ self._cache.pop(key, None)
64
+ self._access.pop(key, None)
65
+
66
+ def clear(self) -> None:
67
+ self._cache.clear()
68
+ self._access.clear()
69
+
70
+ def _evict(self):
71
+ """Evict least recently used item."""
72
+ if self._access:
73
+ oldest = min(self._access, key=self._access.get)
74
+ del self._cache[oldest]
75
+ del self._access[oldest]
76
+
77
+
78
+ class DiskBackend(CacheBackend):
79
+ """Persistent disk cache using pickle files."""
80
+
81
+ def __init__(self, directory: str = ".recall_cache"):
82
+ self.directory = directory
83
+ os.makedirs(directory, exist_ok=True)
84
+
85
+ def _path(self, key: str) -> str:
86
+ safe = hashlib.sha256(key.encode()).hexdigest()[:16]
87
+ return os.path.join(self.directory, f"{safe}.cache")
88
+
89
+ def get(self, key: str) -> Optional[tuple[float, Any]]:
90
+ path = self._path(key)
91
+ if os.path.exists(path):
92
+ try:
93
+ with open(path, "rb") as f:
94
+ expire_time, value = pickle.load(f)
95
+ if expire_time > time.time():
96
+ return (expire_time, value)
97
+ else:
98
+ os.remove(path)
99
+ except (pickle.PickleError, OSError):
100
+ pass
101
+ return None
102
+
103
+ def set(self, key: str, value: Any, ttl: float) -> None:
104
+ path = self._path(key)
105
+ with open(path, "wb") as f:
106
+ pickle.dump((time.time() + ttl, value), f)
107
+
108
+ def delete(self, key: str) -> None:
109
+ path = self._path(key)
110
+ if os.path.exists(path):
111
+ os.remove(path)
112
+
113
+ def clear(self) -> None:
114
+ for f in os.listdir(self.directory):
115
+ if f.endswith(".cache"):
116
+ os.remove(os.path.join(self.directory, f))
117
+
118
+
119
+ class RedisBackend(CacheBackend):
120
+ """Redis cache backend."""
121
+
122
+ def __init__(self, url: str = "redis://localhost:6379", prefix: str = "recall:"):
123
+ import redis
124
+ self.client = redis.from_url(url)
125
+ self.prefix = prefix
126
+
127
+ def _key(self, key: str) -> str:
128
+ return f"{self.prefix}{key}"
129
+
130
+ def get(self, key: str) -> Optional[tuple[float, Any]]:
131
+ raw = self.client.get(self._key(key))
132
+ if raw:
133
+ return pickle.loads(raw)
134
+ return None
135
+
136
+ def set(self, key: str, value: Any, ttl: float) -> None:
137
+ data = pickle.dumps((time.time() + ttl, value))
138
+ self.client.setex(self._key(key), int(ttl), data)
139
+
140
+ def delete(self, key: str) -> None:
141
+ self.client.delete(self._key(key))
142
+
143
+ def clear(self) -> None:
144
+ keys = self.client.keys(f"{self.prefix}*")
145
+ if keys:
146
+ self.client.delete(*keys)
147
+
148
+
149
+ def _make_key(func: Callable, args: tuple, kwargs: dict) -> str:
150
+ """Generate a unique cache key from function and arguments."""
151
+ key_data = json.dumps({
152
+ "func": f"{func.__module__}.{func.__qualname__}",
153
+ "args": args,
154
+ "kwargs": kwargs,
155
+ }, sort_keys=True, default=str)
156
+ return hashlib.sha256(key_data.encode()).hexdigest()
157
+
158
+
159
+ def cache(
160
+ ttl: Union[str, float] = "1h",
161
+ maxsize: int = 1000,
162
+ backend: Optional[CacheBackend] = None,
163
+ key_fn: Optional[Callable] = None,
164
+ ):
165
+ """
166
+ Decorator that caches function results with TTL.
167
+
168
+ Args:
169
+ ttl: Time-to-live in seconds, or shorthand like "1h", "30m", "7d".
170
+ maxsize: Maximum number of cached items (memory backend only).
171
+ backend: Custom backend (MemoryBackend, DiskBackend, RedisBackend).
172
+ key_fn: Custom key function f(func, args, kwargs) -> str.
173
+
174
+ Usage:
175
+ @cache(ttl="1h")
176
+ def get_user(user_id):
177
+ return db.query(user_id)
178
+
179
+ @cache(ttl=300, backend=DiskBackend("/tmp/cache"))
180
+ def expensive_computation(x, y):
181
+ return x ** y
182
+ """
183
+ # Parse TTL shorthand
184
+ if isinstance(ttl, str):
185
+ multipliers = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
186
+ ttl = float(ttl[:-1]) * multipliers.get(ttl[-1].lower(), 1)
187
+
188
+ if backend is None:
189
+ backend = MemoryBackend(maxsize=maxsize)
190
+
191
+ def decorator(func: Callable) -> Callable:
192
+ @functools.wraps(func)
193
+ def wrapper(*args, **kwargs):
194
+ if key_fn:
195
+ k = key_fn(func, args, kwargs)
196
+ else:
197
+ k = _make_key(func, args, kwargs)
198
+
199
+ result = backend.get(k)
200
+ if result is not None:
201
+ _, value = result
202
+ return value
203
+
204
+ value = func(*args, **kwargs)
205
+ backend.set(k, value, ttl)
206
+ return value
207
+
208
+ # Attach cache management methods
209
+ wrapper.cache_backend = backend
210
+ wrapper.cache_clear = backend.clear
211
+ wrapper.cache_delete = lambda *a, **kw: backend.delete(
212
+ key_fn(func, a, kw) if key_fn else _make_key(func, a, kw)
213
+ )
214
+
215
+ return wrapper
216
+
217
+ return decorator
@@ -0,0 +1,137 @@
1
+ Metadata-Version: 2.5
2
+ Name: recall-cache
3
+ Version: 0.1.0
4
+ Summary: Smart caching for any function — simple as requests
5
+ Project-URL: Homepage, https://github.com/hermes-telegram/recall
6
+ Author-email: hermes-telegram <hermes_tm@agentmail.to>
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Keywords: cache,caching,diskcache,memoize,redis,ttl
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Libraries
13
+ Requires-Python: >=3.8
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest; extra == 'dev'
16
+ Requires-Dist: redis; extra == 'dev'
17
+ Provides-Extra: redis
18
+ Requires-Dist: redis>=4.0; extra == 'redis'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # recall
22
+
23
+ Smart caching for any function — simple as requests.
24
+
25
+ ```python
26
+ from recall import cache
27
+
28
+ @cache(ttl="1h")
29
+ def get_user(user_id):
30
+ return db.query(user_id)
31
+ ```
32
+
33
+ ## Features
34
+
35
+ - **Simple API** — just `@cache(ttl="1h")` on any function
36
+ - **Multiple backends** — Memory, Disk, Redis
37
+ - **TTL shorthand** — `"30m"`, `"1h"`, `"7d"` instead of raw seconds
38
+ - **LRU eviction** — automatic cleanup when maxsize is reached
39
+ - **Thread-safe** — works in concurrent environments
40
+ - **Zero dependencies** — Redis backend optional
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install recall
46
+ # With Redis support:
47
+ pip install recall[redis]
48
+ ```
49
+
50
+ ## Quick Start
51
+
52
+ ```python
53
+ from recall import cache
54
+ import time
55
+
56
+ @cache(ttl="1h", maxsize=1000)
57
+ def expensive_func(x):
58
+ time.sleep(2)
59
+ return x * 2
60
+
61
+ # First call: computes
62
+ result = expensive_func(5) # takes 2 seconds
63
+
64
+ # Second call: instant (from cache)
65
+ result = expensive_func(5) # returns immediately
66
+ ```
67
+
68
+ ## Backends
69
+
70
+ ### Memory (default)
71
+
72
+ ```python
73
+ @cache(ttl="1h", maxsize=1000)
74
+ def func(x):
75
+ return x * 2
76
+ ```
77
+
78
+ ### Disk (persistent)
79
+
80
+ ```python
81
+ from recall import DiskBackend
82
+
83
+ @cache(ttl="1h", backend=DiskBackend("/tmp/my_cache"))
84
+ def func(x):
85
+ return x * 2
86
+ ```
87
+
88
+ ### Redis
89
+
90
+ ```python
91
+ from recall import RedisBackend
92
+
93
+ @cache(ttl="1h", backend=RedisBackend("redis://localhost:6379"))
94
+ def func(x):
95
+ return x * 2
96
+ ```
97
+
98
+ ## Cache Management
99
+
100
+ ```python
101
+ # Clear all cached values
102
+ expensive_func.cache_clear()
103
+
104
+ # Delete specific key
105
+ expensive_func.cache_delete(42)
106
+
107
+ # Custom key function
108
+ @cache(ttl="1h", key_fn=lambda f, a, k: f"{a}_{k.get('mode', '')}")
109
+ def custom(data, mode):
110
+ return f"{data}_{mode}"
111
+ ```
112
+
113
+ ## TTL Formats
114
+
115
+ | Shorthand | Meaning |
116
+ |-----------|---------|
117
+ | `"30s"` | 30 seconds |
118
+ | `"5m"` | 5 minutes |
119
+ | `"1h"` | 1 hour |
120
+ | `"1d"` | 1 day |
121
+ | `"1w"` | 1 week |
122
+ | `3600` | raw seconds (int/float) |
123
+
124
+ ## Why recall?
125
+
126
+ | Tool | Issue |
127
+ |------|-------|
128
+ | `functools.lru_cache` | No TTL, no persistence |
129
+ | `cachetools` | Complex API, no disk/Redis |
130
+ | `redis` alone | Manual key management |
131
+ | `dogpile.cache` | Overkill for simple use |
132
+
133
+ **recall** = simple API + real backends + TTL done right.
134
+
135
+ ## License
136
+
137
+ MIT
@@ -0,0 +1,6 @@
1
+ recall/__init__.py,sha256=DQYA2z6XR4n_xu7Em5ROigsS6q-QOLIxC325RHKuOfw,258
2
+ recall/cache.py,sha256=eEsOGGgplO-6wKp3qTgRVqKelZ2uRYrb0Gg-kTcWulw,6594
3
+ recall_cache-0.1.0.dist-info/METADATA,sha256=-XgG4R50aqdcjk0cehYwrRPjCe-xINWUZxwu4hHEFDI,2882
4
+ recall_cache-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
5
+ recall_cache-0.1.0.dist-info/licenses/LICENSE,sha256=JlZ8sQSp-7ydoSasBSWtgwHJ1QmauZOM8wxQ1gfgrXA,1072
6
+ recall_cache-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 hermes-telegram
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.