singleflight-cache 0.1.0__tar.gz
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.
- singleflight_cache-0.1.0/.github/workflows/ci.yml +24 -0
- singleflight_cache-0.1.0/.github/workflows/publish.yml +47 -0
- singleflight_cache-0.1.0/.gitignore +11 -0
- singleflight_cache-0.1.0/PKG-INFO +82 -0
- singleflight_cache-0.1.0/README.md +67 -0
- singleflight_cache-0.1.0/benchmark.py +100 -0
- singleflight_cache-0.1.0/pyproject.toml +24 -0
- singleflight_cache-0.1.0/src/singleflight_cache/__init__.py +198 -0
- singleflight_cache-0.1.0/tests/test_cache.py +222 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [ master, main ]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: [ master, main ]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
test:
|
|
11
|
+
name: Run Tests (Python ${{ matrix.python-version }})
|
|
12
|
+
runs-on: ubuntu-latest
|
|
13
|
+
strategy:
|
|
14
|
+
matrix:
|
|
15
|
+
python-version: ['3.8', '3.9', '3.10', '3.11', '3.12', '3.13']
|
|
16
|
+
steps:
|
|
17
|
+
- uses: actions/checkout@v4
|
|
18
|
+
- name: Set up Python ${{ matrix.python-version }}
|
|
19
|
+
uses: actions/setup-python@v5
|
|
20
|
+
with:
|
|
21
|
+
python-version: ${{ matrix.python-version }}
|
|
22
|
+
- name: Run Unit Tests
|
|
23
|
+
run: |
|
|
24
|
+
PYTHONPATH=src python -m unittest discover -s tests -p "test_*.py"
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
push:
|
|
7
|
+
tags:
|
|
8
|
+
- 'v*'
|
|
9
|
+
workflow_dispatch:
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
test:
|
|
13
|
+
name: Run Unit Tests
|
|
14
|
+
runs-on: ubuntu-latest
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@v4
|
|
17
|
+
- name: Set up Python
|
|
18
|
+
uses: actions/setup-python@v5
|
|
19
|
+
with:
|
|
20
|
+
python-version: '3.11'
|
|
21
|
+
- name: Run Tests
|
|
22
|
+
run: |
|
|
23
|
+
PYTHONPATH=src python -m unittest discover -s tests -p "test_*.py"
|
|
24
|
+
|
|
25
|
+
build-and-publish:
|
|
26
|
+
name: Build and Publish to PyPI
|
|
27
|
+
needs: test
|
|
28
|
+
runs-on: ubuntu-latest
|
|
29
|
+
permissions:
|
|
30
|
+
id-token: write # Required for PyPI OIDC Trusted Publishing
|
|
31
|
+
steps:
|
|
32
|
+
- uses: actions/checkout@v4
|
|
33
|
+
- name: Set up Python
|
|
34
|
+
uses: actions/setup-python@v5
|
|
35
|
+
with:
|
|
36
|
+
python-version: '3.11'
|
|
37
|
+
- name: Install build dependencies
|
|
38
|
+
run: |
|
|
39
|
+
python -m pip install --upgrade pip
|
|
40
|
+
pip install build hatchling
|
|
41
|
+
- name: Build package
|
|
42
|
+
run: |
|
|
43
|
+
python -m build
|
|
44
|
+
- name: Publish package to PyPI
|
|
45
|
+
uses: pypa/gh-action-pypi-publish@release/v1
|
|
46
|
+
with:
|
|
47
|
+
skip-existing: true
|
|
@@ -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,67 @@
|
|
|
1
|
+
# singleflight-cache
|
|
2
|
+
|
|
3
|
+
A high-performance, thread-safe local cache for Python featuring **Single-Flight** execution, **Inflight Disowning**, and **O(1) LRU Eviction**.
|
|
4
|
+
|
|
5
|
+
## The Problem it Solves
|
|
6
|
+
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").
|
|
7
|
+
|
|
8
|
+
`singleflight-cache` solves this gracefully:
|
|
9
|
+
- **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.
|
|
10
|
+
- **Inflight Disowning & Invalidation Protection:** Explicit `set()`, `remove()`, `invalidate()`, or `clear()` calls disown ongoing in-flight computations so stale values never overwrite newly cached data.
|
|
11
|
+
- **Reentrancy Guard:** Detects recursive calls on the same thread for the same key to prevent deadlocks with clear `RecursionError` diagnostics.
|
|
12
|
+
- **O(1) LRU & Bounded Eviction:** Uses `OrderedDict` for true O(1) LRU order updates and bounded eviction scanning.
|
|
13
|
+
- **TTL Expiration:** Optional Time-To-Live expiration per key.
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pip install singleflight-cache
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from singleflight_cache import SingleFlightCache # FastCache is also available as an alias
|
|
25
|
+
|
|
26
|
+
# Create a cache with up to 1000 items and a 60-second TTL
|
|
27
|
+
cache = SingleFlightCache(max_size=1000, ttl=60)
|
|
28
|
+
|
|
29
|
+
def fetch_user_data(user_id):
|
|
30
|
+
# This expensive operation will only run ONCE even if 100 threads
|
|
31
|
+
# ask for 'user_123' at the exact same moment.
|
|
32
|
+
response = requests.get(f"https://api.example.com/users/{user_id}")
|
|
33
|
+
return response.json()
|
|
34
|
+
|
|
35
|
+
# Single-Flight execution:
|
|
36
|
+
data = cache.get("user_123", fetch_user_data, "user_123")
|
|
37
|
+
|
|
38
|
+
# Direct cache read (without factory):
|
|
39
|
+
value = cache.get("user_123", default=None)
|
|
40
|
+
|
|
41
|
+
# Direct write (disowns any running in-flight computation):
|
|
42
|
+
cache.set("user_123", {"name": "Alice"})
|
|
43
|
+
|
|
44
|
+
# Explicit invalidation:
|
|
45
|
+
cache.remove("user_123") # or cache.invalidate("user_123")
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Features
|
|
49
|
+
|
|
50
|
+
### In-Flight Disowning
|
|
51
|
+
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.
|
|
52
|
+
|
|
53
|
+
### Reentrancy Protection
|
|
54
|
+
Attempting to recursively request the same key from within its own generator function raises a `RecursionError` instead of causing a silent thread deadlock.
|
|
55
|
+
|
|
56
|
+
## Benchmarks
|
|
57
|
+
|
|
58
|
+
We simulated a highly concurrent environment experiencing a heavy cache miss ("thundering herd" scenario):
|
|
59
|
+
- **5 distinct keys** requested simultaneously.
|
|
60
|
+
- **10 concurrent threads per key** (50 threads total).
|
|
61
|
+
- Simulated **0.5s** underlying fetch time per miss.
|
|
62
|
+
|
|
63
|
+
| Library | Total Time | Fetch Executions | Notes |
|
|
64
|
+
|---------|------------|------------------|-------|
|
|
65
|
+
| `functools.lru_cache` | 0.507s | 50 | Fast, but suffers from a massive **Thundering Herd**. |
|
|
66
|
+
| `cachetools` + Global Lock | 2.522s | 5 | Prevents herd, but creates a **Global Bottleneck**. |
|
|
67
|
+
| **`singleflight-cache`** | **0.507s** | **5** | **Perfect.** Fully concurrent and strictly single-flight. |
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import threading
|
|
3
|
+
import functools
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
sys.path.insert(0, './src')
|
|
7
|
+
from singleflight_cache import FastCache
|
|
8
|
+
try:
|
|
9
|
+
from cachetools import TTLCache
|
|
10
|
+
except ImportError:
|
|
11
|
+
print("Please install cachetools to run this benchmark: pip install cachetools")
|
|
12
|
+
sys.exit(1)
|
|
13
|
+
|
|
14
|
+
def simulate_work(duration=0.1):
|
|
15
|
+
"""Simulate a costly data fetch operation."""
|
|
16
|
+
time.sleep(duration)
|
|
17
|
+
return "result"
|
|
18
|
+
|
|
19
|
+
def run_benchmark(fetch_func, num_keys=5, threads_per_key=10):
|
|
20
|
+
start = time.time()
|
|
21
|
+
threads = []
|
|
22
|
+
|
|
23
|
+
for k in range(num_keys):
|
|
24
|
+
key = f"key_{k}"
|
|
25
|
+
for _ in range(threads_per_key):
|
|
26
|
+
t = threading.Thread(target=fetch_func, args=(key,))
|
|
27
|
+
threads.append(t)
|
|
28
|
+
t.start()
|
|
29
|
+
|
|
30
|
+
for t in threads:
|
|
31
|
+
t.join()
|
|
32
|
+
|
|
33
|
+
end = time.time()
|
|
34
|
+
return end - start
|
|
35
|
+
|
|
36
|
+
def main():
|
|
37
|
+
num_keys = 5
|
|
38
|
+
threads_per_key = 10
|
|
39
|
+
fetch_time = 0.5
|
|
40
|
+
|
|
41
|
+
print("="*80)
|
|
42
|
+
print("BENCHMARK: Concurrent Cache Misses (Thundering Herd)")
|
|
43
|
+
print("="*80)
|
|
44
|
+
print(f"Distinct Keys Requested : {num_keys}")
|
|
45
|
+
print(f"Concurrent Threads / Key: {threads_per_key}")
|
|
46
|
+
print(f"Total Threads : {num_keys * threads_per_key}")
|
|
47
|
+
print(f"Simulated Fetch Time : {fetch_time}s")
|
|
48
|
+
print("-" * 80)
|
|
49
|
+
print(f"{'Library':<30} | {'Time (s)':<10} | {'Fetch Executions':<20} | {'Notes'}")
|
|
50
|
+
print("-" * 80)
|
|
51
|
+
|
|
52
|
+
# 1. functools.lru_cache (Built-in)
|
|
53
|
+
call_count_lru = [0]
|
|
54
|
+
lock_lru = threading.Lock()
|
|
55
|
+
|
|
56
|
+
@functools.lru_cache(maxsize=1000)
|
|
57
|
+
def builtin_fetch(key):
|
|
58
|
+
with lock_lru:
|
|
59
|
+
call_count_lru[0] += 1
|
|
60
|
+
return simulate_work(fetch_time)
|
|
61
|
+
|
|
62
|
+
t_lru = run_benchmark(builtin_fetch, num_keys, threads_per_key)
|
|
63
|
+
print(f"{'functools.lru_cache':<30} | {t_lru:<10.3f} | {call_count_lru[0]:<20} | Thundering Herd!")
|
|
64
|
+
|
|
65
|
+
# 2. Naive Thread-Safe Cache (cachetools + Lock)
|
|
66
|
+
naive_cache = TTLCache(maxsize=1000, ttl=60)
|
|
67
|
+
naive_lock = threading.RLock()
|
|
68
|
+
call_count_naive = [0]
|
|
69
|
+
|
|
70
|
+
def naive_fetch(key):
|
|
71
|
+
with naive_lock:
|
|
72
|
+
if key in naive_cache:
|
|
73
|
+
return naive_cache[key]
|
|
74
|
+
call_count_naive[0] += 1
|
|
75
|
+
val = simulate_work(fetch_time)
|
|
76
|
+
naive_cache[key] = val
|
|
77
|
+
return val
|
|
78
|
+
|
|
79
|
+
t_naive = run_benchmark(naive_fetch, num_keys, threads_per_key)
|
|
80
|
+
print(f"{'cachetools + Global Lock':<30} | {t_naive:<10.3f} | {call_count_naive[0]:<20} | Bottlenecked!")
|
|
81
|
+
|
|
82
|
+
# 3. singleflight-cache (Our library)
|
|
83
|
+
fast_cache = FastCache(ttl=60, max_size=1000)
|
|
84
|
+
call_count_fast = [0]
|
|
85
|
+
lock_fast = threading.Lock()
|
|
86
|
+
|
|
87
|
+
def fast_factory():
|
|
88
|
+
with lock_fast:
|
|
89
|
+
call_count_fast[0] += 1
|
|
90
|
+
return simulate_work(fetch_time)
|
|
91
|
+
|
|
92
|
+
def fast_fetch(key):
|
|
93
|
+
return fast_cache.get(key, fast_factory)
|
|
94
|
+
|
|
95
|
+
t_fast = run_benchmark(fast_fetch, num_keys, threads_per_key)
|
|
96
|
+
print(f"{'singleflight-cache':<30} | {t_fast:<10.3f} | {call_count_fast[0]:<20} | Perfect!")
|
|
97
|
+
print("=" * 80)
|
|
98
|
+
|
|
99
|
+
if __name__ == "__main__":
|
|
100
|
+
main()
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "singleflight-cache"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name="Aviv", email="aviv@example.com" },
|
|
10
|
+
]
|
|
11
|
+
description = "A high-performance thread-safe local cache with Single-Flight logic"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
requires-python = ">=3.7"
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
"Homepage" = "https://github.com/avivklas/singleflight-cache"
|
|
24
|
+
"Bug Tracker" = "https://github.com/avivklas/singleflight-cache/issues"
|
|
@@ -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,222 @@
|
|
|
1
|
+
import threading
|
|
2
|
+
import time
|
|
3
|
+
from concurrent.futures import Future, ThreadPoolExecutor
|
|
4
|
+
from threading import Event, Thread
|
|
5
|
+
from typing import Any, List
|
|
6
|
+
from unittest import TestCase
|
|
7
|
+
from unittest.mock import Mock
|
|
8
|
+
|
|
9
|
+
from singleflight_cache import FastCache, SingleFlightCache
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class TestSingleFlightCache(TestCase):
|
|
13
|
+
def setUp(self) -> None:
|
|
14
|
+
self.cache: SingleFlightCache = SingleFlightCache(max_size=3, ttl=None)
|
|
15
|
+
|
|
16
|
+
def test_backwards_compatibility_fast_cache_alias(self):
|
|
17
|
+
self.assertIs(FastCache, SingleFlightCache)
|
|
18
|
+
fc = FastCache(max_size=5, ttl=10)
|
|
19
|
+
self.assertEqual(fc.max_size, 5)
|
|
20
|
+
self.assertEqual(fc.ttl, 10)
|
|
21
|
+
|
|
22
|
+
def test_ttl_and_max_size_properties(self):
|
|
23
|
+
cache = SingleFlightCache(max_size=7, ttl=42)
|
|
24
|
+
self.assertEqual(cache.max_size, 7)
|
|
25
|
+
self.assertEqual(cache.ttl, 42)
|
|
26
|
+
|
|
27
|
+
def test_get_returns_default_when_key_missing(self):
|
|
28
|
+
self.assertIsNone(self.cache.get("missing"))
|
|
29
|
+
self.assertEqual(self.cache.get("missing", "fallback"), "fallback")
|
|
30
|
+
|
|
31
|
+
def test_set_then_get_returns_stored_value(self):
|
|
32
|
+
self.cache.set("key", "value")
|
|
33
|
+
self.assertEqual(self.cache.get("key"), "value")
|
|
34
|
+
|
|
35
|
+
def test_get_returns_default_when_entry_expired(self):
|
|
36
|
+
cache = SingleFlightCache(ttl=10)
|
|
37
|
+
cache.set("key", "value")
|
|
38
|
+
entry = cache._cache["key"]
|
|
39
|
+
entry.expiry = time.monotonic() - 1
|
|
40
|
+
|
|
41
|
+
self.assertIsNone(cache.get("key"))
|
|
42
|
+
|
|
43
|
+
def test_len_reflects_number_of_stored_items(self):
|
|
44
|
+
self.assertEqual(len(self.cache), 0)
|
|
45
|
+
self.cache.set("a", 1)
|
|
46
|
+
self.cache.set("b", 2)
|
|
47
|
+
self.assertEqual(len(self.cache), 2)
|
|
48
|
+
|
|
49
|
+
def test_remove_and_invalidate(self):
|
|
50
|
+
self.cache.set("key1", "val1")
|
|
51
|
+
self.cache.set("key2", "val2")
|
|
52
|
+
self.cache.remove("key1")
|
|
53
|
+
self.cache.invalidate("key2")
|
|
54
|
+
self.assertIsNone(self.cache.get("key1"))
|
|
55
|
+
self.assertIsNone(self.cache.get("key2"))
|
|
56
|
+
self.assertEqual(len(self.cache), 0)
|
|
57
|
+
|
|
58
|
+
def test_clear_removes_all_items(self):
|
|
59
|
+
self.cache.set("a", 1)
|
|
60
|
+
self.cache.set("b", 2)
|
|
61
|
+
self.cache.clear()
|
|
62
|
+
self.assertEqual(len(self.cache), 0)
|
|
63
|
+
|
|
64
|
+
def test_single_flight_execution(self):
|
|
65
|
+
call_count = 0
|
|
66
|
+
lock = threading.Lock()
|
|
67
|
+
|
|
68
|
+
def factory(key):
|
|
69
|
+
nonlocal call_count
|
|
70
|
+
with lock:
|
|
71
|
+
call_count += 1
|
|
72
|
+
time.sleep(0.1)
|
|
73
|
+
return f"value_for_{key}"
|
|
74
|
+
|
|
75
|
+
results = []
|
|
76
|
+
threads = []
|
|
77
|
+
|
|
78
|
+
def worker():
|
|
79
|
+
res = self.cache.get("test_key", factory, "test_key")
|
|
80
|
+
results.append(res)
|
|
81
|
+
|
|
82
|
+
for _ in range(20):
|
|
83
|
+
t = threading.Thread(target=worker)
|
|
84
|
+
threads.append(t)
|
|
85
|
+
t.start()
|
|
86
|
+
|
|
87
|
+
for t in threads:
|
|
88
|
+
t.join()
|
|
89
|
+
|
|
90
|
+
self.assertEqual(len(results), 20)
|
|
91
|
+
self.assertTrue(all(r == "value_for_test_key" for r in results))
|
|
92
|
+
self.assertEqual(call_count, 1)
|
|
93
|
+
|
|
94
|
+
def test_set_evicts_least_recently_used_item(self):
|
|
95
|
+
cache = SingleFlightCache(max_size=2)
|
|
96
|
+
cache.set("a", "va")
|
|
97
|
+
cache.set("b", "vb")
|
|
98
|
+
|
|
99
|
+
# Access 'a' to make it most recently used
|
|
100
|
+
cache.get("a")
|
|
101
|
+
|
|
102
|
+
# Add 'c', which should evict 'b'
|
|
103
|
+
cache.set("c", "vc")
|
|
104
|
+
|
|
105
|
+
self.assertIsNone(cache.get("b"))
|
|
106
|
+
self.assertEqual(cache.get("a"), "va")
|
|
107
|
+
self.assertEqual(cache.get("c"), "vc")
|
|
108
|
+
self.assertEqual(len(cache), 2)
|
|
109
|
+
|
|
110
|
+
def test_eviction_prefers_expired_items(self):
|
|
111
|
+
cache = SingleFlightCache(max_size=2)
|
|
112
|
+
cache.set("a", "va")
|
|
113
|
+
cache.set("b", "vb")
|
|
114
|
+
|
|
115
|
+
entry_a = cache._cache["a"]
|
|
116
|
+
entry_a.expiry = time.monotonic() - 10
|
|
117
|
+
cache.get("b")
|
|
118
|
+
|
|
119
|
+
cache.set("c", "vc")
|
|
120
|
+
|
|
121
|
+
self.assertIsNone(cache.get("a"))
|
|
122
|
+
self.assertEqual(cache.get("b"), "vb")
|
|
123
|
+
self.assertEqual(cache.get("c"), "vc")
|
|
124
|
+
|
|
125
|
+
def test_get_or_set_if_doesnt_exist_caches_result(self):
|
|
126
|
+
generator = Mock(return_value="generated-value")
|
|
127
|
+
result = self.cache.get_or_set_if_doesnt_exist("key", generator)
|
|
128
|
+
self.assertEqual(result, "generated-value")
|
|
129
|
+
generator.assert_called_once()
|
|
130
|
+
self.assertEqual(self.cache.get("key"), "generated-value")
|
|
131
|
+
|
|
132
|
+
def test_exception_propagation(self):
|
|
133
|
+
class MyError(Exception):
|
|
134
|
+
pass
|
|
135
|
+
|
|
136
|
+
def faulty_factory():
|
|
137
|
+
time.sleep(0.05)
|
|
138
|
+
raise MyError("Failed")
|
|
139
|
+
|
|
140
|
+
threads = []
|
|
141
|
+
exceptions = []
|
|
142
|
+
|
|
143
|
+
def worker():
|
|
144
|
+
try:
|
|
145
|
+
self.cache.get("bad_key", faulty_factory)
|
|
146
|
+
except Exception as e:
|
|
147
|
+
exceptions.append(e)
|
|
148
|
+
|
|
149
|
+
for _ in range(10):
|
|
150
|
+
t = threading.Thread(target=worker)
|
|
151
|
+
threads.append(t)
|
|
152
|
+
t.start()
|
|
153
|
+
|
|
154
|
+
for t in threads:
|
|
155
|
+
t.join()
|
|
156
|
+
|
|
157
|
+
self.assertEqual(len(exceptions), 10)
|
|
158
|
+
self.assertTrue(all(isinstance(e, MyError) for e in exceptions))
|
|
159
|
+
self.assertEqual(len(self.cache), 0)
|
|
160
|
+
|
|
161
|
+
good_val = self.cache.get("bad_key", lambda: "success")
|
|
162
|
+
self.assertEqual(good_val, "success")
|
|
163
|
+
|
|
164
|
+
def test_reentrant_call_raises_recursion_error(self):
|
|
165
|
+
def reentrant_generator():
|
|
166
|
+
return self.cache.get("key", lambda: "inner")
|
|
167
|
+
|
|
168
|
+
with self.assertRaises(RecursionError):
|
|
169
|
+
self.cache.get("key", reentrant_generator)
|
|
170
|
+
|
|
171
|
+
def test_remove_during_inflight_computation_prevents_stale_value(self):
|
|
172
|
+
computation_started = Event()
|
|
173
|
+
release_computation = Event()
|
|
174
|
+
|
|
175
|
+
def generator():
|
|
176
|
+
computation_started.set()
|
|
177
|
+
release_computation.wait(timeout=5)
|
|
178
|
+
return "stale-value"
|
|
179
|
+
|
|
180
|
+
results = []
|
|
181
|
+
computing_thread = Thread(
|
|
182
|
+
target=lambda: results.append(self.cache.get("key", generator))
|
|
183
|
+
)
|
|
184
|
+
computing_thread.start()
|
|
185
|
+
self.assertTrue(computation_started.wait(timeout=5))
|
|
186
|
+
|
|
187
|
+
self.cache.remove("key")
|
|
188
|
+
release_computation.set()
|
|
189
|
+
computing_thread.join(timeout=5)
|
|
190
|
+
|
|
191
|
+
self.assertEqual(results, ["stale-value"])
|
|
192
|
+
self.assertIsNone(self.cache.get("key"))
|
|
193
|
+
self.assertEqual(len(self.cache), 0)
|
|
194
|
+
|
|
195
|
+
def test_set_during_inflight_prevents_stale_overwrite(self):
|
|
196
|
+
computation_started = Event()
|
|
197
|
+
release_computation = Event()
|
|
198
|
+
|
|
199
|
+
def slow_generator():
|
|
200
|
+
computation_started.set()
|
|
201
|
+
release_computation.wait(timeout=5)
|
|
202
|
+
return "stale-generated-value"
|
|
203
|
+
|
|
204
|
+
computing_thread = Thread(
|
|
205
|
+
target=lambda: self.cache.get("key", slow_generator)
|
|
206
|
+
)
|
|
207
|
+
computing_thread.start()
|
|
208
|
+
self.assertTrue(computation_started.wait(timeout=5))
|
|
209
|
+
|
|
210
|
+
self.cache.set("key", "fresh-explicit-value")
|
|
211
|
+
release_computation.set()
|
|
212
|
+
computing_thread.join(timeout=5)
|
|
213
|
+
|
|
214
|
+
self.assertEqual(self.cache.get("key"), "fresh-explicit-value")
|
|
215
|
+
|
|
216
|
+
def test_does_not_cache_none_result(self):
|
|
217
|
+
generator = Mock(return_value=None)
|
|
218
|
+
result = self.cache.get("key", generator)
|
|
219
|
+
|
|
220
|
+
self.assertIsNone(result)
|
|
221
|
+
self.assertEqual(len(self.cache), 0)
|
|
222
|
+
self.assertIsNone(self.cache.get("key"))
|