2015-02-16 11:16:47 -05:00
|
|
|
#
|
2023-11-21 15:29:58 -05:00
|
|
|
# This file is licensed under the Affero General Public License (AGPL) version 3.
|
|
|
|
#
|
2024-01-23 06:26:48 -05:00
|
|
|
# Copyright 2015, 2016 OpenMarket Ltd
|
2023-11-21 15:29:58 -05:00
|
|
|
# Copyright (C) 2023 New Vector, Ltd
|
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Affero General Public License as
|
|
|
|
# published by the Free Software Foundation, either version 3 of the
|
|
|
|
# License, or (at your option) any later version.
|
|
|
|
#
|
|
|
|
# See the GNU Affero General Public License for more details:
|
|
|
|
# <https://www.gnu.org/licenses/agpl-3.0.html>.
|
|
|
|
#
|
|
|
|
# Originally licensed under the Apache License, Version 2.0:
|
|
|
|
# <http://www.apache.org/licenses/LICENSE-2.0>.
|
|
|
|
#
|
|
|
|
# [This file includes modifications made by New Vector Limited]
|
2015-02-16 11:16:47 -05:00
|
|
|
#
|
|
|
|
#
|
|
|
|
|
|
|
|
import logging
|
2018-07-09 02:09:20 -04:00
|
|
|
from collections import OrderedDict
|
2023-09-08 14:29:38 -04:00
|
|
|
from typing import Any, Generic, Iterable, Optional, TypeVar, Union, overload
|
2021-04-06 08:58:18 -04:00
|
|
|
|
|
|
|
import attr
|
|
|
|
from typing_extensions import Literal
|
2015-02-16 11:16:47 -05:00
|
|
|
|
2021-11-16 08:47:36 -05:00
|
|
|
from twisted.internet import defer
|
|
|
|
|
2020-05-11 13:45:23 -04:00
|
|
|
from synapse.config import cache as cache_config
|
2018-07-18 09:35:24 -04:00
|
|
|
from synapse.metrics.background_process_metrics import run_as_background_process
|
2021-04-06 08:58:18 -04:00
|
|
|
from synapse.util import Clock
|
2021-09-22 05:59:52 -04:00
|
|
|
from synapse.util.caches import EvictionReason, register_cache
|
2015-02-16 11:16:47 -05:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2021-07-15 12:46:54 -04:00
|
|
|
SENTINEL: Any = object()
|
2021-04-06 08:58:18 -04:00
|
|
|
|
2018-09-21 09:55:47 -04:00
|
|
|
|
2021-04-06 08:58:18 -04:00
|
|
|
T = TypeVar("T")
|
|
|
|
KT = TypeVar("KT")
|
|
|
|
VT = TypeVar("VT")
|
2018-09-21 09:55:47 -04:00
|
|
|
|
2021-04-06 08:58:18 -04:00
|
|
|
|
|
|
|
class ExpiringCache(Generic[KT, VT]):
|
2019-06-20 05:32:02 -04:00
|
|
|
def __init__(
|
|
|
|
self,
|
2021-04-06 08:58:18 -04:00
|
|
|
cache_name: str,
|
|
|
|
clock: Clock,
|
|
|
|
max_len: int = 0,
|
|
|
|
expiry_ms: int = 0,
|
|
|
|
reset_expiry_on_get: bool = False,
|
|
|
|
iterable: bool = False,
|
2019-06-20 05:32:02 -04:00
|
|
|
):
|
2015-02-16 11:16:47 -05:00
|
|
|
"""
|
|
|
|
Args:
|
2021-04-06 08:58:18 -04:00
|
|
|
cache_name: Name of this cache, used for logging.
|
|
|
|
clock
|
|
|
|
max_len: Max size of dict. If the dict grows larger than this
|
2015-02-16 11:16:47 -05:00
|
|
|
then the oldest items get automatically evicted. Default is 0,
|
|
|
|
which indicates there is no max limit.
|
2021-04-06 08:58:18 -04:00
|
|
|
expiry_ms: How long before an item is evicted from the cache
|
2015-02-16 11:16:47 -05:00
|
|
|
in milliseconds. Default is 0, indicating items never get
|
|
|
|
evicted based on time.
|
2021-04-06 08:58:18 -04:00
|
|
|
reset_expiry_on_get: If true, will reset the expiry time for
|
2015-02-16 11:16:47 -05:00
|
|
|
an item on access. Defaults to False.
|
2021-04-06 08:58:18 -04:00
|
|
|
iterable: If true, the size is calculated by summing the
|
2017-01-16 08:48:04 -05:00
|
|
|
sizes of all entries, rather than the number of entries.
|
2015-02-16 11:16:47 -05:00
|
|
|
"""
|
|
|
|
self._cache_name = cache_name
|
|
|
|
|
2020-05-11 13:45:23 -04:00
|
|
|
self._original_max_size = max_len
|
|
|
|
|
|
|
|
self._max_size = int(max_len * cache_config.properties.default_factor_size)
|
|
|
|
|
2015-02-16 11:16:47 -05:00
|
|
|
self._clock = clock
|
|
|
|
|
|
|
|
self._expiry_ms = expiry_ms
|
|
|
|
self._reset_expiry_on_get = reset_expiry_on_get
|
|
|
|
|
2023-09-08 14:29:38 -04:00
|
|
|
self._cache: OrderedDict[KT, _CacheEntry[VT]] = OrderedDict()
|
2015-02-16 11:16:47 -05:00
|
|
|
|
2017-01-16 08:48:04 -05:00
|
|
|
self.iterable = iterable
|
2016-02-23 06:54:48 -05:00
|
|
|
|
2018-05-21 20:47:37 -04:00
|
|
|
self.metrics = register_cache("expiring", cache_name, self)
|
|
|
|
|
2015-02-16 11:16:47 -05:00
|
|
|
if not self._expiry_ms:
|
|
|
|
# Don't bother starting the loop if things never expire
|
|
|
|
return
|
|
|
|
|
2021-11-16 08:47:36 -05:00
|
|
|
def f() -> "defer.Deferred[None]":
|
2023-09-15 04:10:24 -04:00
|
|
|
return run_as_background_process("prune_cache", self._prune_cache)
|
2015-02-16 11:16:47 -05:00
|
|
|
|
2016-02-02 12:18:50 -05:00
|
|
|
self._clock.looping_call(f, self._expiry_ms / 2)
|
2015-02-16 11:16:47 -05:00
|
|
|
|
2021-04-06 08:58:18 -04:00
|
|
|
def __setitem__(self, key: KT, value: VT) -> None:
|
2015-02-16 11:16:47 -05:00
|
|
|
now = self._clock.time_msec()
|
|
|
|
self._cache[key] = _CacheEntry(now, value)
|
2020-05-11 13:45:23 -04:00
|
|
|
self.evict()
|
2015-02-16 11:16:47 -05:00
|
|
|
|
2021-04-06 08:58:18 -04:00
|
|
|
def evict(self) -> None:
|
2015-02-16 11:16:47 -05:00
|
|
|
# Evict if there are now too many items
|
2020-05-11 13:45:23 -04:00
|
|
|
while self._max_size and len(self) > self._max_size:
|
2017-01-17 06:18:13 -05:00
|
|
|
_key, value = self._cache.popitem(last=False)
|
|
|
|
if self.iterable:
|
2023-09-08 14:29:38 -04:00
|
|
|
# type-ignore, here and below: if self.iterable is true, then the value
|
|
|
|
# type VT should be Sized (i.e. have a __len__ method). We don't enforce
|
|
|
|
# this via the type system at present.
|
|
|
|
self.metrics.inc_evictions(EvictionReason.size, len(value.value)) # type: ignore[arg-type]
|
2018-02-01 12:57:51 -05:00
|
|
|
else:
|
2021-09-22 05:59:52 -04:00
|
|
|
self.metrics.inc_evictions(EvictionReason.size)
|
2015-02-16 11:16:47 -05:00
|
|
|
|
2021-04-06 08:58:18 -04:00
|
|
|
def __getitem__(self, key: KT) -> VT:
|
2016-02-23 06:54:48 -05:00
|
|
|
try:
|
|
|
|
entry = self._cache[key]
|
2016-06-02 06:29:44 -04:00
|
|
|
self.metrics.inc_hits()
|
2016-03-01 05:59:17 -05:00
|
|
|
except KeyError:
|
2016-06-02 06:29:44 -04:00
|
|
|
self.metrics.inc_misses()
|
2016-03-01 06:00:10 -05:00
|
|
|
raise
|
2015-02-16 11:16:47 -05:00
|
|
|
|
|
|
|
if self._reset_expiry_on_get:
|
|
|
|
entry.time = self._clock.time_msec()
|
|
|
|
|
|
|
|
return entry.value
|
|
|
|
|
2021-04-06 08:58:18 -04:00
|
|
|
def pop(self, key: KT, default: T = SENTINEL) -> Union[VT, T]:
|
2018-10-01 07:25:27 -04:00
|
|
|
"""Removes and returns the value with the given key from the cache.
|
|
|
|
|
|
|
|
If the key isn't in the cache then `default` will be returned if
|
|
|
|
specified, otherwise `KeyError` will get raised.
|
|
|
|
|
|
|
|
Identical functionality to `dict.pop(..)`.
|
|
|
|
"""
|
|
|
|
|
2021-04-06 08:58:18 -04:00
|
|
|
value = self._cache.pop(key, SENTINEL)
|
|
|
|
# The key was not found.
|
2018-09-21 09:55:47 -04:00
|
|
|
if value is SENTINEL:
|
2021-04-06 08:58:18 -04:00
|
|
|
if default is SENTINEL:
|
|
|
|
raise KeyError(key)
|
|
|
|
return default
|
2018-09-21 09:55:47 -04:00
|
|
|
|
2022-02-15 09:31:04 -05:00
|
|
|
if self.iterable:
|
2024-03-13 13:05:57 -04:00
|
|
|
self.metrics.inc_evictions(EvictionReason.invalidation, len(value.value))
|
2022-02-15 09:31:04 -05:00
|
|
|
else:
|
|
|
|
self.metrics.inc_evictions(EvictionReason.invalidation)
|
|
|
|
|
2021-04-06 08:58:18 -04:00
|
|
|
return value.value
|
2018-09-21 09:55:47 -04:00
|
|
|
|
2021-04-06 08:58:18 -04:00
|
|
|
def __contains__(self, key: KT) -> bool:
|
2017-06-29 09:08:33 -04:00
|
|
|
return key in self._cache
|
|
|
|
|
2021-04-06 08:58:18 -04:00
|
|
|
@overload
|
2024-03-13 12:46:44 -04:00
|
|
|
def get(self, key: KT, default: Literal[None] = None) -> Optional[VT]: ...
|
2021-04-06 08:58:18 -04:00
|
|
|
|
|
|
|
@overload
|
2024-03-13 12:46:44 -04:00
|
|
|
def get(self, key: KT, default: T) -> Union[VT, T]: ...
|
2021-04-06 08:58:18 -04:00
|
|
|
|
|
|
|
def get(self, key: KT, default: Optional[T] = None) -> Union[VT, Optional[T]]:
|
2015-02-16 11:16:47 -05:00
|
|
|
try:
|
|
|
|
return self[key]
|
|
|
|
except KeyError:
|
|
|
|
return default
|
|
|
|
|
2021-04-06 08:58:18 -04:00
|
|
|
def setdefault(self, key: KT, value: VT) -> VT:
|
2017-03-10 05:30:38 -05:00
|
|
|
try:
|
|
|
|
return self[key]
|
|
|
|
except KeyError:
|
|
|
|
self[key] = value
|
|
|
|
return value
|
|
|
|
|
2021-11-17 14:07:02 -05:00
|
|
|
async def _prune_cache(self) -> None:
|
2015-02-16 11:16:47 -05:00
|
|
|
if not self._expiry_ms:
|
|
|
|
# zero expiry time means don't expire. This should never get called
|
|
|
|
# since we have this check in start too.
|
|
|
|
return
|
2017-01-16 08:48:04 -05:00
|
|
|
begin_length = len(self)
|
2015-02-16 11:16:47 -05:00
|
|
|
|
|
|
|
now = self._clock.time_msec()
|
|
|
|
|
|
|
|
keys_to_delete = set()
|
|
|
|
|
2020-06-15 07:03:36 -04:00
|
|
|
for key, cache_entry in self._cache.items():
|
2015-02-16 11:16:47 -05:00
|
|
|
if now - cache_entry.time > self._expiry_ms:
|
|
|
|
keys_to_delete.add(key)
|
|
|
|
|
|
|
|
for k in keys_to_delete:
|
2017-01-17 06:18:13 -05:00
|
|
|
value = self._cache.pop(k)
|
|
|
|
if self.iterable:
|
2023-09-08 14:29:38 -04:00
|
|
|
self.metrics.inc_evictions(EvictionReason.time, len(value.value)) # type: ignore[arg-type]
|
2018-09-21 11:25:42 -04:00
|
|
|
else:
|
2021-09-22 05:59:52 -04:00
|
|
|
self.metrics.inc_evictions(EvictionReason.time)
|
2015-02-16 11:16:47 -05:00
|
|
|
|
|
|
|
logger.debug(
|
|
|
|
"[%s] _prune_cache before: %d, after len: %d",
|
2019-06-20 05:32:02 -04:00
|
|
|
self._cache_name,
|
|
|
|
begin_length,
|
|
|
|
len(self),
|
2015-02-16 11:16:47 -05:00
|
|
|
)
|
|
|
|
|
2021-04-06 08:58:18 -04:00
|
|
|
def __len__(self) -> int:
|
2017-01-16 08:48:04 -05:00
|
|
|
if self.iterable:
|
2023-09-08 14:29:38 -04:00
|
|
|
g: Iterable[int] = (len(entry.value) for entry in self._cache.values()) # type: ignore[arg-type]
|
|
|
|
return sum(g)
|
2017-01-16 08:48:04 -05:00
|
|
|
else:
|
|
|
|
return len(self._cache)
|
2016-02-23 06:54:48 -05:00
|
|
|
|
2020-05-11 13:45:23 -04: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:
|
2022-11-16 10:25:24 -05:00
|
|
|
Whether the cache changed size or not.
|
2020-05-11 13:45:23 -04:00
|
|
|
"""
|
|
|
|
new_size = int(self._original_max_size * factor)
|
|
|
|
if new_size != self._max_size:
|
|
|
|
self._max_size = new_size
|
|
|
|
self.evict()
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2015-02-16 11:16:47 -05:00
|
|
|
|
2021-11-16 08:47:36 -05:00
|
|
|
@attr.s(slots=True, auto_attribs=True)
|
2023-09-08 14:29:38 -04:00
|
|
|
class _CacheEntry(Generic[VT]):
|
2021-11-16 08:47:36 -05:00
|
|
|
time: int
|
2023-09-08 14:29:38 -04:00
|
|
|
value: VT
|