2016-01-07 05:26:29 +01:00
|
|
|
# Copyright 2015, 2016 OpenMarket Ltd
|
2015-02-11 15:52:23 +01:00
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
2021-07-05 17:32:12 +02:00
|
|
|
import logging
|
2022-05-13 21:32:39 +02:00
|
|
|
import math
|
2015-04-15 17:07:59 +02:00
|
|
|
import threading
|
2021-07-05 17:32:12 +02:00
|
|
|
import weakref
|
2021-11-30 16:39:07 +01:00
|
|
|
from enum import Enum
|
2018-07-09 08:09:20 +02:00
|
|
|
from functools import wraps
|
2020-10-16 16:56:39 +02:00
|
|
|
from typing import (
|
2021-07-05 17:32:12 +02:00
|
|
|
TYPE_CHECKING,
|
2020-10-16 16:56:39 +02:00
|
|
|
Any,
|
|
|
|
Callable,
|
2021-04-28 12:59:28 +02:00
|
|
|
Collection,
|
2021-11-30 16:39:07 +01:00
|
|
|
Dict,
|
2020-10-16 16:56:39 +02:00
|
|
|
Generic,
|
2021-04-28 12:59:28 +02:00
|
|
|
List,
|
2020-10-16 16:56:39 +02:00
|
|
|
Optional,
|
|
|
|
Type,
|
|
|
|
TypeVar,
|
|
|
|
Union,
|
|
|
|
cast,
|
|
|
|
overload,
|
|
|
|
)
|
|
|
|
|
|
|
|
from typing_extensions import Literal
|
2015-04-15 17:07:59 +02:00
|
|
|
|
2021-07-05 17:32:12 +02:00
|
|
|
from twisted.internet import reactor
|
2021-09-10 18:03:18 +02:00
|
|
|
from twisted.internet.interfaces import IReactorTime
|
2021-07-05 17:32:12 +02:00
|
|
|
|
2020-05-11 19:45:23 +02:00
|
|
|
from synapse.config import cache as cache_config
|
2021-07-05 17:32:12 +02:00
|
|
|
from synapse.metrics.background_process_metrics import wrap_as_background_process
|
2022-05-13 21:32:39 +02:00
|
|
|
from synapse.metrics.jemalloc import get_jemalloc_stats
|
2021-07-05 17:32:12 +02:00
|
|
|
from synapse.util import Clock, caches
|
2021-09-22 11:59:52 +02:00
|
|
|
from synapse.util.caches import CacheMetric, EvictionReason, register_cache
|
2021-05-24 15:02:01 +02:00
|
|
|
from synapse.util.caches.treecache import TreeCache, iterate_tree_cache_entry
|
2021-07-05 17:32:12 +02:00
|
|
|
from synapse.util.linked_list import ListNode
|
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
from synapse.server import HomeServer
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
2016-01-22 14:40:37 +01:00
|
|
|
|
2021-05-05 17:54:36 +02:00
|
|
|
try:
|
|
|
|
from pympler.asizeof import Asizer
|
|
|
|
|
2021-10-06 12:20:49 +02:00
|
|
|
def _get_size_of(val: Any, *, recurse: bool = True) -> int:
|
2021-05-05 17:54:36 +02:00
|
|
|
"""Get an estimate of the size in bytes of the object.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
val: The object to size.
|
|
|
|
recurse: If true will include referenced values in the size,
|
|
|
|
otherwise only sizes the given object.
|
|
|
|
"""
|
|
|
|
# Ignore singleton values when calculating memory usage.
|
|
|
|
if val in ((), None, ""):
|
|
|
|
return 0
|
|
|
|
|
|
|
|
sizer = Asizer()
|
|
|
|
sizer.exclude_refs((), None, "")
|
|
|
|
return sizer.asizeof(val, limit=100 if recurse else 0)
|
|
|
|
|
|
|
|
except ImportError:
|
|
|
|
|
2021-10-06 12:20:49 +02:00
|
|
|
def _get_size_of(val: Any, *, recurse: bool = True) -> int:
|
2021-05-05 17:54:36 +02:00
|
|
|
return 0
|
|
|
|
|
|
|
|
|
2020-10-16 17:21:43 +02:00
|
|
|
# Function type: the type used for invalidation callbacks
|
2020-10-16 16:56:39 +02:00
|
|
|
FT = TypeVar("FT", bound=Callable[..., Any])
|
2020-10-16 17:21:43 +02:00
|
|
|
|
|
|
|
# Key and Value type for the cache
|
2020-10-16 16:56:39 +02:00
|
|
|
KT = TypeVar("KT")
|
|
|
|
VT = TypeVar("VT")
|
|
|
|
|
2020-10-16 17:21:43 +02:00
|
|
|
# a general type var, distinct from either KT or VT
|
|
|
|
T = TypeVar("T")
|
|
|
|
|
2021-07-05 17:32:12 +02:00
|
|
|
P = TypeVar("P")
|
|
|
|
|
|
|
|
|
|
|
|
class _TimedListNode(ListNode[P]):
|
|
|
|
"""A `ListNode` that tracks last access time."""
|
|
|
|
|
|
|
|
__slots__ = ["last_access_ts_secs"]
|
|
|
|
|
2021-10-06 12:20:49 +02:00
|
|
|
def update_last_access(self, clock: Clock) -> None:
|
2021-07-05 17:32:12 +02:00
|
|
|
self.last_access_ts_secs = int(clock.time())
|
|
|
|
|
|
|
|
|
|
|
|
# Whether to insert new cache entries to the global list. We only add to it if
|
|
|
|
# time based eviction is enabled.
|
|
|
|
USE_GLOBAL_LIST = False
|
|
|
|
|
|
|
|
# A linked list of all cache entries, allowing efficient time based eviction.
|
|
|
|
GLOBAL_ROOT = ListNode["_Node"].create_root_node()
|
|
|
|
|
|
|
|
|
|
|
|
@wrap_as_background_process("LruCache._expire_old_entries")
|
2022-05-13 21:32:39 +02:00
|
|
|
async def _expire_old_entries(
|
2022-07-05 16:13:47 +02:00
|
|
|
clock: Clock, expiry_seconds: float, autotune_config: Optional[dict]
|
2022-05-13 21:32:39 +02:00
|
|
|
) -> None:
|
2021-07-05 17:32:12 +02:00
|
|
|
"""Walks the global cache list to find cache entries that haven't been
|
2022-05-13 21:32:39 +02:00
|
|
|
accessed in the given number of seconds, or if a given memory threshold has been breached.
|
2021-07-05 17:32:12 +02:00
|
|
|
"""
|
2022-05-13 21:32:39 +02:00
|
|
|
if autotune_config:
|
|
|
|
max_cache_memory_usage = autotune_config["max_cache_memory_usage"]
|
|
|
|
target_cache_memory_usage = autotune_config["target_cache_memory_usage"]
|
|
|
|
min_cache_ttl = autotune_config["min_cache_ttl"] / 1000
|
2021-07-05 17:32:12 +02:00
|
|
|
|
|
|
|
now = int(clock.time())
|
|
|
|
node = GLOBAL_ROOT.prev_node
|
|
|
|
assert node is not None
|
|
|
|
|
|
|
|
i = 0
|
|
|
|
|
|
|
|
logger.debug("Searching for stale caches")
|
|
|
|
|
2022-05-13 21:32:39 +02:00
|
|
|
evicting_due_to_memory = False
|
|
|
|
|
|
|
|
# determine if we're evicting due to memory
|
|
|
|
jemalloc_interface = get_jemalloc_stats()
|
|
|
|
if jemalloc_interface and autotune_config:
|
|
|
|
try:
|
|
|
|
jemalloc_interface.refresh_stats()
|
|
|
|
mem_usage = jemalloc_interface.get_stat("allocated")
|
|
|
|
if mem_usage > max_cache_memory_usage:
|
|
|
|
logger.info("Begin memory-based cache eviction.")
|
|
|
|
evicting_due_to_memory = True
|
|
|
|
except Exception:
|
|
|
|
logger.warning(
|
|
|
|
"Unable to read allocated memory, skipping memory-based cache eviction."
|
|
|
|
)
|
|
|
|
|
2021-07-05 17:32:12 +02:00
|
|
|
while node is not GLOBAL_ROOT:
|
|
|
|
# Only the root node isn't a `_TimedListNode`.
|
|
|
|
assert isinstance(node, _TimedListNode)
|
|
|
|
|
2022-05-13 21:32:39 +02:00
|
|
|
# if node has not aged past expiry_seconds and we are not evicting due to memory usage, there's
|
|
|
|
# nothing to do here
|
|
|
|
if (
|
|
|
|
node.last_access_ts_secs > now - expiry_seconds
|
|
|
|
and not evicting_due_to_memory
|
|
|
|
):
|
|
|
|
break
|
|
|
|
|
|
|
|
# if entry is newer than min_cache_entry_ttl then do not evict and don't evict anything newer
|
|
|
|
if evicting_due_to_memory and now - node.last_access_ts_secs < min_cache_ttl:
|
2021-07-05 17:32:12 +02:00
|
|
|
break
|
|
|
|
|
|
|
|
cache_entry = node.get_cache_entry()
|
|
|
|
next_node = node.prev_node
|
|
|
|
|
|
|
|
# The node should always have a reference to a cache entry and a valid
|
|
|
|
# `prev_node`, as we only drop them when we remove the node from the
|
|
|
|
# list.
|
|
|
|
assert next_node is not None
|
|
|
|
assert cache_entry is not None
|
|
|
|
cache_entry.drop_from_cache()
|
|
|
|
|
2022-05-13 21:32:39 +02:00
|
|
|
# Check mem allocation periodically if we are evicting a bunch of caches
|
|
|
|
if jemalloc_interface and evicting_due_to_memory and (i + 1) % 100 == 0:
|
|
|
|
try:
|
|
|
|
jemalloc_interface.refresh_stats()
|
|
|
|
mem_usage = jemalloc_interface.get_stat("allocated")
|
|
|
|
if mem_usage < target_cache_memory_usage:
|
|
|
|
evicting_due_to_memory = False
|
|
|
|
logger.info("Stop memory-based cache eviction.")
|
|
|
|
except Exception:
|
|
|
|
logger.warning(
|
|
|
|
"Unable to read allocated memory, this may affect memory-based cache eviction."
|
|
|
|
)
|
|
|
|
# If we've failed to read the current memory usage then we
|
|
|
|
# should stop trying to evict based on memory usage
|
|
|
|
evicting_due_to_memory = False
|
|
|
|
|
2021-07-05 17:32:12 +02:00
|
|
|
# If we do lots of work at once we yield to allow other stuff to happen.
|
|
|
|
if (i + 1) % 10000 == 0:
|
|
|
|
logger.debug("Waiting during drop")
|
2022-05-13 21:32:39 +02:00
|
|
|
if node.last_access_ts_secs > now - expiry_seconds:
|
|
|
|
await clock.sleep(0.5)
|
|
|
|
else:
|
|
|
|
await clock.sleep(0)
|
2021-07-05 17:32:12 +02:00
|
|
|
logger.debug("Waking during drop")
|
|
|
|
|
|
|
|
node = next_node
|
|
|
|
|
|
|
|
# If we've yielded then our current node may have been evicted, so we
|
|
|
|
# need to check that its still valid.
|
|
|
|
if node.prev_node is None:
|
|
|
|
break
|
|
|
|
|
|
|
|
i += 1
|
|
|
|
|
|
|
|
logger.info("Dropped %d items from caches", i)
|
|
|
|
|
|
|
|
|
2021-10-06 12:20:49 +02:00
|
|
|
def setup_expire_lru_cache_entries(hs: "HomeServer") -> None:
|
2021-07-05 17:32:12 +02:00
|
|
|
"""Start a background job that expires all cache entries if they have not
|
2022-05-13 21:32:39 +02:00
|
|
|
been accessed for the given number of seconds, or if a given memory usage threshold has been
|
|
|
|
breached.
|
2021-07-05 17:32:12 +02:00
|
|
|
"""
|
2022-05-13 21:32:39 +02:00
|
|
|
if not hs.config.caches.expiry_time_msec and not hs.config.caches.cache_autotuning:
|
2021-07-05 17:32:12 +02:00
|
|
|
return
|
|
|
|
|
2022-05-13 21:32:39 +02:00
|
|
|
if hs.config.caches.expiry_time_msec:
|
|
|
|
expiry_time = hs.config.caches.expiry_time_msec / 1000
|
|
|
|
logger.info("Expiring LRU caches after %d seconds", expiry_time)
|
|
|
|
else:
|
|
|
|
expiry_time = math.inf
|
2021-07-05 17:32:12 +02:00
|
|
|
|
|
|
|
global USE_GLOBAL_LIST
|
|
|
|
USE_GLOBAL_LIST = True
|
|
|
|
|
|
|
|
clock = hs.get_clock()
|
|
|
|
clock.looping_call(
|
2022-05-13 21:32:39 +02:00
|
|
|
_expire_old_entries,
|
|
|
|
30 * 1000,
|
|
|
|
clock,
|
|
|
|
expiry_time,
|
|
|
|
hs.config.caches.cache_autotuning,
|
2021-07-05 17:32:12 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2021-10-06 12:20:49 +02:00
|
|
|
class _Node(Generic[KT, VT]):
|
2021-07-05 17:32:12 +02:00
|
|
|
__slots__ = [
|
|
|
|
"_list_node",
|
|
|
|
"_global_list_node",
|
|
|
|
"_cache",
|
|
|
|
"key",
|
|
|
|
"value",
|
|
|
|
"callbacks",
|
|
|
|
"memory",
|
|
|
|
]
|
2016-03-22 17:06:21 +01:00
|
|
|
|
2021-04-08 23:38:54 +02:00
|
|
|
def __init__(
|
2021-04-28 12:59:28 +02:00
|
|
|
self,
|
2021-07-05 17:32:12 +02:00
|
|
|
root: "ListNode[_Node]",
|
2021-10-06 12:20:49 +02:00
|
|
|
key: KT,
|
|
|
|
value: VT,
|
2021-11-30 16:39:07 +01:00
|
|
|
cache: "weakref.ReferenceType[LruCache[KT, VT]]",
|
2021-07-05 17:32:12 +02:00
|
|
|
clock: Clock,
|
2021-04-28 12:59:28 +02:00
|
|
|
callbacks: Collection[Callable[[], None]] = (),
|
2021-09-22 15:21:58 +02:00
|
|
|
prune_unread_entries: bool = True,
|
2021-04-08 23:38:54 +02:00
|
|
|
):
|
2021-07-05 17:32:12 +02:00
|
|
|
self._list_node = ListNode.insert_after(self, root)
|
2021-09-22 15:21:58 +02:00
|
|
|
self._global_list_node: Optional[_TimedListNode] = None
|
|
|
|
if USE_GLOBAL_LIST and prune_unread_entries:
|
2021-07-05 17:32:12 +02:00
|
|
|
self._global_list_node = _TimedListNode.insert_after(self, GLOBAL_ROOT)
|
|
|
|
self._global_list_node.update_last_access(clock)
|
|
|
|
|
|
|
|
# We store a weak reference to the cache object so that this _Node can
|
|
|
|
# remove itself from the cache. If the cache is dropped we ensure we
|
|
|
|
# remove our entries in the lists.
|
|
|
|
self._cache = cache
|
|
|
|
|
2016-03-22 17:06:21 +01:00
|
|
|
self.key = key
|
|
|
|
self.value = value
|
2021-04-28 12:59:28 +02:00
|
|
|
|
|
|
|
# Set of callbacks to run when the node gets deleted. We store as a list
|
|
|
|
# rather than a set to keep memory usage down (and since we expect few
|
|
|
|
# entries per node, the performance of checking for duplication in a
|
|
|
|
# list vs using a set is negligible).
|
|
|
|
#
|
|
|
|
# Note that we store this as an optional list to keep the memory
|
|
|
|
# footprint down. Storing `None` is free as its a singleton, while empty
|
|
|
|
# lists are 56 bytes (and empty sets are 216 bytes, if we did the naive
|
|
|
|
# thing and used sets).
|
2021-07-15 18:46:54 +02:00
|
|
|
self.callbacks: Optional[List[Callable[[], None]]] = None
|
2021-04-28 12:59:28 +02:00
|
|
|
|
|
|
|
self.add_callbacks(callbacks)
|
|
|
|
|
2021-05-05 17:54:36 +02:00
|
|
|
self.memory = 0
|
|
|
|
if caches.TRACK_MEMORY_USAGE:
|
|
|
|
self.memory = (
|
|
|
|
_get_size_of(key)
|
|
|
|
+ _get_size_of(value)
|
2021-07-05 17:32:12 +02:00
|
|
|
+ _get_size_of(self._list_node, recurse=False)
|
2021-05-05 17:54:36 +02:00
|
|
|
+ _get_size_of(self.callbacks, recurse=False)
|
|
|
|
+ _get_size_of(self, recurse=False)
|
|
|
|
)
|
|
|
|
self.memory += _get_size_of(self.memory, recurse=False)
|
|
|
|
|
2021-07-05 17:32:12 +02:00
|
|
|
if self._global_list_node:
|
|
|
|
self.memory += _get_size_of(self._global_list_node, recurse=False)
|
|
|
|
self.memory += _get_size_of(self._global_list_node.last_access_ts_secs)
|
|
|
|
|
2021-04-28 12:59:28 +02:00
|
|
|
def add_callbacks(self, callbacks: Collection[Callable[[], None]]) -> None:
|
|
|
|
"""Add to stored list of callbacks, removing duplicates."""
|
|
|
|
|
|
|
|
if not callbacks:
|
|
|
|
return
|
|
|
|
|
|
|
|
if not self.callbacks:
|
|
|
|
self.callbacks = []
|
|
|
|
|
|
|
|
for callback in callbacks:
|
|
|
|
if callback not in self.callbacks:
|
|
|
|
self.callbacks.append(callback)
|
|
|
|
|
|
|
|
def run_and_clear_callbacks(self) -> None:
|
|
|
|
"""Run all callbacks and clear the stored list of callbacks. Used when
|
|
|
|
the node is being deleted.
|
|
|
|
"""
|
|
|
|
|
|
|
|
if not self.callbacks:
|
|
|
|
return
|
|
|
|
|
|
|
|
for callback in self.callbacks:
|
|
|
|
callback()
|
|
|
|
|
|
|
|
self.callbacks = None
|
2016-03-22 17:06:21 +01:00
|
|
|
|
2021-07-05 17:32:12 +02:00
|
|
|
def drop_from_cache(self) -> None:
|
|
|
|
"""Drop this node from the cache.
|
|
|
|
|
|
|
|
Ensures that the entry gets removed from the cache and that we get
|
|
|
|
removed from all lists.
|
|
|
|
"""
|
|
|
|
cache = self._cache()
|
2021-11-30 17:28:02 +01:00
|
|
|
if (
|
|
|
|
cache is None
|
|
|
|
or cache.pop(self.key, _Sentinel.sentinel) is _Sentinel.sentinel
|
|
|
|
):
|
2021-07-05 17:32:12 +02:00
|
|
|
# `cache.pop` should call `drop_from_lists()`, unless this Node had
|
|
|
|
# already been removed from the cache.
|
|
|
|
self.drop_from_lists()
|
|
|
|
|
|
|
|
def drop_from_lists(self) -> None:
|
|
|
|
"""Remove this node from the cache lists."""
|
|
|
|
self._list_node.remove_from_list()
|
|
|
|
|
|
|
|
if self._global_list_node:
|
|
|
|
self._global_list_node.remove_from_list()
|
|
|
|
|
|
|
|
def move_to_front(self, clock: Clock, cache_list_root: ListNode) -> None:
|
|
|
|
"""Moves this node to the front of all the lists its in."""
|
|
|
|
self._list_node.move_after(cache_list_root)
|
|
|
|
if self._global_list_node:
|
|
|
|
self._global_list_node.move_after(GLOBAL_ROOT)
|
|
|
|
self._global_list_node.update_last_access(clock)
|
|
|
|
|
2016-03-22 17:06:21 +01:00
|
|
|
|
2021-11-30 16:39:07 +01:00
|
|
|
class _Sentinel(Enum):
|
|
|
|
# defining a sentinel in this way allows mypy to correctly handle the
|
|
|
|
# type of a dictionary lookup.
|
|
|
|
sentinel = object()
|
|
|
|
|
|
|
|
|
2020-10-16 16:56:39 +02:00
|
|
|
class LruCache(Generic[KT, VT]):
|
2016-01-22 13:21:13 +01:00
|
|
|
"""
|
2020-10-16 16:51:57 +02:00
|
|
|
Least-recently-used cache, supporting prometheus metrics and invalidation callbacks.
|
|
|
|
|
2016-01-22 13:21:13 +01:00
|
|
|
If cache_type=TreeCache, all keys must be tuples.
|
|
|
|
"""
|
2019-06-20 11:32:02 +02:00
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
2020-05-11 19:45:23 +02:00
|
|
|
max_size: int,
|
2020-10-16 16:51:57 +02:00
|
|
|
cache_name: Optional[str] = None,
|
2020-05-11 19:45:23 +02:00
|
|
|
cache_type: Type[Union[dict, TreeCache]] = dict,
|
2021-11-30 16:39:07 +01:00
|
|
|
size_callback: Optional[Callable[[VT], int]] = None,
|
2020-10-16 16:51:57 +02:00
|
|
|
metrics_collection_callback: Optional[Callable[[], None]] = None,
|
2020-05-11 19:45:23 +02:00
|
|
|
apply_cache_factor_from_config: bool = True,
|
2021-07-05 17:32:12 +02:00
|
|
|
clock: Optional[Clock] = None,
|
2021-09-22 15:21:58 +02:00
|
|
|
prune_unread_entries: bool = True,
|
2019-06-20 11:32:02 +02:00
|
|
|
):
|
2018-02-01 18:57:51 +01:00
|
|
|
"""
|
|
|
|
Args:
|
2020-05-11 19:45:23 +02:00
|
|
|
max_size: The maximum amount of entries the cache can hold
|
2018-02-01 18:57:51 +01:00
|
|
|
|
2020-10-16 16:51:57 +02:00
|
|
|
cache_name: The name of this cache, for the prometheus metrics. If unset,
|
|
|
|
no metrics will be reported on this cache.
|
|
|
|
|
2018-02-01 18:57:51 +01:00
|
|
|
cache_type (type):
|
|
|
|
type of underlying cache to be used. Typically one of dict
|
|
|
|
or TreeCache.
|
|
|
|
|
|
|
|
size_callback (func(V) -> int | None):
|
|
|
|
|
2020-10-16 16:51:57 +02:00
|
|
|
metrics_collection_callback:
|
|
|
|
metrics collection callback. This is called early in the metrics
|
|
|
|
collection process, before any of the metrics registered with the
|
|
|
|
prometheus Registry are collected, so can be used to update any dynamic
|
|
|
|
metrics.
|
|
|
|
|
|
|
|
Ignored if cache_name is None.
|
2020-05-11 19:45:23 +02:00
|
|
|
|
|
|
|
apply_cache_factor_from_config (bool): If true, `max_size` will be
|
|
|
|
multiplied by a cache factor derived from the homeserver config
|
2022-02-02 16:11:23 +01:00
|
|
|
|
|
|
|
clock:
|
|
|
|
|
|
|
|
prune_unread_entries: If True, cache entries that haven't been read recently
|
|
|
|
will be evicted from the cache in the background. Set to False to
|
|
|
|
opt-out of this behaviour.
|
2018-02-01 18:57:51 +01:00
|
|
|
"""
|
2021-07-05 17:32:12 +02:00
|
|
|
# Default `clock` to something sensible. Note that we rename it to
|
|
|
|
# `real_clock` so that mypy doesn't think its still `Optional`.
|
|
|
|
if clock is None:
|
2021-09-10 18:03:18 +02:00
|
|
|
real_clock = Clock(cast(IReactorTime, reactor))
|
2021-07-05 17:32:12 +02:00
|
|
|
else:
|
|
|
|
real_clock = clock
|
|
|
|
|
2021-11-30 16:39:07 +01:00
|
|
|
cache: Union[Dict[KT, _Node[KT, VT]], TreeCache] = cache_type()
|
2016-01-29 11:00:45 +01:00
|
|
|
self.cache = cache # Used for introspection.
|
2020-05-27 13:04:37 +02:00
|
|
|
self.apply_cache_factor_from_config = apply_cache_factor_from_config
|
2020-05-11 19:45:23 +02:00
|
|
|
|
|
|
|
# Save the original max size, and apply the default size factor.
|
|
|
|
self._original_max_size = max_size
|
|
|
|
# We previously didn't apply the cache factor here, and as such some caches were
|
|
|
|
# not affected by the global cache factor. Add an option here to disable applying
|
|
|
|
# the cache factor when a cache is created
|
|
|
|
if apply_cache_factor_from_config:
|
|
|
|
self.max_size = int(max_size * cache_config.properties.default_factor_size)
|
|
|
|
else:
|
|
|
|
self.max_size = int(max_size)
|
|
|
|
|
2020-10-19 22:13:50 +02:00
|
|
|
# register_cache might call our "set_cache_factor" callback; there's nothing to
|
|
|
|
# do yet when we get resized.
|
2021-07-15 18:46:54 +02:00
|
|
|
self._on_resize: Optional[Callable[[], None]] = None
|
2020-10-19 22:13:50 +02:00
|
|
|
|
2020-10-16 16:51:57 +02:00
|
|
|
if cache_name is not None:
|
2021-07-15 18:46:54 +02:00
|
|
|
metrics: Optional[CacheMetric] = register_cache(
|
2020-10-16 16:51:57 +02:00
|
|
|
"lru_cache",
|
|
|
|
cache_name,
|
|
|
|
self,
|
|
|
|
collect_callback=metrics_collection_callback,
|
2021-07-15 18:46:54 +02:00
|
|
|
)
|
2020-10-16 16:51:57 +02:00
|
|
|
else:
|
|
|
|
metrics = None
|
|
|
|
|
|
|
|
# this is exposed for access from outside this class
|
|
|
|
self.metrics = metrics
|
|
|
|
|
2021-07-05 17:32:12 +02:00
|
|
|
# We create a single weakref to self here so that we don't need to keep
|
|
|
|
# creating more each time we create a `_Node`.
|
|
|
|
weak_ref_to_self = weakref.ref(self)
|
|
|
|
|
2021-11-30 16:39:07 +01:00
|
|
|
list_root = ListNode[_Node[KT, VT]].create_root_node()
|
2015-02-11 15:52:23 +01:00
|
|
|
|
2015-04-15 17:07:59 +02:00
|
|
|
lock = threading.Lock()
|
|
|
|
|
2021-09-10 18:03:18 +02:00
|
|
|
def evict() -> None:
|
2020-05-11 19:45:23 +02:00
|
|
|
while cache_len() > self.max_size:
|
2021-07-05 17:32:12 +02:00
|
|
|
# Get the last node in the list (i.e. the oldest node).
|
2017-01-13 18:46:17 +01:00
|
|
|
todelete = list_root.prev_node
|
2021-07-05 17:32:12 +02:00
|
|
|
|
|
|
|
# The list root should always have a valid `prev_node` if the
|
|
|
|
# cache is not empty.
|
|
|
|
assert todelete is not None
|
|
|
|
|
|
|
|
# The node should always have a reference to a cache entry, as
|
|
|
|
# we only drop the cache entry when we remove the node from the
|
|
|
|
# list.
|
|
|
|
node = todelete.get_cache_entry()
|
|
|
|
assert node is not None
|
|
|
|
|
|
|
|
evicted_len = delete_node(node)
|
|
|
|
cache.pop(node.key, None)
|
2020-10-16 16:51:57 +02:00
|
|
|
if metrics:
|
2021-09-22 11:59:52 +02:00
|
|
|
metrics.inc_evictions(EvictionReason.size, evicted_len)
|
2017-01-13 18:46:17 +01:00
|
|
|
|
2020-10-16 16:56:39 +02:00
|
|
|
def synchronized(f: FT) -> FT:
|
2015-04-15 17:07:59 +02:00
|
|
|
@wraps(f)
|
2021-10-06 12:20:49 +02:00
|
|
|
def inner(*args: Any, **kwargs: Any) -> Any:
|
2015-04-15 17:07:59 +02:00
|
|
|
with lock:
|
|
|
|
return f(*args, **kwargs)
|
|
|
|
|
2020-10-16 16:56:39 +02:00
|
|
|
return cast(FT, inner)
|
2015-04-15 17:07:59 +02:00
|
|
|
|
2017-01-17 12:18:13 +01:00
|
|
|
cached_cache_len = [0]
|
|
|
|
if size_callback is not None:
|
2019-06-20 11:32:02 +02:00
|
|
|
|
2021-10-06 12:20:49 +02:00
|
|
|
def cache_len() -> int:
|
2017-01-17 12:18:13 +01:00
|
|
|
return cached_cache_len[0]
|
2019-06-20 11:32:02 +02:00
|
|
|
|
2017-01-17 12:18:13 +01:00
|
|
|
else:
|
2019-06-20 11:32:02 +02:00
|
|
|
|
2021-10-06 12:20:49 +02:00
|
|
|
def cache_len() -> int:
|
2017-01-17 12:18:13 +01:00
|
|
|
return len(cache)
|
|
|
|
|
|
|
|
self.len = synchronized(cache_len)
|
|
|
|
|
2021-10-06 12:20:49 +02:00
|
|
|
def add_node(
|
|
|
|
key: KT, value: VT, callbacks: Collection[Callable[[], None]] = ()
|
|
|
|
) -> None:
|
2021-11-30 16:39:07 +01:00
|
|
|
node: _Node[KT, VT] = _Node(
|
2021-09-22 15:21:58 +02:00
|
|
|
list_root,
|
|
|
|
key,
|
|
|
|
value,
|
|
|
|
weak_ref_to_self,
|
|
|
|
real_clock,
|
|
|
|
callbacks,
|
|
|
|
prune_unread_entries,
|
|
|
|
)
|
2015-02-11 15:52:23 +01:00
|
|
|
cache[key] = node
|
|
|
|
|
2017-01-17 12:18:13 +01:00
|
|
|
if size_callback:
|
|
|
|
cached_cache_len[0] += size_callback(node.value)
|
|
|
|
|
2021-05-05 17:54:36 +02:00
|
|
|
if caches.TRACK_MEMORY_USAGE and metrics:
|
|
|
|
metrics.inc_memory_usage(node.memory)
|
|
|
|
|
2021-11-30 16:39:07 +01:00
|
|
|
def move_node_to_front(node: _Node[KT, VT]) -> None:
|
2021-07-05 17:32:12 +02:00
|
|
|
node.move_to_front(real_clock, list_root)
|
|
|
|
|
2021-11-30 16:39:07 +01:00
|
|
|
def delete_node(node: _Node[KT, VT]) -> int:
|
2021-07-05 17:32:12 +02:00
|
|
|
node.drop_from_lists()
|
2015-02-11 15:52:23 +01:00
|
|
|
|
2018-02-01 18:57:51 +01:00
|
|
|
deleted_len = 1
|
2017-01-17 12:18:13 +01:00
|
|
|
if size_callback:
|
2018-02-01 18:57:51 +01:00
|
|
|
deleted_len = size_callback(node.value)
|
|
|
|
cached_cache_len[0] -= deleted_len
|
2017-01-17 12:18:13 +01:00
|
|
|
|
2021-04-28 12:59:28 +02:00
|
|
|
node.run_and_clear_callbacks()
|
|
|
|
|
2021-05-05 17:54:36 +02:00
|
|
|
if caches.TRACK_MEMORY_USAGE and metrics:
|
|
|
|
metrics.dec_memory_usage(node.memory)
|
|
|
|
|
2018-02-01 18:57:51 +01:00
|
|
|
return deleted_len
|
2016-08-19 12:18:26 +02:00
|
|
|
|
2020-10-16 16:56:39 +02:00
|
|
|
@overload
|
|
|
|
def cache_get(
|
|
|
|
key: KT,
|
|
|
|
default: Literal[None] = None,
|
2021-04-28 12:59:28 +02:00
|
|
|
callbacks: Collection[Callable[[], None]] = ...,
|
2020-10-16 16:56:39 +02:00
|
|
|
update_metrics: bool = ...,
|
|
|
|
) -> Optional[VT]:
|
|
|
|
...
|
|
|
|
|
|
|
|
@overload
|
|
|
|
def cache_get(
|
|
|
|
key: KT,
|
|
|
|
default: T,
|
2021-04-28 12:59:28 +02:00
|
|
|
callbacks: Collection[Callable[[], None]] = ...,
|
2020-10-16 16:56:39 +02:00
|
|
|
update_metrics: bool = ...,
|
|
|
|
) -> Union[T, VT]:
|
|
|
|
...
|
|
|
|
|
2015-04-15 17:07:59 +02:00
|
|
|
@synchronized
|
2020-10-16 16:56:39 +02:00
|
|
|
def cache_get(
|
|
|
|
key: KT,
|
2020-10-16 17:21:43 +02:00
|
|
|
default: Optional[T] = None,
|
2021-04-28 12:59:28 +02:00
|
|
|
callbacks: Collection[Callable[[], None]] = (),
|
2020-10-16 16:56:39 +02:00
|
|
|
update_metrics: bool = True,
|
2021-10-06 12:20:49 +02:00
|
|
|
) -> Union[None, T, VT]:
|
2015-02-11 15:52:23 +01:00
|
|
|
node = cache.get(key, None)
|
|
|
|
if node is not None:
|
|
|
|
move_node_to_front(node)
|
2021-04-28 12:59:28 +02:00
|
|
|
node.add_callbacks(callbacks)
|
2020-10-16 16:51:57 +02:00
|
|
|
if update_metrics and metrics:
|
|
|
|
metrics.inc_hits()
|
2016-03-22 17:06:21 +01:00
|
|
|
return node.value
|
2015-02-11 15:52:23 +01:00
|
|
|
else:
|
2020-10-16 16:51:57 +02:00
|
|
|
if update_metrics and metrics:
|
|
|
|
metrics.inc_misses()
|
2015-02-11 15:52:23 +01:00
|
|
|
return default
|
|
|
|
|
2015-04-15 17:07:59 +02:00
|
|
|
@synchronized
|
2021-10-06 12:20:49 +02:00
|
|
|
def cache_set(
|
2021-11-30 16:39:07 +01:00
|
|
|
key: KT, value: VT, callbacks: Collection[Callable[[], None]] = ()
|
2021-10-06 12:20:49 +02:00
|
|
|
) -> None:
|
2015-02-11 15:52:23 +01:00
|
|
|
node = cache.get(key, None)
|
|
|
|
if node is not None:
|
2018-03-19 12:35:53 +01:00
|
|
|
# We sometimes store large objects, e.g. dicts, which cause
|
|
|
|
# the inequality check to take a long time. So let's only do
|
|
|
|
# the check if we have some callbacks to call.
|
2021-04-28 12:59:28 +02:00
|
|
|
if value != node.value:
|
|
|
|
node.run_and_clear_callbacks()
|
2016-08-19 12:18:26 +02:00
|
|
|
|
2018-03-19 12:35:53 +01:00
|
|
|
# We don't bother to protect this by value != node.value as
|
|
|
|
# generally size_callback will be cheap compared with equality
|
|
|
|
# checks. (For example, taking the size of two dicts is quicker
|
|
|
|
# than comparing them for equality.)
|
2018-03-15 16:40:13 +01:00
|
|
|
if size_callback:
|
|
|
|
cached_cache_len[0] -= size_callback(node.value)
|
|
|
|
cached_cache_len[0] += size_callback(value)
|
2017-01-17 12:18:13 +01:00
|
|
|
|
2021-04-28 12:59:28 +02:00
|
|
|
node.add_callbacks(callbacks)
|
2016-08-19 12:18:26 +02:00
|
|
|
|
2015-02-11 15:52:23 +01:00
|
|
|
move_node_to_front(node)
|
2016-03-22 17:06:21 +01:00
|
|
|
node.value = value
|
2015-02-11 15:52:23 +01:00
|
|
|
else:
|
2017-01-17 12:18:13 +01:00
|
|
|
add_node(key, value, set(callbacks))
|
2017-01-13 18:46:17 +01:00
|
|
|
|
|
|
|
evict()
|
2015-02-11 15:52:23 +01:00
|
|
|
|
2015-04-15 17:07:59 +02:00
|
|
|
@synchronized
|
2020-10-16 16:56:39 +02:00
|
|
|
def cache_set_default(key: KT, value: VT) -> VT:
|
2015-02-11 15:52:23 +01:00
|
|
|
node = cache.get(key, None)
|
|
|
|
if node is not None:
|
2016-03-22 17:06:21 +01:00
|
|
|
return node.value
|
2015-02-11 15:52:23 +01:00
|
|
|
else:
|
|
|
|
add_node(key, value)
|
2017-01-13 18:46:17 +01:00
|
|
|
evict()
|
2015-02-11 15:52:23 +01:00
|
|
|
return value
|
|
|
|
|
2020-10-16 16:56:39 +02:00
|
|
|
@overload
|
2020-10-16 17:14:42 +02:00
|
|
|
def cache_pop(key: KT, default: Literal[None] = None) -> Optional[VT]:
|
2020-10-16 16:56:39 +02:00
|
|
|
...
|
|
|
|
|
|
|
|
@overload
|
|
|
|
def cache_pop(key: KT, default: T) -> Union[T, VT]:
|
|
|
|
...
|
|
|
|
|
2015-04-15 17:07:59 +02:00
|
|
|
@synchronized
|
2021-10-06 12:20:49 +02:00
|
|
|
def cache_pop(key: KT, default: Optional[T] = None) -> Union[None, T, VT]:
|
2015-02-11 15:52:23 +01:00
|
|
|
node = cache.get(key, None)
|
|
|
|
if node:
|
2022-02-15 15:31:04 +01:00
|
|
|
evicted_len = delete_node(node)
|
2016-03-22 17:06:21 +01:00
|
|
|
cache.pop(node.key, None)
|
2022-02-15 15:31:04 +01:00
|
|
|
if metrics:
|
|
|
|
metrics.inc_evictions(EvictionReason.invalidation, evicted_len)
|
2016-03-22 17:06:21 +01:00
|
|
|
return node.value
|
2015-02-11 15:52:23 +01:00
|
|
|
else:
|
|
|
|
return default
|
|
|
|
|
2016-01-21 20:16:25 +01:00
|
|
|
@synchronized
|
2020-10-16 16:56:39 +02:00
|
|
|
def cache_del_multi(key: KT) -> None:
|
2021-05-27 11:33:56 +02:00
|
|
|
"""Delete an entry, or tree of entries
|
|
|
|
|
|
|
|
If the LruCache is backed by a regular dict, then "key" must be of
|
|
|
|
the right type for this cache
|
|
|
|
|
|
|
|
If the LruCache is backed by a TreeCache, then "key" must be a tuple, but
|
|
|
|
may be of lower cardinality than the TreeCache - in which case the whole
|
|
|
|
subtree is deleted.
|
2016-01-22 13:10:33 +01:00
|
|
|
"""
|
2021-05-27 11:33:56 +02:00
|
|
|
popped = cache.pop(key, None)
|
2016-01-21 20:16:25 +01:00
|
|
|
if popped is None:
|
|
|
|
return
|
2021-05-24 15:02:01 +02:00
|
|
|
# for each deleted node, we now need to remove it from the linked list
|
|
|
|
# and run its callbacks.
|
|
|
|
for leaf in iterate_tree_cache_entry(popped):
|
2016-01-21 20:16:25 +01:00
|
|
|
delete_node(leaf)
|
|
|
|
|
2015-05-21 12:13:19 +02:00
|
|
|
@synchronized
|
2020-10-16 16:56:39 +02:00
|
|
|
def cache_clear() -> None:
|
2016-08-19 12:18:26 +02:00
|
|
|
for node in cache.values():
|
2021-04-28 12:59:28 +02:00
|
|
|
node.run_and_clear_callbacks()
|
2021-07-05 17:32:12 +02:00
|
|
|
node.drop_from_lists()
|
|
|
|
|
|
|
|
assert list_root.next_node == list_root
|
|
|
|
assert list_root.prev_node == list_root
|
|
|
|
|
2015-05-21 12:13:19 +02:00
|
|
|
cache.clear()
|
2017-01-18 15:55:23 +01:00
|
|
|
if size_callback:
|
|
|
|
cached_cache_len[0] = 0
|
2015-05-21 12:13:19 +02:00
|
|
|
|
2021-05-05 17:54:36 +02:00
|
|
|
if caches.TRACK_MEMORY_USAGE and metrics:
|
|
|
|
metrics.clear_memory_usage()
|
|
|
|
|
2015-04-15 17:07:59 +02:00
|
|
|
@synchronized
|
2020-10-16 16:56:39 +02:00
|
|
|
def cache_contains(key: KT) -> bool:
|
2015-03-25 20:04:59 +01:00
|
|
|
return key in cache
|
|
|
|
|
2020-10-19 22:13:50 +02:00
|
|
|
# make sure that we clear out any excess entries after we get resized.
|
2020-05-11 19:45:23 +02:00
|
|
|
self._on_resize = evict
|
2020-10-19 22:13:50 +02:00
|
|
|
|
2015-02-11 15:52:23 +01:00
|
|
|
self.get = cache_get
|
|
|
|
self.set = cache_set
|
|
|
|
self.setdefault = cache_set_default
|
|
|
|
self.pop = cache_pop
|
2021-05-27 11:33:56 +02:00
|
|
|
self.del_multi = cache_del_multi
|
2020-10-19 13:20:29 +02:00
|
|
|
# `invalidate` is exposed for consistency with DeferredCache, so that it can be
|
|
|
|
# invalidated by the cache invalidation replication stream.
|
2021-05-27 11:33:56 +02:00
|
|
|
self.invalidate = cache_del_multi
|
2017-01-13 18:46:17 +01:00
|
|
|
self.len = synchronized(cache_len)
|
2015-03-25 20:04:59 +01:00
|
|
|
self.contains = cache_contains
|
2015-05-21 12:13:19 +02:00
|
|
|
self.clear = cache_clear
|
2015-02-11 15:52:23 +01:00
|
|
|
|
2021-10-06 12:20:49 +02:00
|
|
|
def __getitem__(self, key: KT) -> VT:
|
2021-11-30 16:39:07 +01:00
|
|
|
result = self.get(key, _Sentinel.sentinel)
|
|
|
|
if result is _Sentinel.sentinel:
|
2015-02-11 15:52:23 +01:00
|
|
|
raise KeyError()
|
|
|
|
else:
|
2021-11-30 16:39:07 +01:00
|
|
|
return result
|
2015-02-11 15:52:23 +01:00
|
|
|
|
2021-10-06 12:20:49 +02:00
|
|
|
def __setitem__(self, key: KT, value: VT) -> None:
|
2015-02-11 15:52:23 +01:00
|
|
|
self.set(key, value)
|
|
|
|
|
2021-10-06 12:20:49 +02:00
|
|
|
def __delitem__(self, key: KT, value: VT) -> None:
|
2021-11-30 16:39:07 +01:00
|
|
|
result = self.pop(key, _Sentinel.sentinel)
|
|
|
|
if result is _Sentinel.sentinel:
|
2015-02-11 15:52:23 +01:00
|
|
|
raise KeyError()
|
2015-03-04 18:32:28 +01:00
|
|
|
|
2021-10-06 12:20:49 +02:00
|
|
|
def __len__(self) -> int:
|
2015-03-04 18:32:28 +01:00
|
|
|
return self.len()
|
2015-03-25 20:04:59 +01:00
|
|
|
|
2021-10-06 12:20:49 +02:00
|
|
|
def __contains__(self, key: KT) -> bool:
|
2015-03-25 20:04:59 +01:00
|
|
|
return self.contains(key)
|
2020-05-11 19:45:23 +02:00
|
|
|
|
|
|
|
def set_cache_factor(self, factor: float) -> bool:
|
|
|
|
"""
|
|
|
|
Set the cache factor for this individual cache.
|
|
|
|
|
|
|
|
This will trigger a resize if it changes, which may require evicting
|
|
|
|
items from the cache.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
bool: Whether the cache changed size or not.
|
|
|
|
"""
|
2020-05-27 13:04:37 +02:00
|
|
|
if not self.apply_cache_factor_from_config:
|
|
|
|
return False
|
|
|
|
|
2020-05-11 19:45:23 +02:00
|
|
|
new_size = int(self._original_max_size * factor)
|
|
|
|
if new_size != self.max_size:
|
|
|
|
self.max_size = new_size
|
2020-10-19 22:13:50 +02:00
|
|
|
if self._on_resize:
|
|
|
|
self._on_resize()
|
2020-05-11 19:45:23 +02:00
|
|
|
return True
|
|
|
|
return False
|
2021-07-05 17:32:12 +02:00
|
|
|
|
|
|
|
def __del__(self) -> None:
|
|
|
|
# We're about to be deleted, so we make sure to clear up all the nodes
|
|
|
|
# and run callbacks, etc.
|
|
|
|
#
|
|
|
|
# This happens e.g. in the sync code where we have an expiring cache of
|
|
|
|
# lru caches.
|
|
|
|
self.clear()
|
2022-07-15 11:30:46 +02:00
|
|
|
|
|
|
|
|
|
|
|
class AsyncLruCache(Generic[KT, VT]):
|
|
|
|
"""
|
|
|
|
An asynchronous wrapper around a subset of the LruCache API.
|
|
|
|
|
|
|
|
On its own this doesn't change the behaviour but allows subclasses that
|
|
|
|
utilize external cache systems that require await behaviour to be created.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs): # type: ignore
|
|
|
|
self._lru_cache: LruCache[KT, VT] = LruCache(*args, **kwargs)
|
|
|
|
|
|
|
|
async def get(
|
|
|
|
self, key: KT, default: Optional[T] = None, update_metrics: bool = True
|
|
|
|
) -> Optional[VT]:
|
|
|
|
return self._lru_cache.get(key, update_metrics=update_metrics)
|
|
|
|
|
|
|
|
async def set(self, key: KT, value: VT) -> None:
|
|
|
|
self._lru_cache.set(key, value)
|
|
|
|
|
|
|
|
async def invalidate(self, key: KT) -> None:
|
|
|
|
# This method should invalidate any external cache and then invalidate the LruCache.
|
|
|
|
return self._lru_cache.invalidate(key)
|
|
|
|
|
|
|
|
def invalidate_local(self, key: KT) -> None:
|
|
|
|
"""Remove an entry from the local cache
|
|
|
|
|
|
|
|
This variant of `invalidate` is useful if we know that the external
|
|
|
|
cache has already been invalidated.
|
|
|
|
"""
|
|
|
|
return self._lru_cache.invalidate(key)
|
|
|
|
|
|
|
|
async def contains(self, key: KT) -> bool:
|
|
|
|
return self._lru_cache.contains(key)
|
|
|
|
|
|
|
|
async def clear(self) -> None:
|
|
|
|
self._lru_cache.clear()
|