|
| 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) |
0 commit comments