lrucache.py 24 KB

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