2019-01-30 05:55:25 -05:00
|
|
|
#
|
2023-11-21 15:29:58 -05:00
|
|
|
# This file is licensed under the Affero General Public License (AGPL) version 3.
|
|
|
|
#
|
|
|
|
# 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]
|
2019-01-30 05:55:25 -05:00
|
|
|
#
|
|
|
|
#
|
|
|
|
|
|
|
|
import logging
|
|
|
|
import time
|
2021-03-29 12:15:33 -04:00
|
|
|
from typing import Any, Callable, Dict, Generic, Tuple, TypeVar, Union
|
2019-01-30 05:55:25 -05:00
|
|
|
|
|
|
|
import attr
|
|
|
|
from sortedcontainers import SortedList
|
|
|
|
|
|
|
|
from synapse.util.caches import register_cache
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2021-07-15 12:46:54 -04:00
|
|
|
SENTINEL: Any = object()
|
2019-01-30 05:55:25 -05:00
|
|
|
|
2021-03-29 12:15:33 -04:00
|
|
|
T = TypeVar("T")
|
|
|
|
KT = TypeVar("KT")
|
|
|
|
VT = TypeVar("VT")
|
2019-01-30 05:55:25 -05:00
|
|
|
|
2021-03-29 12:15:33 -04:00
|
|
|
|
|
|
|
class TTLCache(Generic[KT, VT]):
|
2019-01-30 05:55:25 -05:00
|
|
|
"""A key/value cache implementation where each entry has its own TTL"""
|
|
|
|
|
2021-03-29 12:15:33 -04:00
|
|
|
def __init__(self, cache_name: str, timer: Callable[[], float] = time.time):
|
2019-01-30 05:55:25 -05:00
|
|
|
# map from key to _CacheEntry
|
2023-09-08 14:29:38 -04:00
|
|
|
self._data: Dict[KT, _CacheEntry[KT, VT]] = {}
|
2019-01-30 05:55:25 -05:00
|
|
|
|
|
|
|
# the _CacheEntries, sorted by expiry time
|
2023-09-08 14:29:38 -04:00
|
|
|
self._expiry_list: SortedList[_CacheEntry[KT, VT]] = SortedList()
|
2019-01-30 05:55:25 -05:00
|
|
|
|
|
|
|
self._timer = timer
|
|
|
|
|
2020-05-11 13:45:23 -04:00
|
|
|
self._metrics = register_cache("ttl", cache_name, self, resizable=False)
|
2019-01-30 05:55:25 -05:00
|
|
|
|
2021-03-29 12:15:33 -04:00
|
|
|
def set(self, key: KT, value: VT, ttl: float) -> None:
|
2019-01-30 05:55:25 -05:00
|
|
|
"""Add/update an entry in the cache
|
|
|
|
|
|
|
|
Args:
|
|
|
|
key: key for this entry
|
|
|
|
value: value for this entry
|
2021-03-29 12:15:33 -04:00
|
|
|
ttl: TTL for this entry, in seconds
|
2019-01-30 05:55:25 -05:00
|
|
|
"""
|
|
|
|
expiry = self._timer() + ttl
|
|
|
|
|
|
|
|
self.expire()
|
|
|
|
e = self._data.pop(key, SENTINEL)
|
2021-03-29 12:15:33 -04:00
|
|
|
if e is not SENTINEL:
|
|
|
|
assert isinstance(e, _CacheEntry)
|
2019-01-30 05:55:25 -05:00
|
|
|
self._expiry_list.remove(e)
|
|
|
|
|
2019-08-12 10:39:14 -04:00
|
|
|
entry = _CacheEntry(expiry_time=expiry, ttl=ttl, key=key, value=value)
|
2019-01-30 05:55:25 -05:00
|
|
|
self._data[key] = entry
|
|
|
|
self._expiry_list.add(entry)
|
|
|
|
|
2021-03-29 12:15:33 -04:00
|
|
|
def get(self, key: KT, default: T = SENTINEL) -> Union[VT, T]:
|
2019-01-30 05:55:25 -05:00
|
|
|
"""Get a value from the cache
|
|
|
|
|
|
|
|
Args:
|
|
|
|
key: key to look up
|
|
|
|
default: default value to return, if key is not found. If not set, and the
|
|
|
|
key is not found, a KeyError will be raised
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
value from the cache, or the default
|
|
|
|
"""
|
|
|
|
self.expire()
|
|
|
|
e = self._data.get(key, SENTINEL)
|
2021-03-29 12:15:33 -04:00
|
|
|
if e is SENTINEL:
|
2019-01-30 05:55:25 -05:00
|
|
|
self._metrics.inc_misses()
|
2021-03-29 12:15:33 -04:00
|
|
|
if default is SENTINEL:
|
2019-01-30 05:55:25 -05:00
|
|
|
raise KeyError(key)
|
|
|
|
return default
|
2021-03-29 12:15:33 -04:00
|
|
|
assert isinstance(e, _CacheEntry)
|
2019-01-30 05:55:25 -05:00
|
|
|
self._metrics.inc_hits()
|
|
|
|
return e.value
|
|
|
|
|
2021-03-29 12:15:33 -04:00
|
|
|
def get_with_expiry(self, key: KT) -> Tuple[VT, float, float]:
|
2019-01-30 05:55:25 -05:00
|
|
|
"""Get a value, and its expiry time, from the cache
|
|
|
|
|
|
|
|
Args:
|
|
|
|
key: key to look up
|
|
|
|
|
|
|
|
Returns:
|
2021-03-29 12:15:33 -04:00
|
|
|
A tuple of the value from the cache, the expiry time and the TTL
|
2019-01-30 05:55:25 -05:00
|
|
|
|
|
|
|
Raises:
|
|
|
|
KeyError if the entry is not found
|
|
|
|
"""
|
|
|
|
self.expire()
|
|
|
|
try:
|
|
|
|
e = self._data[key]
|
|
|
|
except KeyError:
|
|
|
|
self._metrics.inc_misses()
|
|
|
|
raise
|
|
|
|
self._metrics.inc_hits()
|
2019-08-12 10:39:14 -04:00
|
|
|
return e.value, e.expiry_time, e.ttl
|
2019-01-30 05:55:25 -05:00
|
|
|
|
2022-04-27 09:03:44 -04:00
|
|
|
def pop(self, key: KT, default: T = SENTINEL) -> Union[VT, T]:
|
2019-01-30 05:55:25 -05:00
|
|
|
"""Remove a value from the cache
|
|
|
|
|
|
|
|
If key is in the cache, remove it and return its value, else return default.
|
|
|
|
If default is not given and key is not in the cache, a KeyError is raised.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
key: key to look up
|
|
|
|
default: default value to return, if key is not found. If not set, and the
|
|
|
|
key is not found, a KeyError will be raised
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
value from the cache, or the default
|
|
|
|
"""
|
|
|
|
self.expire()
|
|
|
|
e = self._data.pop(key, SENTINEL)
|
2021-03-29 12:15:33 -04:00
|
|
|
if e is SENTINEL:
|
2019-01-30 05:55:25 -05:00
|
|
|
self._metrics.inc_misses()
|
2021-03-29 12:15:33 -04:00
|
|
|
if default is SENTINEL:
|
2019-01-30 05:55:25 -05:00
|
|
|
raise KeyError(key)
|
|
|
|
return default
|
2021-03-29 12:15:33 -04:00
|
|
|
assert isinstance(e, _CacheEntry)
|
2019-01-30 05:55:25 -05:00
|
|
|
self._expiry_list.remove(e)
|
|
|
|
self._metrics.inc_hits()
|
|
|
|
return e.value
|
|
|
|
|
2021-03-29 12:15:33 -04:00
|
|
|
def __getitem__(self, key: KT) -> VT:
|
2019-01-30 05:55:25 -05:00
|
|
|
return self.get(key)
|
|
|
|
|
2021-03-29 12:15:33 -04:00
|
|
|
def __delitem__(self, key: KT) -> None:
|
2019-01-30 05:55:25 -05:00
|
|
|
self.pop(key)
|
|
|
|
|
2021-03-29 12:15:33 -04:00
|
|
|
def __contains__(self, key: KT) -> bool:
|
2019-01-30 05:55:25 -05:00
|
|
|
return key in self._data
|
|
|
|
|
2021-03-29 12:15:33 -04:00
|
|
|
def __len__(self) -> int:
|
2019-01-30 05:55:25 -05:00
|
|
|
self.expire()
|
|
|
|
return len(self._data)
|
|
|
|
|
2021-03-29 12:15:33 -04:00
|
|
|
def expire(self) -> None:
|
2019-01-30 05:55:25 -05:00
|
|
|
"""Run the expiry on the cache. Any entries whose expiry times are due will
|
|
|
|
be removed
|
|
|
|
"""
|
|
|
|
now = self._timer()
|
|
|
|
while self._expiry_list:
|
|
|
|
first_entry = self._expiry_list[0]
|
|
|
|
if first_entry.expiry_time - now > 0.0:
|
|
|
|
break
|
|
|
|
del self._data[first_entry.key]
|
|
|
|
del self._expiry_list[0]
|
|
|
|
|
|
|
|
|
2021-10-06 06:20:49 -04:00
|
|
|
@attr.s(frozen=True, slots=True, auto_attribs=True)
|
2023-09-08 14:29:38 -04:00
|
|
|
class _CacheEntry(Generic[KT, VT]):
|
2019-01-30 05:55:25 -05:00
|
|
|
"""TTLCache entry"""
|
2019-06-20 05:32:02 -04:00
|
|
|
|
2019-01-30 05:55:25 -05:00
|
|
|
# expiry_time is the first attribute, so that entries are sorted by expiry.
|
2021-10-06 06:20:49 -04:00
|
|
|
expiry_time: float
|
|
|
|
ttl: float
|
2023-09-08 14:29:38 -04:00
|
|
|
key: KT
|
|
|
|
value: VT
|