singleflight-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.
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import threading
|
|
2
|
+
import time
|
|
3
|
+
from collections import OrderedDict
|
|
4
|
+
from concurrent.futures import Future
|
|
5
|
+
from typing import Any, Callable, Dict, Optional, Tuple, TypeVar
|
|
6
|
+
|
|
7
|
+
T = TypeVar("T")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CacheEntry:
|
|
11
|
+
__slots__ = ("value", "expiry")
|
|
12
|
+
|
|
13
|
+
def __init__(self, value: Any, ttl: Optional[float]):
|
|
14
|
+
self.value = value
|
|
15
|
+
self.expiry = time.monotonic() + ttl if ttl is not None else None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SingleFlightCache:
|
|
19
|
+
"""
|
|
20
|
+
High-performance thread-safe local cache with Single-Flight logic.
|
|
21
|
+
|
|
22
|
+
Features:
|
|
23
|
+
- Single-Flight: Concurrent cache misses for the same key trigger the underlying
|
|
24
|
+
fetch operation exactly once. Other threads wait for the result.
|
|
25
|
+
- Inflight Disowning: Invalidating (set/remove/clear) a key during inflight computation
|
|
26
|
+
disowns the running future so stale results never overwrite fresh data.
|
|
27
|
+
- Reentrancy Guard: Detects recursive calls on the same thread for the same key to prevent deadlocks.
|
|
28
|
+
- Optimized O(1) LRU & TTL: Uses OrderedDict for O(1) LRU updates and bounded eviction scanning.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
def __init__(self, max_size: Optional[int] = None, ttl: Optional[float] = None):
|
|
32
|
+
"""
|
|
33
|
+
:param max_size: Maximum number of items in the cache (triggers LRU eviction).
|
|
34
|
+
:param ttl: Time-to-live in seconds for cached items.
|
|
35
|
+
"""
|
|
36
|
+
self._max_size = max_size
|
|
37
|
+
self._ttl = ttl
|
|
38
|
+
self._cache: OrderedDict[str, CacheEntry] = OrderedDict()
|
|
39
|
+
# Maps key -> (future, owner_thread_id)
|
|
40
|
+
self._inflight: Dict[str, Tuple[Future[Any], int]] = {}
|
|
41
|
+
self._lock = threading.Lock()
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def ttl(self) -> Optional[float]:
|
|
45
|
+
return self._ttl
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def max_size(self) -> Optional[int]:
|
|
49
|
+
return self._max_size
|
|
50
|
+
|
|
51
|
+
_SENTINEL = object()
|
|
52
|
+
|
|
53
|
+
def _try_read(self, key: str) -> Any:
|
|
54
|
+
"""Return cached value if present and not expired, else _SENTINEL.
|
|
55
|
+
Must be called with self._lock held."""
|
|
56
|
+
entry = self._cache.get(key)
|
|
57
|
+
if entry is not None:
|
|
58
|
+
if entry.expiry is None or time.monotonic() <= entry.expiry:
|
|
59
|
+
self._cache.move_to_end(key)
|
|
60
|
+
return entry.value
|
|
61
|
+
return self._SENTINEL
|
|
62
|
+
|
|
63
|
+
def _store(self, key: str, value: Any) -> None:
|
|
64
|
+
"""Write a value into the cache, evicting if needed.
|
|
65
|
+
Must be called with self._lock held."""
|
|
66
|
+
if (
|
|
67
|
+
self._max_size is not None
|
|
68
|
+
and len(self._cache) >= self._max_size
|
|
69
|
+
and key not in self._cache
|
|
70
|
+
):
|
|
71
|
+
self._evict()
|
|
72
|
+
self._cache[key] = CacheEntry(value, self._ttl)
|
|
73
|
+
self._cache.move_to_end(key)
|
|
74
|
+
|
|
75
|
+
def get(self, key: str, factory_or_default: Any = None, *args: Any, **kwargs: Any) -> Any:
|
|
76
|
+
"""
|
|
77
|
+
Gets a value from the cache.
|
|
78
|
+
- If `factory_or_default` is callable, fetches or computes the value using Single-Flight logic.
|
|
79
|
+
- If `factory_or_default` is not callable, returns the cached value if present, else `factory_or_default`.
|
|
80
|
+
"""
|
|
81
|
+
if callable(factory_or_default):
|
|
82
|
+
return self.get_or_set_if_doesnt_exist(key, factory_or_default, *args, **kwargs)
|
|
83
|
+
|
|
84
|
+
with self._lock:
|
|
85
|
+
val = self._try_read(key)
|
|
86
|
+
if val is not self._SENTINEL:
|
|
87
|
+
return val
|
|
88
|
+
return factory_or_default
|
|
89
|
+
|
|
90
|
+
def set(self, key: str, value: Any) -> None:
|
|
91
|
+
"""Sets a value directly into the cache, disowning any in-flight computation."""
|
|
92
|
+
with self._lock:
|
|
93
|
+
self._store(key, value)
|
|
94
|
+
self._inflight.pop(key, None)
|
|
95
|
+
|
|
96
|
+
def get_or_set_if_doesnt_exist(
|
|
97
|
+
self, key: str, generator: Callable[..., Any], *args: Any, **kwargs: Any
|
|
98
|
+
) -> Any:
|
|
99
|
+
"""
|
|
100
|
+
Returns the cached value if present. On a miss, calls `generator(*args, **kwargs)` to
|
|
101
|
+
produce it — concurrent callers for the same key share one computation.
|
|
102
|
+
"""
|
|
103
|
+
with self._lock:
|
|
104
|
+
value = self._try_read(key)
|
|
105
|
+
if value is not self._SENTINEL:
|
|
106
|
+
return value
|
|
107
|
+
|
|
108
|
+
entry = self._inflight.get(key)
|
|
109
|
+
current_tid = threading.get_ident()
|
|
110
|
+
|
|
111
|
+
future: Future[Any]
|
|
112
|
+
if entry is not None:
|
|
113
|
+
if entry[1] == current_tid:
|
|
114
|
+
raise RecursionError(
|
|
115
|
+
f"Reentrant get_or_set_if_doesnt_exist() for key '{key}' on the same thread would deadlock"
|
|
116
|
+
)
|
|
117
|
+
future = entry[0]
|
|
118
|
+
must_compute = False
|
|
119
|
+
else:
|
|
120
|
+
future = Future()
|
|
121
|
+
self._inflight[key] = (future, current_tid)
|
|
122
|
+
must_compute = True
|
|
123
|
+
|
|
124
|
+
if must_compute:
|
|
125
|
+
try:
|
|
126
|
+
value = generator(*args, **kwargs)
|
|
127
|
+
except BaseException as e:
|
|
128
|
+
with self._lock:
|
|
129
|
+
if self._inflight.get(key, (None,))[0] is future:
|
|
130
|
+
del self._inflight[key]
|
|
131
|
+
future.set_exception(e)
|
|
132
|
+
raise
|
|
133
|
+
|
|
134
|
+
with self._lock:
|
|
135
|
+
owned = self._inflight.get(key, (None,))[0] is future
|
|
136
|
+
if owned:
|
|
137
|
+
del self._inflight[key]
|
|
138
|
+
if value is not None:
|
|
139
|
+
self._store(key, value)
|
|
140
|
+
future.set_result(value)
|
|
141
|
+
return value
|
|
142
|
+
|
|
143
|
+
# Waiter path: another thread is computing — wait for its result.
|
|
144
|
+
result = future.result()
|
|
145
|
+
with self._lock:
|
|
146
|
+
cached = self._try_read(key)
|
|
147
|
+
if cached is not self._SENTINEL:
|
|
148
|
+
return cached
|
|
149
|
+
if result is None:
|
|
150
|
+
return None
|
|
151
|
+
# Result didn't land in cache (invalidated mid-flight) — retry.
|
|
152
|
+
return self.get_or_set_if_doesnt_exist(key, generator, *args, **kwargs)
|
|
153
|
+
|
|
154
|
+
# Alias for get_or_set_if_doesnt_exist
|
|
155
|
+
get_or_set = get_or_set_if_doesnt_exist
|
|
156
|
+
|
|
157
|
+
def remove(self, key: str) -> None:
|
|
158
|
+
"""Remove a key from the cache, disowning any in-flight computation."""
|
|
159
|
+
with self._lock:
|
|
160
|
+
self._cache.pop(key, None)
|
|
161
|
+
self._inflight.pop(key, None)
|
|
162
|
+
|
|
163
|
+
def invalidate(self, key: str) -> None:
|
|
164
|
+
"""Alias for remove()."""
|
|
165
|
+
self.remove(key)
|
|
166
|
+
|
|
167
|
+
def clear(self) -> None:
|
|
168
|
+
"""Clear all items, disowning all in-flight computations."""
|
|
169
|
+
with self._lock:
|
|
170
|
+
self._cache.clear()
|
|
171
|
+
self._inflight.clear()
|
|
172
|
+
|
|
173
|
+
def __len__(self) -> int:
|
|
174
|
+
return len(self._cache)
|
|
175
|
+
|
|
176
|
+
_EVICT_SCAN_LIMIT = 5
|
|
177
|
+
|
|
178
|
+
def _evict(self) -> None:
|
|
179
|
+
"""Evict one item: prefer an expired LRU entry, else true LRU. O(1).
|
|
180
|
+
Must be called with self._lock held."""
|
|
181
|
+
if not self._cache:
|
|
182
|
+
return
|
|
183
|
+
|
|
184
|
+
now = time.monotonic()
|
|
185
|
+
scanned = 0
|
|
186
|
+
for key in self._cache:
|
|
187
|
+
if self._cache[key].expiry is not None and now > self._cache[key].expiry:
|
|
188
|
+
del self._cache[key]
|
|
189
|
+
return
|
|
190
|
+
scanned += 1
|
|
191
|
+
if scanned >= self._EVICT_SCAN_LIMIT:
|
|
192
|
+
break
|
|
193
|
+
|
|
194
|
+
self._cache.popitem(last=False)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
# FastCache is an alias for SingleFlightCache for backward compatibility
|
|
198
|
+
FastCache = SingleFlightCache
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: singleflight-cache
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A high-performance thread-safe local cache with Single-Flight logic
|
|
5
|
+
Project-URL: Homepage, https://github.com/avivklas/singleflight-cache
|
|
6
|
+
Project-URL: Bug Tracker, https://github.com/avivklas/singleflight-cache/issues
|
|
7
|
+
Author-email: Aviv <aviv@example.com>
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
13
|
+
Requires-Python: >=3.7
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# singleflight-cache
|
|
17
|
+
|
|
18
|
+
A high-performance, thread-safe local cache for Python featuring **Single-Flight** execution, **Inflight Disowning**, and **O(1) LRU Eviction**.
|
|
19
|
+
|
|
20
|
+
## The Problem it Solves
|
|
21
|
+
If multiple threads simultaneously experience a cache miss for the same key, traditional caches will queue them up behind a lock, or allow all of them to execute the expensive fetch operation concurrently ("thundering herd").
|
|
22
|
+
|
|
23
|
+
`singleflight-cache` solves this gracefully:
|
|
24
|
+
- **Single-Flight Execution:** Only the first thread executes the data fetch. Other concurrent threads requesting the same key wait passively for the first thread's result without duplicating work.
|
|
25
|
+
- **Inflight Disowning & Invalidation Protection:** Explicit `set()`, `remove()`, `invalidate()`, or `clear()` calls disown ongoing in-flight computations so stale values never overwrite newly cached data.
|
|
26
|
+
- **Reentrancy Guard:** Detects recursive calls on the same thread for the same key to prevent deadlocks with clear `RecursionError` diagnostics.
|
|
27
|
+
- **O(1) LRU & Bounded Eviction:** Uses `OrderedDict` for true O(1) LRU order updates and bounded eviction scanning.
|
|
28
|
+
- **TTL Expiration:** Optional Time-To-Live expiration per key.
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install singleflight-cache
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Usage
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from singleflight_cache import SingleFlightCache # FastCache is also available as an alias
|
|
40
|
+
|
|
41
|
+
# Create a cache with up to 1000 items and a 60-second TTL
|
|
42
|
+
cache = SingleFlightCache(max_size=1000, ttl=60)
|
|
43
|
+
|
|
44
|
+
def fetch_user_data(user_id):
|
|
45
|
+
# This expensive operation will only run ONCE even if 100 threads
|
|
46
|
+
# ask for 'user_123' at the exact same moment.
|
|
47
|
+
response = requests.get(f"https://api.example.com/users/{user_id}")
|
|
48
|
+
return response.json()
|
|
49
|
+
|
|
50
|
+
# Single-Flight execution:
|
|
51
|
+
data = cache.get("user_123", fetch_user_data, "user_123")
|
|
52
|
+
|
|
53
|
+
# Direct cache read (without factory):
|
|
54
|
+
value = cache.get("user_123", default=None)
|
|
55
|
+
|
|
56
|
+
# Direct write (disowns any running in-flight computation):
|
|
57
|
+
cache.set("user_123", {"name": "Alice"})
|
|
58
|
+
|
|
59
|
+
# Explicit invalidation:
|
|
60
|
+
cache.remove("user_123") # or cache.invalidate("user_123")
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Features
|
|
64
|
+
|
|
65
|
+
### In-Flight Disowning
|
|
66
|
+
If key `k` is removed or overwritten (`cache.set("k", new_val)`) while a slow generator is still computing in the background, `singleflight-cache` disowns the running computation. When the slow thread finishes, it detects it no longer owns the slot and discards the stale result instead of corrupting the cache.
|
|
67
|
+
|
|
68
|
+
### Reentrancy Protection
|
|
69
|
+
Attempting to recursively request the same key from within its own generator function raises a `RecursionError` instead of causing a silent thread deadlock.
|
|
70
|
+
|
|
71
|
+
## Benchmarks
|
|
72
|
+
|
|
73
|
+
We simulated a highly concurrent environment experiencing a heavy cache miss ("thundering herd" scenario):
|
|
74
|
+
- **5 distinct keys** requested simultaneously.
|
|
75
|
+
- **10 concurrent threads per key** (50 threads total).
|
|
76
|
+
- Simulated **0.5s** underlying fetch time per miss.
|
|
77
|
+
|
|
78
|
+
| Library | Total Time | Fetch Executions | Notes |
|
|
79
|
+
|---------|------------|------------------|-------|
|
|
80
|
+
| `functools.lru_cache` | 0.507s | 50 | Fast, but suffers from a massive **Thundering Herd**. |
|
|
81
|
+
| `cachetools` + Global Lock | 2.522s | 5 | Prevents herd, but creates a **Global Bottleneck**. |
|
|
82
|
+
| **`singleflight-cache`** | **0.507s** | **5** | **Perfect.** Fully concurrent and strictly single-flight. |
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
singleflight_cache/__init__.py,sha256=NRyHb_hsbw7-38BfBQ5OH4PrEIxFm5Cyu2AreaOuXfk,7121
|
|
2
|
+
singleflight_cache-0.1.0.dist-info/METADATA,sha256=h-Eci_RpPh_PY2ob8Z7yvDxEwlU81BOQDZNwH1-e-ss,3971
|
|
3
|
+
singleflight_cache-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
4
|
+
singleflight_cache-0.1.0.dist-info/RECORD,,
|