Skip to content

Commit b60b3fd

Browse files
committed
chore: Replace the expiringdict dependency with an internal cache
1 parent d5eeb80 commit b60b3fd

7 files changed

Lines changed: 390 additions & 12 deletions

File tree

‎ldclient/feature_store_helpers.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,8 @@
44

55
from typing import Any, Dict, Mapping
66

7-
from expiringdict import ExpiringDict
8-
97
from ldclient.feature_store import CacheConfig
8+
from ldclient.impl.expiring_cache import ExpiringCache
109
from ldclient.impl.util import log
1110
from ldclient.interfaces import (
1211
DiagnosticDescription,
@@ -66,7 +65,7 @@ def __init__(self, cache_config: CacheConfig):
6665
:param cache_config: the caching parameters
6766
"""
6867
if cache_config.enabled:
69-
self._cache = ExpiringDict(max_len=cache_config.capacity, max_age_seconds=cache_config.expiration)
68+
self._cache = ExpiringCache(max_len=cache_config.capacity, max_age_seconds=cache_config.expiration)
7069
else:
7170
self._cache = _NOOP_CACHE
7271
self._inited = False

‎ldclient/impl/async_big_segments.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import asyncio
22
from typing import Awaitable, Callable, Optional, Tuple
33

4-
from expiringdict import ExpiringDict
5-
64
from ldclient.async_config import AsyncBigSegmentsConfig
75
from ldclient.evaluation import BigSegmentsStatus
86
from ldclient.impl.aio.concurrency import AsyncRepeatingTask
@@ -11,6 +9,7 @@
119
_hash_for_user_key,
1210
is_stale
1311
)
12+
from ldclient.impl.expiring_cache import ExpiringCache
1413
from ldclient.impl.listeners import Listeners
1514
from ldclient.impl.util import log
1615
from ldclient.interfaces import (
@@ -66,7 +65,7 @@ def __init__(self, config: AsyncBigSegmentsConfig):
6665
self.__poll_task = None # type: Optional[AsyncRepeatingTask]
6766

6867
if self.__store:
69-
self.__cache = ExpiringDict(max_len=config.context_cache_size, max_age_seconds=config.context_cache_time)
68+
self.__cache = ExpiringCache(max_len=config.context_cache_size, max_age_seconds=config.context_cache_time)
7069
self.__poll_task = AsyncRepeatingTask.at_interval("ldclient.bigsegment.status-poll", config.status_poll_interval, 0, self.poll_store_and_update_status)
7170

7271
def start(self):

‎ldclient/impl/big_segments.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
from threading import Lock
22
from typing import Callable, Optional, Tuple
33

4-
from expiringdict import ExpiringDict
5-
64
from ldclient.config import BigSegmentsConfig
75
from ldclient.evaluation import BigSegmentsStatus
86
from ldclient.impl.big_segments_common import (
97
EMPTY_MEMBERSHIP,
108
_hash_for_user_key,
119
is_stale
1210
)
11+
from ldclient.impl.expiring_cache import ExpiringCache
1312
from ldclient.impl.listeners import Listeners
1413
from ldclient.impl.repeating_task import RepeatingTask
1514
from ldclient.impl.util import log
@@ -68,7 +67,7 @@ def __init__(self, config: BigSegmentsConfig):
6867
self.__poll_task = None # type: Optional[RepeatingTask]
6968

7069
if self.__store:
71-
self.__cache = ExpiringDict(max_len=config.context_cache_size, max_age_seconds=config.context_cache_time)
70+
self.__cache = ExpiringCache(max_len=config.context_cache_size, max_age_seconds=config.context_cache_time)
7271
self.__poll_task = RepeatingTask.at_interval("ldclient.bigsegment.status-poll", config.status_poll_interval, 0, self.poll_store_and_update_status)
7372
self.__poll_task.start()
7473

‎ldclient/impl/expiring_cache.py‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import time
2+
from collections import OrderedDict
3+
from threading import Lock
4+
from typing import Any, Callable, Hashable, Optional, Tuple
5+
6+
7+
class ExpiringCache:
8+
"""A thread-safe cache with a maximum size and a maximum entry age.
9+
10+
An entry expires ``max_age_seconds`` after it was last written. When the cache is full, a new
11+
key evicts the entry that was written first. Reads do not change the eviction order.
12+
"""
13+
14+
def __init__(self, max_len: int, max_age_seconds: float, clock: Callable[[], float] = time.monotonic):
15+
"""
16+
:param max_len: the maximum number of entries; must be at least 1
17+
:param max_age_seconds: the time after a write at which an entry expires
18+
:param clock: returns the current time in seconds
19+
"""
20+
if max_len < 1:
21+
raise ValueError("max_len must be at least 1")
22+
self._max_len = max_len
23+
self._max_age = max_age_seconds
24+
self._clock = clock
25+
self._data: 'OrderedDict[Hashable, Tuple[Any, float]]' = OrderedDict()
26+
self._lock = Lock()
27+
28+
def get(self, key: Hashable, default: Optional[Any] = None) -> Any:
29+
"""Returns the value for the key, or ``default`` if the key is missing or expired."""
30+
with self._lock:
31+
entry = self._data.get(key)
32+
if entry is None:
33+
return default
34+
value, written_at = entry
35+
if self._clock() - written_at >= self._max_age:
36+
del self._data[key]
37+
return default
38+
return value
39+
40+
def __setitem__(self, key: Hashable, value: Any) -> None:
41+
with self._lock:
42+
if key in self._data:
43+
del self._data[key]
44+
elif len(self._data) >= self._max_len:
45+
self._data.popitem(last=False)
46+
self._data[key] = (value, self._clock())
47+
48+
def pop(self, key: Hashable, default: Optional[Any] = None) -> Any:
49+
"""Removes the key and returns its value, or ``default`` if the key is missing or expired."""
50+
with self._lock:
51+
entry = self._data.pop(key, None)
52+
if entry is None:
53+
return default
54+
value, written_at = entry
55+
if self._clock() - written_at >= self._max_age:
56+
return default
57+
return value
58+
59+
def clear(self) -> None:
60+
with self._lock:
61+
self._data.clear()
62+
63+
def __len__(self) -> int:
64+
"""Returns the number of stored entries, including expired entries not yet removed."""
65+
with self._lock:
66+
return len(self._data)

‎ldclient/testing/impl/datasystem/test_cache_lifecycle.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ def test_init_after_disable_skips_decode_loop(self):
228228
assert wrapper._inited is True
229229

230230
def test_disable_cache_drops_entries_from_old_cache(self):
231-
"""The old ExpiringDict must be empty after disable so its entries get GC'd."""
231+
"""The old cache must be empty after disable so its entries get GC'd."""
232232
core = RecordingCore()
233233
core.data = {FEATURES: {"flag-1": _flag("flag-1")}}
234234
wrapper = CachingStoreWrapper(core, CacheConfig.default())

0 commit comments

Comments
 (0)