lrucache.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. import math
  16. import threading
  17. import weakref
  18. from enum import Enum
  19. from functools import wraps
  20. from typing import (
  21. TYPE_CHECKING,
  22. Any,
  23. Callable,
  24. Collection,
  25. Dict,
  26. Generic,
  27. Iterable,
  28. List,
  29. Optional,
  30. Tuple,
  31. Type,
  32. TypeVar,
  33. Union,
  34. cast,
  35. overload,
  36. )
  37. from typing_extensions import Literal
  38. from twisted.internet import reactor
  39. from twisted.internet.interfaces import IReactorTime
  40. from synapse.config import cache as cache_config
  41. from synapse.metrics.background_process_metrics import wrap_as_background_process
  42. from synapse.metrics.jemalloc import get_jemalloc_stats
  43. from synapse.util import Clock, caches
  44. from synapse.util.caches import CacheMetric, EvictionReason, register_cache
  45. from synapse.util.caches.treecache import (
  46. TreeCache,
  47. iterate_tree_cache_entry,
  48. iterate_tree_cache_items,
  49. )
  50. from synapse.util.linked_list import ListNode
  51. if TYPE_CHECKING:
  52. from synapse.server import HomeServer
  53. logger = logging.getLogger(__name__)
  54. try:
  55. from pympler.asizeof import Asizer
  56. def _get_size_of(val: Any, *, recurse: bool = True) -> int:
  57. """Get an estimate of the size in bytes of the object.
  58. Args:
  59. val: The object to size.
  60. recurse: If true will include referenced values in the size,
  61. otherwise only sizes the given object.
  62. """
  63. # Ignore singleton values when calculating memory usage.
  64. if val in ((), None, ""):
  65. return 0
  66. sizer = Asizer()
  67. sizer.exclude_refs((), None, "")
  68. return sizer.asizeof(val, limit=100 if recurse else 0)
  69. except ImportError:
  70. def _get_size_of(val: Any, *, recurse: bool = True) -> int:
  71. return 0
  72. # Function type: the type used for invalidation callbacks
  73. FT = TypeVar("FT", bound=Callable[..., Any])
  74. # Key and Value type for the cache
  75. KT = TypeVar("KT")
  76. VT = TypeVar("VT")
  77. # a general type var, distinct from either KT or VT
  78. T = TypeVar("T")
  79. P = TypeVar("P")
  80. class _TimedListNode(ListNode[P]):
  81. """A `ListNode` that tracks last access time."""
  82. __slots__ = ["last_access_ts_secs"]
  83. def update_last_access(self, clock: Clock) -> None:
  84. self.last_access_ts_secs = int(clock.time())
  85. # Whether to insert new cache entries to the global list. We only add to it if
  86. # time based eviction is enabled.
  87. USE_GLOBAL_LIST = False
  88. # A linked list of all cache entries, allowing efficient time based eviction.
  89. GLOBAL_ROOT = ListNode["_Node"].create_root_node()
  90. @wrap_as_background_process("LruCache._expire_old_entries")
  91. async def _expire_old_entries(
  92. clock: Clock, expiry_seconds: float, autotune_config: Optional[dict]
  93. ) -> None:
  94. """Walks the global cache list to find cache entries that haven't been
  95. accessed in the given number of seconds, or if a given memory threshold has been breached.
  96. """
  97. if autotune_config:
  98. max_cache_memory_usage = autotune_config["max_cache_memory_usage"]
  99. target_cache_memory_usage = autotune_config["target_cache_memory_usage"]
  100. min_cache_ttl = autotune_config["min_cache_ttl"] / 1000
  101. now = int(clock.time())
  102. node = GLOBAL_ROOT.prev_node
  103. assert node is not None
  104. i = 0
  105. logger.debug("Searching for stale caches")
  106. evicting_due_to_memory = False
  107. # determine if we're evicting due to memory
  108. jemalloc_interface = get_jemalloc_stats()
  109. if jemalloc_interface and autotune_config:
  110. try:
  111. jemalloc_interface.refresh_stats()
  112. mem_usage = jemalloc_interface.get_stat("allocated")
  113. if mem_usage > max_cache_memory_usage:
  114. logger.info("Begin memory-based cache eviction.")
  115. evicting_due_to_memory = True
  116. except Exception:
  117. logger.warning(
  118. "Unable to read allocated memory, skipping memory-based cache eviction."
  119. )
  120. while node is not GLOBAL_ROOT:
  121. # Only the root node isn't a `_TimedListNode`.
  122. assert isinstance(node, _TimedListNode)
  123. # if node has not aged past expiry_seconds and we are not evicting due to memory usage, there's
  124. # nothing to do here
  125. if (
  126. node.last_access_ts_secs > now - expiry_seconds
  127. and not evicting_due_to_memory
  128. ):
  129. break
  130. # if entry is newer than min_cache_entry_ttl then do not evict and don't evict anything newer
  131. if evicting_due_to_memory and now - node.last_access_ts_secs < min_cache_ttl:
  132. break
  133. cache_entry = node.get_cache_entry()
  134. next_node = node.prev_node
  135. # The node should always have a reference to a cache entry and a valid
  136. # `prev_node`, as we only drop them when we remove the node from the
  137. # list.
  138. assert next_node is not None
  139. assert cache_entry is not None
  140. cache_entry.drop_from_cache()
  141. # Check mem allocation periodically if we are evicting a bunch of caches
  142. if jemalloc_interface and evicting_due_to_memory and (i + 1) % 100 == 0:
  143. try:
  144. jemalloc_interface.refresh_stats()
  145. mem_usage = jemalloc_interface.get_stat("allocated")
  146. if mem_usage < target_cache_memory_usage:
  147. evicting_due_to_memory = False
  148. logger.info("Stop memory-based cache eviction.")
  149. except Exception:
  150. logger.warning(
  151. "Unable to read allocated memory, this may affect memory-based cache eviction."
  152. )
  153. # If we've failed to read the current memory usage then we
  154. # should stop trying to evict based on memory usage
  155. evicting_due_to_memory = False
  156. # If we do lots of work at once we yield to allow other stuff to happen.
  157. if (i + 1) % 10000 == 0:
  158. logger.debug("Waiting during drop")
  159. if node.last_access_ts_secs > now - expiry_seconds:
  160. await clock.sleep(0.5)
  161. else:
  162. await clock.sleep(0)
  163. logger.debug("Waking during drop")
  164. node = next_node
  165. # If we've yielded then our current node may have been evicted, so we
  166. # need to check that its still valid.
  167. if node.prev_node is None:
  168. break
  169. i += 1
  170. logger.info("Dropped %d items from caches", i)
  171. def setup_expire_lru_cache_entries(hs: "HomeServer") -> None:
  172. """Start a background job that expires all cache entries if they have not
  173. been accessed for the given number of seconds, or if a given memory usage threshold has been
  174. breached.
  175. """
  176. if not hs.config.caches.expiry_time_msec and not hs.config.caches.cache_autotuning:
  177. return
  178. if hs.config.caches.expiry_time_msec:
  179. expiry_time = hs.config.caches.expiry_time_msec / 1000
  180. logger.info("Expiring LRU caches after %d seconds", expiry_time)
  181. else:
  182. expiry_time = math.inf
  183. global USE_GLOBAL_LIST
  184. USE_GLOBAL_LIST = True
  185. clock = hs.get_clock()
  186. clock.looping_call(
  187. _expire_old_entries,
  188. 30 * 1000,
  189. clock,
  190. expiry_time,
  191. hs.config.caches.cache_autotuning,
  192. )
  193. class _Node(Generic[KT, VT]):
  194. __slots__ = [
  195. "_list_node",
  196. "_global_list_node",
  197. "_cache",
  198. "key",
  199. "value",
  200. "callbacks",
  201. "memory",
  202. ]
  203. def __init__(
  204. self,
  205. root: "ListNode[_Node]",
  206. key: KT,
  207. value: VT,
  208. cache: "weakref.ReferenceType[LruCache[KT, VT]]",
  209. clock: Clock,
  210. callbacks: Collection[Callable[[], None]] = (),
  211. prune_unread_entries: bool = True,
  212. ):
  213. self._list_node = ListNode.insert_after(self, root)
  214. self._global_list_node: Optional[_TimedListNode] = None
  215. if USE_GLOBAL_LIST and prune_unread_entries:
  216. self._global_list_node = _TimedListNode.insert_after(self, GLOBAL_ROOT)
  217. self._global_list_node.update_last_access(clock)
  218. # We store a weak reference to the cache object so that this _Node can
  219. # remove itself from the cache. If the cache is dropped we ensure we
  220. # remove our entries in the lists.
  221. self._cache = cache
  222. self.key = key
  223. self.value = value
  224. # Set of callbacks to run when the node gets deleted. We store as a list
  225. # rather than a set to keep memory usage down (and since we expect few
  226. # entries per node, the performance of checking for duplication in a
  227. # list vs using a set is negligible).
  228. #
  229. # Note that we store this as an optional list to keep the memory
  230. # footprint down. Storing `None` is free as its a singleton, while empty
  231. # lists are 56 bytes (and empty sets are 216 bytes, if we did the naive
  232. # thing and used sets).
  233. self.callbacks: Optional[List[Callable[[], None]]] = None
  234. self.add_callbacks(callbacks)
  235. self.memory = 0
  236. if caches.TRACK_MEMORY_USAGE:
  237. self.memory = (
  238. _get_size_of(key)
  239. + _get_size_of(value)
  240. + _get_size_of(self._list_node, recurse=False)
  241. + _get_size_of(self.callbacks, recurse=False)
  242. + _get_size_of(self, recurse=False)
  243. )
  244. self.memory += _get_size_of(self.memory, recurse=False)
  245. if self._global_list_node:
  246. self.memory += _get_size_of(self._global_list_node, recurse=False)
  247. self.memory += _get_size_of(self._global_list_node.last_access_ts_secs)
  248. def add_callbacks(self, callbacks: Collection[Callable[[], None]]) -> None:
  249. """Add to stored list of callbacks, removing duplicates."""
  250. if not callbacks:
  251. return
  252. if not self.callbacks:
  253. self.callbacks = []
  254. for callback in callbacks:
  255. if callback not in self.callbacks:
  256. self.callbacks.append(callback)
  257. def run_and_clear_callbacks(self) -> None:
  258. """Run all callbacks and clear the stored list of callbacks. Used when
  259. the node is being deleted.
  260. """
  261. if not self.callbacks:
  262. return
  263. for callback in self.callbacks:
  264. callback()
  265. self.callbacks = None
  266. def drop_from_cache(self) -> None:
  267. """Drop this node from the cache.
  268. Ensures that the entry gets removed from the cache and that we get
  269. removed from all lists.
  270. """
  271. cache = self._cache()
  272. if (
  273. cache is None
  274. or cache.pop(self.key, _Sentinel.sentinel) is _Sentinel.sentinel
  275. ):
  276. # `cache.pop` should call `drop_from_lists()`, unless this Node had
  277. # already been removed from the cache.
  278. self.drop_from_lists()
  279. def drop_from_lists(self) -> None:
  280. """Remove this node from the cache lists."""
  281. self._list_node.remove_from_list()
  282. if self._global_list_node:
  283. self._global_list_node.remove_from_list()
  284. def move_to_front(self, clock: Clock, cache_list_root: ListNode) -> None:
  285. """Moves this node to the front of all the lists its in."""
  286. self._list_node.move_after(cache_list_root)
  287. if self._global_list_node:
  288. self._global_list_node.move_after(GLOBAL_ROOT)
  289. self._global_list_node.update_last_access(clock)
  290. class _Sentinel(Enum):
  291. # defining a sentinel in this way allows mypy to correctly handle the
  292. # type of a dictionary lookup.
  293. sentinel = object()
  294. class LruCache(Generic[KT, VT]):
  295. """
  296. Least-recently-used cache, supporting prometheus metrics and invalidation callbacks.
  297. If cache_type=TreeCache, all keys must be tuples.
  298. """
  299. def __init__(
  300. self,
  301. max_size: int,
  302. cache_name: Optional[str] = None,
  303. cache_type: Type[Union[dict, TreeCache]] = dict,
  304. size_callback: Optional[Callable[[VT], int]] = None,
  305. metrics_collection_callback: Optional[Callable[[], None]] = None,
  306. apply_cache_factor_from_config: bool = True,
  307. clock: Optional[Clock] = None,
  308. prune_unread_entries: bool = True,
  309. ):
  310. """
  311. Args:
  312. max_size: The maximum amount of entries the cache can hold
  313. cache_name: The name of this cache, for the prometheus metrics. If unset,
  314. no metrics will be reported on this cache.
  315. cache_type:
  316. type of underlying cache to be used. Typically one of dict
  317. or TreeCache.
  318. size_callback:
  319. metrics_collection_callback:
  320. metrics collection callback. This is called early in the metrics
  321. collection process, before any of the metrics registered with the
  322. prometheus Registry are collected, so can be used to update any dynamic
  323. metrics.
  324. Ignored if cache_name is None.
  325. apply_cache_factor_from_config: If true, `max_size` will be
  326. multiplied by a cache factor derived from the homeserver config
  327. clock:
  328. prune_unread_entries: If True, cache entries that haven't been read recently
  329. will be evicted from the cache in the background. Set to False to
  330. opt-out of this behaviour.
  331. """
  332. # Default `clock` to something sensible. Note that we rename it to
  333. # `real_clock` so that mypy doesn't think its still `Optional`.
  334. if clock is None:
  335. real_clock = Clock(cast(IReactorTime, reactor))
  336. else:
  337. real_clock = clock
  338. cache: Union[Dict[KT, _Node[KT, VT]], TreeCache] = cache_type()
  339. self.cache = cache # Used for introspection.
  340. self.apply_cache_factor_from_config = apply_cache_factor_from_config
  341. # Save the original max size, and apply the default size factor.
  342. self._original_max_size = max_size
  343. # We previously didn't apply the cache factor here, and as such some caches were
  344. # not affected by the global cache factor. Add an option here to disable applying
  345. # the cache factor when a cache is created
  346. if apply_cache_factor_from_config:
  347. self.max_size = int(max_size * cache_config.properties.default_factor_size)
  348. else:
  349. self.max_size = int(max_size)
  350. # register_cache might call our "set_cache_factor" callback; there's nothing to
  351. # do yet when we get resized.
  352. self._on_resize: Optional[Callable[[], None]] = None
  353. if cache_name is not None:
  354. metrics: Optional[CacheMetric] = register_cache(
  355. "lru_cache",
  356. cache_name,
  357. self,
  358. collect_callback=metrics_collection_callback,
  359. )
  360. else:
  361. metrics = None
  362. # this is exposed for access from outside this class
  363. self.metrics = metrics
  364. # We create a single weakref to self here so that we don't need to keep
  365. # creating more each time we create a `_Node`.
  366. weak_ref_to_self = weakref.ref(self)
  367. list_root = ListNode[_Node[KT, VT]].create_root_node()
  368. lock = threading.Lock()
  369. def evict() -> None:
  370. while cache_len() > self.max_size:
  371. # Get the last node in the list (i.e. the oldest node).
  372. todelete = list_root.prev_node
  373. # The list root should always have a valid `prev_node` if the
  374. # cache is not empty.
  375. assert todelete is not None
  376. # The node should always have a reference to a cache entry, as
  377. # we only drop the cache entry when we remove the node from the
  378. # list.
  379. node = todelete.get_cache_entry()
  380. assert node is not None
  381. evicted_len = delete_node(node)
  382. cache.pop(node.key, None)
  383. if metrics:
  384. metrics.inc_evictions(EvictionReason.size, evicted_len)
  385. def synchronized(f: FT) -> FT:
  386. @wraps(f)
  387. def inner(*args: Any, **kwargs: Any) -> Any:
  388. with lock:
  389. return f(*args, **kwargs)
  390. return cast(FT, inner)
  391. cached_cache_len = [0]
  392. if size_callback is not None:
  393. def cache_len() -> int:
  394. return cached_cache_len[0]
  395. else:
  396. def cache_len() -> int:
  397. return len(cache)
  398. self.len = synchronized(cache_len)
  399. def add_node(
  400. key: KT, value: VT, callbacks: Collection[Callable[[], None]] = ()
  401. ) -> None:
  402. node: _Node[KT, VT] = _Node(
  403. list_root,
  404. key,
  405. value,
  406. weak_ref_to_self,
  407. real_clock,
  408. callbacks,
  409. prune_unread_entries,
  410. )
  411. cache[key] = node
  412. if size_callback:
  413. cached_cache_len[0] += size_callback(node.value)
  414. if caches.TRACK_MEMORY_USAGE and metrics:
  415. metrics.inc_memory_usage(node.memory)
  416. def move_node_to_front(node: _Node[KT, VT]) -> None:
  417. node.move_to_front(real_clock, list_root)
  418. def delete_node(node: _Node[KT, VT]) -> int:
  419. node.drop_from_lists()
  420. deleted_len = 1
  421. if size_callback:
  422. deleted_len = size_callback(node.value)
  423. cached_cache_len[0] -= deleted_len
  424. node.run_and_clear_callbacks()
  425. if caches.TRACK_MEMORY_USAGE and metrics:
  426. metrics.dec_memory_usage(node.memory)
  427. return deleted_len
  428. @overload
  429. def cache_get(
  430. key: KT,
  431. default: Literal[None] = None,
  432. callbacks: Collection[Callable[[], None]] = ...,
  433. update_metrics: bool = ...,
  434. update_last_access: bool = ...,
  435. ) -> Optional[VT]:
  436. ...
  437. @overload
  438. def cache_get(
  439. key: KT,
  440. default: T,
  441. callbacks: Collection[Callable[[], None]] = ...,
  442. update_metrics: bool = ...,
  443. update_last_access: bool = ...,
  444. ) -> Union[T, VT]:
  445. ...
  446. @synchronized
  447. def cache_get(
  448. key: KT,
  449. default: Optional[T] = None,
  450. callbacks: Collection[Callable[[], None]] = (),
  451. update_metrics: bool = True,
  452. update_last_access: bool = True,
  453. ) -> Union[None, T, VT]:
  454. """Look up a key in the cache
  455. Args:
  456. key
  457. default
  458. callbacks: A collection of callbacks that will fire when the
  459. node is removed from the cache (either due to invalidation
  460. or expiry).
  461. update_metrics: Whether to update the hit rate metrics
  462. update_last_access: Whether to update the last access metrics
  463. on a node if successfully fetched. These metrics are used
  464. to determine when to remove the node from the cache. Set
  465. to False if this fetch should *not* prevent a node from
  466. being expired.
  467. """
  468. node = cache.get(key, None)
  469. if node is not None:
  470. if update_last_access:
  471. move_node_to_front(node)
  472. node.add_callbacks(callbacks)
  473. if update_metrics and metrics:
  474. metrics.inc_hits()
  475. return node.value
  476. else:
  477. if update_metrics and metrics:
  478. metrics.inc_misses()
  479. return default
  480. @overload
  481. def cache_get_multi(
  482. key: tuple,
  483. default: Literal[None] = None,
  484. update_metrics: bool = True,
  485. ) -> Union[None, Iterable[Tuple[KT, VT]]]:
  486. ...
  487. @overload
  488. def cache_get_multi(
  489. key: tuple,
  490. default: T,
  491. update_metrics: bool = True,
  492. ) -> Union[T, Iterable[Tuple[KT, VT]]]:
  493. ...
  494. @synchronized
  495. def cache_get_multi(
  496. key: tuple,
  497. default: Optional[T] = None,
  498. update_metrics: bool = True,
  499. ) -> Union[None, T, Iterable[Tuple[KT, VT]]]:
  500. """Returns a generator yielding all entries under the given key.
  501. Can only be used if backed by a tree cache.
  502. Example:
  503. cache = LruCache(10, cache_type=TreeCache)
  504. cache[(1, 1)] = "a"
  505. cache[(1, 2)] = "b"
  506. cache[(2, 1)] = "c"
  507. items = cache.get_multi((1,))
  508. assert list(items) == [((1, 1), "a"), ((1, 2), "b")]
  509. Returns:
  510. Either default if the key doesn't exist, or a generator of the
  511. key/value pairs.
  512. """
  513. assert isinstance(cache, TreeCache)
  514. node = cache.get(key, None)
  515. if node is not None:
  516. if update_metrics and metrics:
  517. metrics.inc_hits()
  518. # We store entries in the `TreeCache` with values of type `_Node`,
  519. # which we need to unwrap.
  520. return (
  521. (full_key, lru_node.value)
  522. for full_key, lru_node in iterate_tree_cache_items(key, node)
  523. )
  524. else:
  525. if update_metrics and metrics:
  526. metrics.inc_misses()
  527. return default
  528. @synchronized
  529. def cache_set(
  530. key: KT, value: VT, callbacks: Collection[Callable[[], None]] = ()
  531. ) -> None:
  532. node = cache.get(key, None)
  533. if node is not None:
  534. # We sometimes store large objects, e.g. dicts, which cause
  535. # the inequality check to take a long time. So let's only do
  536. # the check if we have some callbacks to call.
  537. if value != node.value:
  538. node.run_and_clear_callbacks()
  539. # We don't bother to protect this by value != node.value as
  540. # generally size_callback will be cheap compared with equality
  541. # checks. (For example, taking the size of two dicts is quicker
  542. # than comparing them for equality.)
  543. if size_callback:
  544. cached_cache_len[0] -= size_callback(node.value)
  545. cached_cache_len[0] += size_callback(value)
  546. node.add_callbacks(callbacks)
  547. move_node_to_front(node)
  548. node.value = value
  549. else:
  550. add_node(key, value, set(callbacks))
  551. evict()
  552. @synchronized
  553. def cache_set_default(key: KT, value: VT) -> VT:
  554. node = cache.get(key, None)
  555. if node is not None:
  556. return node.value
  557. else:
  558. add_node(key, value)
  559. evict()
  560. return value
  561. @overload
  562. def cache_pop(key: KT, default: Literal[None] = None) -> Optional[VT]:
  563. ...
  564. @overload
  565. def cache_pop(key: KT, default: T) -> Union[T, VT]:
  566. ...
  567. @synchronized
  568. def cache_pop(key: KT, default: Optional[T] = None) -> Union[None, T, VT]:
  569. node = cache.get(key, None)
  570. if node:
  571. evicted_len = delete_node(node)
  572. cache.pop(node.key, None)
  573. if metrics:
  574. metrics.inc_evictions(EvictionReason.invalidation, evicted_len)
  575. return node.value
  576. else:
  577. return default
  578. @synchronized
  579. def cache_del_multi(key: KT) -> None:
  580. """Delete an entry, or tree of entries
  581. If the LruCache is backed by a regular dict, then "key" must be of
  582. the right type for this cache
  583. If the LruCache is backed by a TreeCache, then "key" must be a tuple, but
  584. may be of lower cardinality than the TreeCache - in which case the whole
  585. subtree is deleted.
  586. """
  587. popped = cache.pop(key, None)
  588. if popped is None:
  589. return
  590. # for each deleted node, we now need to remove it from the linked list
  591. # and run its callbacks.
  592. for leaf in iterate_tree_cache_entry(popped):
  593. delete_node(leaf)
  594. @synchronized
  595. def cache_clear() -> None:
  596. for node in cache.values():
  597. node.run_and_clear_callbacks()
  598. node.drop_from_lists()
  599. assert list_root.next_node == list_root
  600. assert list_root.prev_node == list_root
  601. cache.clear()
  602. if size_callback:
  603. cached_cache_len[0] = 0
  604. if caches.TRACK_MEMORY_USAGE and metrics:
  605. metrics.clear_memory_usage()
  606. @synchronized
  607. def cache_contains(key: KT) -> bool:
  608. return key in cache
  609. # make sure that we clear out any excess entries after we get resized.
  610. self._on_resize = evict
  611. self.get = cache_get
  612. self.set = cache_set
  613. self.setdefault = cache_set_default
  614. self.pop = cache_pop
  615. self.del_multi = cache_del_multi
  616. if cache_type is TreeCache:
  617. self.get_multi = cache_get_multi
  618. # `invalidate` is exposed for consistency with DeferredCache, so that it can be
  619. # invalidated by the cache invalidation replication stream.
  620. self.invalidate = cache_del_multi
  621. self.len = synchronized(cache_len)
  622. self.contains = cache_contains
  623. self.clear = cache_clear
  624. def __getitem__(self, key: KT) -> VT:
  625. result = self.get(key, _Sentinel.sentinel)
  626. if result is _Sentinel.sentinel:
  627. raise KeyError()
  628. else:
  629. return result
  630. def __setitem__(self, key: KT, value: VT) -> None:
  631. self.set(key, value)
  632. def __delitem__(self, key: KT, value: VT) -> None:
  633. result = self.pop(key, _Sentinel.sentinel)
  634. if result is _Sentinel.sentinel:
  635. raise KeyError()
  636. def __len__(self) -> int:
  637. return self.len()
  638. def __contains__(self, key: KT) -> bool:
  639. return self.contains(key)
  640. def set_cache_factor(self, factor: float) -> bool:
  641. """
  642. Set the cache factor for this individual cache.
  643. This will trigger a resize if it changes, which may require evicting
  644. items from the cache.
  645. Returns:
  646. Whether the cache changed size or not.
  647. """
  648. if not self.apply_cache_factor_from_config:
  649. return False
  650. new_size = int(self._original_max_size * factor)
  651. if new_size != self.max_size:
  652. self.max_size = new_size
  653. if self._on_resize:
  654. self._on_resize()
  655. return True
  656. return False
  657. def __del__(self) -> None:
  658. # We're about to be deleted, so we make sure to clear up all the nodes
  659. # and run callbacks, etc.
  660. #
  661. # This happens e.g. in the sync code where we have an expiring cache of
  662. # lru caches.
  663. self.clear()
  664. class AsyncLruCache(Generic[KT, VT]):
  665. """
  666. An asynchronous wrapper around a subset of the LruCache API.
  667. On its own this doesn't change the behaviour but allows subclasses that
  668. utilize external cache systems that require await behaviour to be created.
  669. """
  670. def __init__(self, *args, **kwargs): # type: ignore
  671. self._lru_cache: LruCache[KT, VT] = LruCache(*args, **kwargs)
  672. async def get(
  673. self, key: KT, default: Optional[T] = None, update_metrics: bool = True
  674. ) -> Optional[VT]:
  675. return self._lru_cache.get(key, update_metrics=update_metrics)
  676. async def get_external(
  677. self,
  678. key: KT,
  679. default: Optional[T] = None,
  680. update_metrics: bool = True,
  681. ) -> Optional[VT]:
  682. # This method should fetch from any configured external cache, in this case noop.
  683. return None
  684. def get_local(
  685. self, key: KT, default: Optional[T] = None, update_metrics: bool = True
  686. ) -> Optional[VT]:
  687. return self._lru_cache.get(key, update_metrics=update_metrics)
  688. async def set(self, key: KT, value: VT) -> None:
  689. self._lru_cache.set(key, value)
  690. def set_local(self, key: KT, value: VT) -> None:
  691. self._lru_cache.set(key, value)
  692. async def invalidate(self, key: KT) -> None:
  693. # This method should invalidate any external cache and then invalidate the LruCache.
  694. return self._lru_cache.invalidate(key)
  695. def invalidate_local(self, key: KT) -> None:
  696. """Remove an entry from the local cache
  697. This variant of `invalidate` is useful if we know that the external
  698. cache has already been invalidated.
  699. """
  700. return self._lru_cache.invalidate(key)
  701. async def contains(self, key: KT) -> bool:
  702. return self._lru_cache.contains(key)
  703. async def clear(self) -> None:
  704. self._lru_cache.clear()