2016-01-06 21:26:29 -07:00
|
|
|
# Copyright 2015, 2016 OpenMarket Ltd
|
2018-04-05 09:24:04 -06:00
|
|
|
# Copyright 2018 New Vector Ltd
|
2015-08-11 10:59:32 -06: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.
|
2020-10-30 05:43:17 -06:00
|
|
|
import enum
|
2018-07-09 00:09:20 -06:00
|
|
|
import functools
|
|
|
|
import inspect
|
2015-08-11 10:59:32 -06:00
|
|
|
import logging
|
2020-10-30 05:43:17 -06:00
|
|
|
from typing import (
|
|
|
|
Any,
|
2022-03-01 02:51:38 -07:00
|
|
|
Awaitable,
|
2020-10-30 05:43:17 -06:00
|
|
|
Callable,
|
2022-03-09 11:07:41 -07:00
|
|
|
Collection,
|
2021-11-16 06:47:36 -07:00
|
|
|
Dict,
|
2020-10-30 05:43:17 -06:00
|
|
|
Generic,
|
2021-11-16 06:47:36 -07:00
|
|
|
Hashable,
|
2020-10-30 05:43:17 -06:00
|
|
|
Iterable,
|
2022-08-23 08:53:27 -06:00
|
|
|
List,
|
2020-10-30 05:43:17 -06:00
|
|
|
Mapping,
|
|
|
|
Optional,
|
|
|
|
Sequence,
|
|
|
|
Tuple,
|
2021-11-16 06:47:36 -07:00
|
|
|
Type,
|
2020-10-30 05:43:17 -06:00
|
|
|
TypeVar,
|
|
|
|
Union,
|
|
|
|
cast,
|
|
|
|
)
|
2019-11-07 02:43:51 -07:00
|
|
|
from weakref import WeakValueDictionary
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2018-07-09 00:09:20 -06:00
|
|
|
from twisted.internet import defer
|
2021-11-16 06:47:36 -07:00
|
|
|
from twisted.python.failure import Failure
|
2018-07-09 00:09:20 -06:00
|
|
|
|
2019-07-03 08:07:04 -06:00
|
|
|
from synapse.logging.context import make_deferred_yieldable, preserve_fn
|
|
|
|
from synapse.util import unwrapFirstError
|
2022-03-14 13:04:29 -06:00
|
|
|
from synapse.util.async_helpers import delay_cancellation
|
2020-10-14 16:25:23 -06:00
|
|
|
from synapse.util.caches.deferred_cache import DeferredCache
|
2020-10-30 05:43:17 -06:00
|
|
|
from synapse.util.caches.lrucache import LruCache
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2019-11-07 02:43:51 -07:00
|
|
|
CacheKey = Union[Tuple, Any]
|
|
|
|
|
2020-09-03 08:38:32 -06:00
|
|
|
F = TypeVar("F", bound=Callable[..., Any])
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2020-09-03 08:38:32 -06:00
|
|
|
|
|
|
|
class _CachedFunction(Generic[F]):
|
2021-07-15 10:46:54 -06:00
|
|
|
invalidate: Any = None
|
|
|
|
invalidate_all: Any = None
|
|
|
|
prefill: Any = None
|
|
|
|
cache: Any = None
|
|
|
|
num_args: Any = None
|
2019-10-02 06:29:01 -06:00
|
|
|
|
2021-07-15 10:46:54 -06:00
|
|
|
__name__: str
|
2020-09-03 08:38:32 -06:00
|
|
|
|
|
|
|
# Note: This function signature is actually fiddled with by the synapse mypy
|
|
|
|
# plugin to a) make it a bound method, and b) remove any `cache_context` arg.
|
2021-07-15 10:46:54 -06:00
|
|
|
__call__: F
|
2019-10-02 06:29:01 -06:00
|
|
|
|
|
|
|
|
2020-09-04 04:54:56 -06:00
|
|
|
class _CacheDescriptorBase:
|
2021-11-16 06:47:36 -07:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
orig: Callable[..., Any],
|
|
|
|
num_args: Optional[int],
|
2022-03-09 11:07:41 -07:00
|
|
|
uncached_args: Optional[Collection[str]] = None,
|
2021-11-16 06:47:36 -07:00
|
|
|
cache_context: bool = False,
|
2022-08-23 03:49:59 -06:00
|
|
|
name: Optional[str] = None,
|
2021-11-16 06:47:36 -07:00
|
|
|
):
|
2017-03-22 07:54:20 -06:00
|
|
|
self.orig = orig
|
2022-08-23 03:49:59 -06:00
|
|
|
self.name = name or orig.__name__
|
2017-03-22 07:54:20 -06:00
|
|
|
|
2019-12-12 10:03:28 -07:00
|
|
|
arg_spec = inspect.getfullargspec(orig)
|
2017-03-22 07:54:20 -06:00
|
|
|
all_args = arg_spec.args
|
|
|
|
|
2022-03-09 11:07:41 -07:00
|
|
|
# There's no reason that keyword-only arguments couldn't be supported,
|
|
|
|
# but right now they're buggy so do not allow them.
|
|
|
|
if arg_spec.kwonlyargs:
|
|
|
|
raise ValueError(
|
|
|
|
"_CacheDescriptorBase does not support keyword-only arguments."
|
|
|
|
)
|
|
|
|
|
2017-03-22 07:54:20 -06:00
|
|
|
if "cache_context" in all_args:
|
|
|
|
if not cache_context:
|
|
|
|
raise ValueError(
|
|
|
|
"Cannot have a 'cache_context' arg without setting"
|
|
|
|
" cache_context=True"
|
|
|
|
)
|
|
|
|
elif cache_context:
|
|
|
|
raise ValueError(
|
|
|
|
"Cannot have cache_context=True without having an arg"
|
|
|
|
" named `cache_context`"
|
|
|
|
)
|
|
|
|
|
2022-03-09 11:07:41 -07:00
|
|
|
if num_args is not None and uncached_args is not None:
|
|
|
|
raise ValueError("Cannot provide both num_args and uncached_args")
|
|
|
|
|
2017-03-22 07:54:20 -06:00
|
|
|
if num_args is None:
|
|
|
|
num_args = len(all_args) - 1
|
|
|
|
if cache_context:
|
|
|
|
num_args -= 1
|
|
|
|
|
|
|
|
if len(all_args) < num_args + 1:
|
|
|
|
raise Exception(
|
|
|
|
"Not enough explicit positional arguments to key off for %r: "
|
|
|
|
"got %i args, but wanted %i. (@cached cannot key off *args or "
|
|
|
|
"**kwargs)" % (orig.__name__, len(all_args), num_args)
|
|
|
|
)
|
|
|
|
|
|
|
|
self.num_args = num_args
|
2017-03-30 07:19:10 -06:00
|
|
|
|
|
|
|
# list of the names of the args used as the cache key
|
2017-03-22 07:54:20 -06:00
|
|
|
self.arg_names = all_args[1 : num_args + 1]
|
|
|
|
|
2022-03-09 11:07:41 -07:00
|
|
|
# If there are args to not cache on, filter them out (and fix the size of num_args).
|
|
|
|
if uncached_args is not None:
|
|
|
|
include_arg_in_cache_key = [n not in uncached_args for n in self.arg_names]
|
|
|
|
else:
|
|
|
|
include_arg_in_cache_key = [True] * len(self.arg_names)
|
|
|
|
|
2017-03-30 07:19:10 -06:00
|
|
|
# self.arg_defaults is a map of arg name to its default value for each
|
|
|
|
# argument that has a default value
|
2017-03-28 04:14:15 -06:00
|
|
|
if arg_spec.defaults:
|
|
|
|
self.arg_defaults = dict(
|
|
|
|
zip(all_args[-len(arg_spec.defaults) :], arg_spec.defaults)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
self.arg_defaults = {}
|
|
|
|
|
2017-03-22 07:54:20 -06:00
|
|
|
if "cache_context" in self.arg_names:
|
|
|
|
raise Exception("cache_context arg cannot be included among the cache keys")
|
|
|
|
|
|
|
|
self.add_cache_context = cache_context
|
|
|
|
|
2022-03-09 11:07:41 -07:00
|
|
|
self.cache_key_builder = _get_cache_key_builder(
|
|
|
|
self.arg_names, include_arg_in_cache_key, self.arg_defaults
|
2020-10-30 05:43:17 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class _LruCachedFunction(Generic[F]):
|
2021-07-15 10:46:54 -06:00
|
|
|
cache: LruCache[CacheKey, Any]
|
|
|
|
__call__: F
|
2020-10-30 05:43:17 -06:00
|
|
|
|
|
|
|
|
|
|
|
def lru_cache(
|
2022-03-09 11:07:41 -07:00
|
|
|
*, max_entries: int = 1000, cache_context: bool = False
|
2020-10-30 05:43:17 -06:00
|
|
|
) -> Callable[[F], _LruCachedFunction[F]]:
|
|
|
|
"""A method decorator that applies a memoizing cache around the function.
|
|
|
|
|
|
|
|
This is more-or-less a drop-in equivalent to functools.lru_cache, although note
|
|
|
|
that the signature is slightly different.
|
|
|
|
|
|
|
|
The main differences with functools.lru_cache are:
|
|
|
|
(a) the size of the cache can be controlled via the cache_factor mechanism
|
|
|
|
(b) the wrapped function can request a "cache_context" which provides a
|
|
|
|
callback mechanism to indicate that the result is no longer valid
|
|
|
|
(c) prometheus metrics are exposed automatically.
|
|
|
|
|
|
|
|
The function should take zero or more arguments, which are used as the key for the
|
|
|
|
cache. Single-argument functions use that argument as the cache key; otherwise the
|
|
|
|
arguments are built into a tuple.
|
|
|
|
|
|
|
|
Cached functions can be "chained" (i.e. a cached function can call other cached
|
|
|
|
functions and get appropriately invalidated when they called caches are
|
|
|
|
invalidated) by adding a special "cache_context" argument to the function
|
|
|
|
and passing that as a kwarg to all caches called. For example:
|
|
|
|
|
|
|
|
@lru_cache(cache_context=True)
|
|
|
|
def foo(self, key, cache_context):
|
|
|
|
r1 = self.bar1(key, on_invalidate=cache_context.invalidate)
|
|
|
|
r2 = self.bar2(key, on_invalidate=cache_context.invalidate)
|
|
|
|
return r1 + r2
|
|
|
|
|
|
|
|
The wrapped function also has a 'cache' property which offers direct access to the
|
|
|
|
underlying LruCache.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def func(orig: F) -> _LruCachedFunction[F]:
|
|
|
|
desc = LruCacheDescriptor(
|
|
|
|
orig,
|
|
|
|
max_entries=max_entries,
|
|
|
|
cache_context=cache_context,
|
|
|
|
)
|
|
|
|
return cast(_LruCachedFunction[F], desc)
|
|
|
|
|
|
|
|
return func
|
|
|
|
|
|
|
|
|
|
|
|
class LruCacheDescriptor(_CacheDescriptorBase):
|
|
|
|
"""Helper for @lru_cache"""
|
|
|
|
|
|
|
|
class _Sentinel(enum.Enum):
|
|
|
|
sentinel = object()
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
2021-11-16 06:47:36 -07:00
|
|
|
orig: Callable[..., Any],
|
2020-10-30 05:43:17 -06:00
|
|
|
max_entries: int = 1000,
|
|
|
|
cache_context: bool = False,
|
|
|
|
):
|
2022-03-09 11:07:41 -07:00
|
|
|
super().__init__(
|
|
|
|
orig, num_args=None, uncached_args=None, cache_context=cache_context
|
|
|
|
)
|
2020-10-30 05:43:17 -06:00
|
|
|
self.max_entries = max_entries
|
|
|
|
|
2021-11-16 06:47:36 -07:00
|
|
|
def __get__(self, obj: Optional[Any], owner: Optional[Type]) -> Callable[..., Any]:
|
2021-07-15 10:46:54 -06:00
|
|
|
cache: LruCache[CacheKey, Any] = LruCache(
|
2022-08-23 03:49:59 -06:00
|
|
|
cache_name=self.name,
|
2020-10-30 05:43:17 -06:00
|
|
|
max_size=self.max_entries,
|
2021-07-15 10:46:54 -06:00
|
|
|
)
|
2020-10-30 05:43:17 -06:00
|
|
|
|
|
|
|
get_cache_key = self.cache_key_builder
|
|
|
|
sentinel = LruCacheDescriptor._Sentinel.sentinel
|
|
|
|
|
|
|
|
@functools.wraps(self.orig)
|
2021-11-16 06:47:36 -07:00
|
|
|
def _wrapped(*args: Any, **kwargs: Any) -> Any:
|
2020-10-30 05:43:17 -06:00
|
|
|
invalidate_callback = kwargs.pop("on_invalidate", None)
|
|
|
|
callbacks = (invalidate_callback,) if invalidate_callback else ()
|
|
|
|
|
|
|
|
cache_key = get_cache_key(args, kwargs)
|
2017-03-22 07:54:20 -06:00
|
|
|
|
2020-10-30 05:43:17 -06:00
|
|
|
ret = cache.get(cache_key, default=sentinel, callbacks=callbacks)
|
|
|
|
if ret != sentinel:
|
|
|
|
return ret
|
|
|
|
|
|
|
|
# Add our own `cache_context` to argument list if the wrapped function
|
|
|
|
# has asked for one
|
|
|
|
if self.add_cache_context:
|
|
|
|
kwargs["cache_context"] = _CacheContext.get_instance(cache, cache_key)
|
|
|
|
|
|
|
|
ret2 = self.orig(obj, *args, **kwargs)
|
|
|
|
cache.set(cache_key, ret2, callbacks=callbacks)
|
|
|
|
|
|
|
|
return ret2
|
|
|
|
|
|
|
|
wrapped = cast(_CachedFunction, _wrapped)
|
|
|
|
wrapped.cache = cache
|
2022-08-23 03:49:59 -06:00
|
|
|
obj.__dict__[self.name] = wrapped
|
2020-10-30 05:43:17 -06:00
|
|
|
|
|
|
|
return wrapped
|
|
|
|
|
|
|
|
|
|
|
|
class DeferredCacheDescriptor(_CacheDescriptorBase):
|
2015-08-11 10:59:32 -06:00
|
|
|
"""A method decorator that applies a memoizing cache around the function.
|
|
|
|
|
|
|
|
This caches deferreds, rather than the results themselves. Deferreds that
|
|
|
|
fail are removed from the cache.
|
|
|
|
|
|
|
|
The function is presumed to take zero or more arguments, which are used in
|
|
|
|
a tuple as the key for the cache. Hits are served directly from the cache;
|
|
|
|
misses use the function body to generate the value.
|
|
|
|
|
|
|
|
The wrapped function has an additional member, a callable called
|
|
|
|
"invalidate". This can be used to remove individual entries from the cache.
|
|
|
|
|
|
|
|
The wrapped function has another additional callable, called "prefill",
|
|
|
|
which can be used to insert values into the cache specifically, without
|
|
|
|
calling the calculation function.
|
2016-08-19 04:18:26 -06:00
|
|
|
|
|
|
|
Cached functions can be "chained" (i.e. a cached function can call other cached
|
|
|
|
functions and get appropriately invalidated when they called caches are
|
|
|
|
invalidated) by adding a special "cache_context" argument to the function
|
|
|
|
and passing that as a kwarg to all caches called. For example::
|
|
|
|
|
2020-08-19 05:09:07 -06:00
|
|
|
@cached(cache_context=True)
|
2016-08-19 04:18:26 -06:00
|
|
|
def foo(self, key, cache_context):
|
2016-08-19 08:13:58 -06:00
|
|
|
r1 = yield self.bar1(key, on_invalidate=cache_context.invalidate)
|
|
|
|
r2 = yield self.bar2(key, on_invalidate=cache_context.invalidate)
|
2019-07-23 07:00:55 -06:00
|
|
|
return r1 + r2
|
2016-08-19 04:18:26 -06:00
|
|
|
|
2017-03-22 07:54:20 -06:00
|
|
|
Args:
|
2022-02-02 08:11:23 -07:00
|
|
|
orig:
|
|
|
|
max_entries:
|
2021-11-16 06:47:36 -07:00
|
|
|
num_args: number of positional arguments (excluding ``self`` and
|
2017-03-22 07:54:20 -06:00
|
|
|
``cache_context``) to use as cache keys. Defaults to all named
|
|
|
|
args of the function.
|
2022-03-09 11:07:41 -07:00
|
|
|
uncached_args: a list of argument names to not use as the cache key.
|
|
|
|
(``self`` and ``cache_context`` are always ignored.) Cannot be used
|
|
|
|
with num_args.
|
2022-02-02 08:11:23 -07:00
|
|
|
tree:
|
|
|
|
cache_context:
|
|
|
|
iterable:
|
|
|
|
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.
|
2015-08-11 10:59:32 -06:00
|
|
|
"""
|
2019-06-20 03:32:02 -06:00
|
|
|
|
2017-03-22 07:54:20 -06:00
|
|
|
def __init__(
|
|
|
|
self,
|
2021-11-16 06:47:36 -07:00
|
|
|
orig: Callable[..., Any],
|
|
|
|
max_entries: int = 1000,
|
|
|
|
num_args: Optional[int] = None,
|
2022-03-09 11:07:41 -07:00
|
|
|
uncached_args: Optional[Collection[str]] = None,
|
2021-11-16 06:47:36 -07:00
|
|
|
tree: bool = False,
|
|
|
|
cache_context: bool = False,
|
|
|
|
iterable: bool = False,
|
2021-09-22 07:21:58 -06:00
|
|
|
prune_unread_entries: bool = True,
|
2022-08-23 03:49:59 -06:00
|
|
|
name: Optional[str] = None,
|
2017-01-13 10:46:17 -07:00
|
|
|
):
|
2022-03-09 11:07:41 -07:00
|
|
|
super().__init__(
|
|
|
|
orig,
|
|
|
|
num_args=num_args,
|
|
|
|
uncached_args=uncached_args,
|
|
|
|
cache_context=cache_context,
|
2022-08-23 03:49:59 -06:00
|
|
|
name=name,
|
2022-03-09 11:07:41 -07:00
|
|
|
)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2021-05-27 03:33:56 -06:00
|
|
|
if tree and self.num_args < 2:
|
|
|
|
raise RuntimeError(
|
|
|
|
"tree=True is nonsensical for cached functions with a single parameter"
|
|
|
|
)
|
|
|
|
|
2015-08-11 10:59:32 -06:00
|
|
|
self.max_entries = max_entries
|
2016-01-22 05:10:33 -07:00
|
|
|
self.tree = tree
|
2017-01-13 10:46:17 -07:00
|
|
|
self.iterable = iterable
|
2021-09-22 07:21:58 -06:00
|
|
|
self.prune_unread_entries = prune_unread_entries
|
2017-01-13 10:46:17 -07:00
|
|
|
|
2021-11-16 06:47:36 -07:00
|
|
|
def __get__(self, obj: Optional[Any], owner: Optional[Type]) -> Callable[..., Any]:
|
2021-07-15 10:46:54 -06:00
|
|
|
cache: DeferredCache[CacheKey, Any] = DeferredCache(
|
2022-08-23 03:49:59 -06:00
|
|
|
name=self.name,
|
2015-08-11 10:59:32 -06:00
|
|
|
max_entries=self.max_entries,
|
2016-01-22 05:10:33 -07:00
|
|
|
tree=self.tree,
|
2017-01-13 10:46:17 -07:00
|
|
|
iterable=self.iterable,
|
2021-09-22 07:21:58 -06:00
|
|
|
prune_unread_entries=self.prune_unread_entries,
|
2021-07-15 10:46:54 -06:00
|
|
|
)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2020-10-30 05:43:17 -06:00
|
|
|
get_cache_key = self.cache_key_builder
|
2017-05-04 07:18:46 -06:00
|
|
|
|
2015-08-11 10:59:32 -06:00
|
|
|
@functools.wraps(self.orig)
|
2021-11-16 06:47:36 -07:00
|
|
|
def _wrapped(*args: Any, **kwargs: Any) -> Any:
|
2016-08-19 08:02:38 -06:00
|
|
|
# If we're passed a cache_context then we'll want to call its invalidate()
|
|
|
|
# whenever we are invalidated
|
2016-08-19 08:13:58 -06:00
|
|
|
invalidate_callback = kwargs.pop("on_invalidate", None)
|
2016-08-19 04:18:26 -06:00
|
|
|
|
2017-05-04 07:18:46 -06:00
|
|
|
cache_key = get_cache_key(args, kwargs)
|
2016-08-19 04:18:26 -06:00
|
|
|
|
2015-08-11 10:59:32 -06:00
|
|
|
try:
|
2020-10-16 05:34:55 -06:00
|
|
|
ret = cache.get(cache_key, callback=invalidate_callback)
|
2015-08-11 10:59:32 -06:00
|
|
|
except KeyError:
|
2020-10-21 15:57:45 -06:00
|
|
|
# Add our own `cache_context` to argument list if the wrapped function
|
|
|
|
# has asked for one
|
|
|
|
if self.add_cache_context:
|
|
|
|
kwargs["cache_context"] = _CacheContext.get_instance(
|
|
|
|
cache, cache_key
|
|
|
|
)
|
|
|
|
|
2020-08-19 05:09:07 -06:00
|
|
|
ret = defer.maybeDeferred(preserve_fn(self.orig), obj, *args, **kwargs)
|
2020-10-16 05:34:55 -06:00
|
|
|
ret = cache.set(cache_key, ret, callback=invalidate_callback)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2022-03-14 13:04:29 -06:00
|
|
|
# We started a new call to `self.orig`, so we must always wait for it to
|
|
|
|
# complete. Otherwise we might mark our current logging context as
|
|
|
|
# finished while `self.orig` is still using it in the background.
|
|
|
|
ret = delay_cancellation(ret)
|
|
|
|
|
2020-10-16 05:34:55 -06:00
|
|
|
return make_deferred_yieldable(ret)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2019-10-02 06:29:01 -06:00
|
|
|
wrapped = cast(_CachedFunction, _wrapped)
|
|
|
|
|
2017-05-04 07:18:46 -06:00
|
|
|
if self.num_args == 1:
|
2021-05-27 03:33:56 -06:00
|
|
|
assert not self.tree
|
2017-05-04 07:18:46 -06:00
|
|
|
wrapped.invalidate = lambda key: cache.invalidate(key[0])
|
|
|
|
wrapped.prefill = lambda key, val: cache.prefill(key[0], val)
|
|
|
|
else:
|
|
|
|
wrapped.invalidate = cache.invalidate
|
|
|
|
wrapped.prefill = cache.prefill
|
|
|
|
|
2016-04-06 06:08:05 -06:00
|
|
|
wrapped.invalidate_all = cache.invalidate_all
|
|
|
|
wrapped.cache = cache
|
2017-05-22 08:04:42 -06:00
|
|
|
wrapped.num_args = self.num_args
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2022-08-23 03:49:59 -06:00
|
|
|
obj.__dict__[self.name] = wrapped
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
return wrapped
|
|
|
|
|
|
|
|
|
2020-10-30 05:43:17 -06:00
|
|
|
class DeferredCacheListDescriptor(_CacheDescriptorBase):
|
2015-08-11 10:59:32 -06:00
|
|
|
"""Wraps an existing cache to support bulk fetching of keys.
|
|
|
|
|
2021-05-14 04:12:36 -06:00
|
|
|
Given an iterable of keys it looks in the cache to find any hits, then passes
|
2022-03-01 02:51:38 -07:00
|
|
|
the set of missing keys to the wrapped function.
|
2017-03-30 06:22:24 -06:00
|
|
|
|
2022-03-01 02:51:38 -07:00
|
|
|
Once wrapped, the function returns a Deferred which resolves to a Dict mapping from
|
|
|
|
input key to output value.
|
2015-08-11 10:59:32 -06:00
|
|
|
"""
|
|
|
|
|
2021-11-16 06:47:36 -07:00
|
|
|
def __init__(
|
|
|
|
self,
|
2022-03-01 02:51:38 -07:00
|
|
|
orig: Callable[..., Awaitable[Dict]],
|
2021-11-16 06:47:36 -07:00
|
|
|
cached_method_name: str,
|
|
|
|
list_name: str,
|
|
|
|
num_args: Optional[int] = None,
|
2022-08-23 03:49:59 -06:00
|
|
|
name: Optional[str] = None,
|
2021-11-16 06:47:36 -07:00
|
|
|
):
|
2015-08-11 10:59:32 -06:00
|
|
|
"""
|
|
|
|
Args:
|
2021-11-16 06:47:36 -07:00
|
|
|
orig
|
|
|
|
cached_method_name: The name of the cached method.
|
|
|
|
list_name: Name of the argument which is the bulk lookup list
|
|
|
|
num_args: number of positional arguments (excluding ``self``,
|
2017-03-22 07:54:20 -06:00
|
|
|
but including list_name) to use as cache keys. Defaults to all
|
|
|
|
named args of the function.
|
2015-08-11 10:59:32 -06:00
|
|
|
"""
|
2022-08-23 03:49:59 -06:00
|
|
|
super().__init__(orig, num_args=num_args, uncached_args=None, name=name)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
self.list_name = list_name
|
|
|
|
|
|
|
|
self.list_pos = self.arg_names.index(self.list_name)
|
2016-04-06 06:08:05 -06:00
|
|
|
self.cached_method_name = cached_method_name
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
self.sentinel = object()
|
|
|
|
|
|
|
|
if self.list_name not in self.arg_names:
|
|
|
|
raise Exception(
|
|
|
|
"Couldn't see arguments %r for %r."
|
2016-04-06 06:08:05 -06:00
|
|
|
% (self.list_name, cached_method_name)
|
2015-08-11 10:59:32 -06:00
|
|
|
)
|
|
|
|
|
2021-11-16 06:47:36 -07:00
|
|
|
def __get__(
|
|
|
|
self, obj: Optional[Any], objtype: Optional[Type] = None
|
2022-03-01 02:51:38 -07:00
|
|
|
) -> Callable[..., "defer.Deferred[Dict[Hashable, Any]]"]:
|
2017-05-22 08:04:42 -06:00
|
|
|
cached_method = getattr(obj, self.cached_method_name)
|
2021-07-15 10:46:54 -06:00
|
|
|
cache: DeferredCache[CacheKey, Any] = cached_method.cache
|
2017-05-22 08:04:42 -06:00
|
|
|
num_args = cached_method.num_args
|
2016-04-06 06:08:05 -06:00
|
|
|
|
2015-08-11 10:59:32 -06:00
|
|
|
@functools.wraps(self.orig)
|
2022-03-01 02:51:38 -07:00
|
|
|
def wrapped(*args: Any, **kwargs: Any) -> "defer.Deferred[Dict]":
|
2018-06-10 15:38:50 -06:00
|
|
|
# If we're passed a cache_context then we'll want to call its
|
|
|
|
# invalidate() whenever we are invalidated
|
2016-08-19 08:13:58 -06:00
|
|
|
invalidate_callback = kwargs.pop("on_invalidate", None)
|
2016-08-19 04:18:26 -06:00
|
|
|
|
2015-08-11 10:59:32 -06:00
|
|
|
arg_dict = inspect.getcallargs(self.orig, obj, *args, **kwargs)
|
|
|
|
keyargs = [arg_dict[arg_nm] for arg_nm in self.arg_names]
|
|
|
|
list_args = arg_dict[self.list_name]
|
|
|
|
|
2017-05-22 08:12:19 -06:00
|
|
|
# If the cache takes a single arg then that is used as the key,
|
|
|
|
# otherwise a tuple is used.
|
|
|
|
if num_args == 1:
|
2019-06-20 03:32:02 -06:00
|
|
|
|
2021-11-16 06:47:36 -07:00
|
|
|
def arg_to_cache_key(arg: Hashable) -> Hashable:
|
2018-06-10 15:38:50 -06:00
|
|
|
return arg
|
2019-06-20 03:32:02 -06:00
|
|
|
|
2022-08-23 08:53:27 -06:00
|
|
|
def cache_key_to_arg(key: tuple) -> Hashable:
|
|
|
|
return key
|
|
|
|
|
2017-05-22 08:12:19 -06:00
|
|
|
else:
|
2018-06-10 15:38:50 -06:00
|
|
|
keylist = list(keyargs)
|
2017-05-22 08:12:19 -06:00
|
|
|
|
2021-11-16 06:47:36 -07:00
|
|
|
def arg_to_cache_key(arg: Hashable) -> Hashable:
|
2018-06-10 15:38:50 -06:00
|
|
|
keylist[self.list_pos] = arg
|
|
|
|
return tuple(keylist)
|
2017-05-22 08:12:19 -06:00
|
|
|
|
2022-08-23 08:53:27 -06:00
|
|
|
def cache_key_to_arg(key: tuple) -> Hashable:
|
|
|
|
return key[self.list_pos]
|
|
|
|
|
|
|
|
cache_keys = [arg_to_cache_key(arg) for arg in list_args]
|
|
|
|
immediate_results, pending_deferred, missing = cache.get_bulk(
|
|
|
|
cache_keys, callback=invalidate_callback
|
|
|
|
)
|
|
|
|
|
|
|
|
results = {cache_key_to_arg(key): v for key, v in immediate_results.items()}
|
|
|
|
|
|
|
|
cached_defers: List["defer.Deferred[Any]"] = []
|
|
|
|
if pending_deferred:
|
|
|
|
|
|
|
|
def update_results(r: Dict) -> None:
|
|
|
|
for k, v in r.items():
|
|
|
|
results[cache_key_to_arg(k)] = v
|
|
|
|
|
|
|
|
pending_deferred.addCallback(update_results)
|
|
|
|
cached_defers.append(pending_deferred)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
if missing:
|
2022-08-23 08:53:27 -06:00
|
|
|
cache_entry = cache.start_bulk_input(missing, invalidate_callback)
|
2018-06-10 15:38:50 -06:00
|
|
|
|
2021-11-16 06:47:36 -07:00
|
|
|
def complete_all(res: Dict[Hashable, Any]) -> None:
|
2022-08-23 08:53:27 -06:00
|
|
|
missing_results = {}
|
|
|
|
for key in missing:
|
|
|
|
arg = cache_key_to_arg(key)
|
|
|
|
val = res.get(arg, None)
|
|
|
|
|
|
|
|
results[arg] = val
|
|
|
|
missing_results[key] = val
|
|
|
|
|
|
|
|
cache_entry.complete_bulk(cache, missing_results)
|
2018-06-10 15:38:50 -06:00
|
|
|
|
2022-03-01 02:51:38 -07:00
|
|
|
def errback_all(f: Failure) -> None:
|
2022-08-23 08:53:27 -06:00
|
|
|
cache_entry.error_bulk(cache, missing, f)
|
2018-06-10 15:38:50 -06:00
|
|
|
|
2015-08-11 10:59:32 -06:00
|
|
|
args_to_call = dict(arg_dict)
|
2022-08-23 08:53:27 -06:00
|
|
|
args_to_call[self.list_name] = {
|
|
|
|
cache_key_to_arg(key) for key in missing
|
|
|
|
}
|
2022-03-01 02:51:38 -07:00
|
|
|
|
|
|
|
# dispatch the call, and attach the two handlers
|
2022-08-23 08:53:27 -06:00
|
|
|
missing_d = defer.maybeDeferred(
|
2022-03-01 02:51:38 -07:00
|
|
|
preserve_fn(self.orig), **args_to_call
|
|
|
|
).addCallbacks(complete_all, errback_all)
|
2022-08-23 08:53:27 -06:00
|
|
|
cached_defers.append(missing_d)
|
2016-06-01 11:01:22 -06:00
|
|
|
|
|
|
|
if cached_defers:
|
2018-06-10 15:38:50 -06:00
|
|
|
d = defer.gatherResults(cached_defers, consumeErrors=True).addCallbacks(
|
|
|
|
lambda _: results, unwrapFirstError
|
|
|
|
)
|
2022-03-14 13:04:29 -06:00
|
|
|
if missing:
|
|
|
|
# We started a new call to `self.orig`, so we must always wait for it to
|
|
|
|
# complete. Otherwise we might mark our current logging context as
|
|
|
|
# finished while `self.orig` is still using it in the background.
|
|
|
|
d = delay_cancellation(d)
|
2019-07-03 08:07:04 -06:00
|
|
|
return make_deferred_yieldable(d)
|
2016-06-01 11:01:22 -06:00
|
|
|
else:
|
2019-10-28 07:33:04 -06:00
|
|
|
return defer.succeed(results)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2022-08-23 03:49:59 -06:00
|
|
|
obj.__dict__[self.name] = wrapped
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
return wrapped
|
|
|
|
|
|
|
|
|
2019-11-07 02:43:51 -07:00
|
|
|
class _CacheContext:
|
|
|
|
"""Holds cache information from the cached function higher in the calling order.
|
|
|
|
|
|
|
|
Can be used to invalidate the higher level cache entry if something changes
|
|
|
|
on a lower level.
|
|
|
|
"""
|
|
|
|
|
2020-10-30 05:43:17 -06:00
|
|
|
Cache = Union[DeferredCache, LruCache]
|
|
|
|
|
2021-07-15 10:46:54 -06:00
|
|
|
_cache_context_objects: """WeakValueDictionary[
|
|
|
|
Tuple["_CacheContext.Cache", CacheKey], "_CacheContext"
|
|
|
|
]""" = WeakValueDictionary()
|
2019-11-07 02:43:51 -07:00
|
|
|
|
2020-10-30 05:43:17 -06:00
|
|
|
def __init__(self, cache: "_CacheContext.Cache", cache_key: CacheKey) -> None:
|
2019-11-07 02:43:51 -07:00
|
|
|
self._cache = cache
|
|
|
|
self._cache_key = cache_key
|
|
|
|
|
2021-07-15 10:46:54 -06:00
|
|
|
def invalidate(self) -> None:
|
2019-11-07 02:43:51 -07:00
|
|
|
"""Invalidates the cache entry referred to by the context."""
|
|
|
|
self._cache.invalidate(self._cache_key)
|
|
|
|
|
|
|
|
@classmethod
|
2020-10-14 12:43:37 -06:00
|
|
|
def get_instance(
|
2020-10-30 05:43:17 -06:00
|
|
|
cls, cache: "_CacheContext.Cache", cache_key: CacheKey
|
|
|
|
) -> "_CacheContext":
|
2019-11-07 02:43:51 -07:00
|
|
|
"""Returns an instance constructed with the given arguments.
|
|
|
|
|
|
|
|
A new instance is only created if none already exists.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# We make sure there are no identical _CacheContext instances. This is
|
|
|
|
# important in particular to dedupe when we add callbacks to lru cache
|
|
|
|
# nodes, otherwise the number of callbacks would grow.
|
|
|
|
return cls._cache_context_objects.setdefault(
|
|
|
|
(cache, cache_key), cls(cache, cache_key)
|
|
|
|
)
|
2016-08-19 04:18:26 -06:00
|
|
|
|
|
|
|
|
2017-03-22 07:54:20 -06:00
|
|
|
def cached(
|
2022-03-09 11:07:41 -07:00
|
|
|
*,
|
2020-09-03 08:38:32 -06:00
|
|
|
max_entries: int = 1000,
|
|
|
|
num_args: Optional[int] = None,
|
2022-03-09 11:07:41 -07:00
|
|
|
uncached_args: Optional[Collection[str]] = None,
|
2020-09-03 08:38:32 -06:00
|
|
|
tree: bool = False,
|
|
|
|
cache_context: bool = False,
|
|
|
|
iterable: bool = False,
|
2021-09-22 07:21:58 -06:00
|
|
|
prune_unread_entries: bool = True,
|
2022-08-23 03:49:59 -06:00
|
|
|
name: Optional[str] = None,
|
2020-09-03 08:38:32 -06:00
|
|
|
) -> Callable[[F], _CachedFunction[F]]:
|
2020-10-30 05:43:17 -06:00
|
|
|
func = lambda orig: DeferredCacheDescriptor(
|
2015-08-11 10:59:32 -06:00
|
|
|
orig,
|
|
|
|
max_entries=max_entries,
|
|
|
|
num_args=num_args,
|
2022-03-09 11:07:41 -07:00
|
|
|
uncached_args=uncached_args,
|
2016-01-22 05:10:33 -07:00
|
|
|
tree=tree,
|
2016-08-19 08:02:38 -06:00
|
|
|
cache_context=cache_context,
|
2017-01-13 10:46:17 -07:00
|
|
|
iterable=iterable,
|
2021-09-22 07:21:58 -06:00
|
|
|
prune_unread_entries=prune_unread_entries,
|
2022-08-23 03:49:59 -06:00
|
|
|
name=name,
|
2015-08-11 10:59:32 -06:00
|
|
|
)
|
|
|
|
|
2020-09-03 08:38:32 -06:00
|
|
|
return cast(Callable[[F], _CachedFunction[F]], func)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2020-09-03 08:38:32 -06:00
|
|
|
|
|
|
|
def cachedList(
|
2022-08-23 03:49:59 -06:00
|
|
|
*,
|
|
|
|
cached_method_name: str,
|
|
|
|
list_name: str,
|
|
|
|
num_args: Optional[int] = None,
|
|
|
|
name: Optional[str] = None,
|
2020-09-03 08:38:32 -06:00
|
|
|
) -> Callable[[F], _CachedFunction[F]]:
|
2022-05-25 05:49:54 -06:00
|
|
|
"""Creates a descriptor that wraps a function in a `DeferredCacheListDescriptor`.
|
2015-08-12 09:42:46 -06:00
|
|
|
|
2022-05-25 05:49:54 -06:00
|
|
|
Used to do batch lookups for an already created cache. One of the arguments
|
2015-08-12 09:42:46 -06:00
|
|
|
is specified as a list that is iterated through to lookup keys in the
|
2021-05-14 04:12:36 -06:00
|
|
|
original cache. A new tuple consisting of the (deduplicated) keys that weren't in
|
2022-05-25 05:49:54 -06:00
|
|
|
the cache gets passed to the original function, which is expected to results
|
|
|
|
in a map of key to value for each passed value. THe new results are stored in the
|
|
|
|
original cache. Note that any missing values are cached as None.
|
2015-08-12 09:42:46 -06:00
|
|
|
|
|
|
|
Args:
|
2020-09-03 08:38:32 -06:00
|
|
|
cached_method_name: The name of the single-item lookup method.
|
2018-06-10 15:38:50 -06:00
|
|
|
This is only used to find the cache to use.
|
2021-05-14 04:12:36 -06:00
|
|
|
list_name: The name of the argument that is the iterable to use to
|
2015-08-12 09:42:46 -06:00
|
|
|
do batch lookups in the cache.
|
2020-09-03 08:38:32 -06:00
|
|
|
num_args: Number of arguments to use as the key in the cache
|
2017-03-22 07:54:20 -06:00
|
|
|
(including list_name). Defaults to all named parameters.
|
2015-08-12 09:42:46 -06:00
|
|
|
|
|
|
|
Example:
|
|
|
|
|
2020-09-04 04:54:56 -06:00
|
|
|
class Example:
|
2022-05-25 05:49:54 -06:00
|
|
|
@cached()
|
|
|
|
def do_something(self, first_arg, second_arg):
|
2015-08-12 09:42:46 -06:00
|
|
|
...
|
|
|
|
|
2022-05-25 05:49:54 -06:00
|
|
|
@cachedList(cached_method_name="do_something", list_name="second_args")
|
2015-08-12 09:42:46 -06:00
|
|
|
def batch_do_something(self, first_arg, second_args):
|
|
|
|
...
|
|
|
|
"""
|
2020-10-30 05:43:17 -06:00
|
|
|
func = lambda orig: DeferredCacheListDescriptor(
|
2015-08-11 10:59:32 -06:00
|
|
|
orig,
|
2016-04-06 06:08:05 -06:00
|
|
|
cached_method_name=cached_method_name,
|
2015-08-11 10:59:32 -06:00
|
|
|
list_name=list_name,
|
|
|
|
num_args=num_args,
|
2022-08-23 03:49:59 -06:00
|
|
|
name=name,
|
2015-08-11 10:59:32 -06:00
|
|
|
)
|
2020-09-03 08:38:32 -06:00
|
|
|
|
|
|
|
return cast(Callable[[F], _CachedFunction[F]], func)
|
2020-10-30 05:43:17 -06:00
|
|
|
|
|
|
|
|
2022-03-09 11:07:41 -07:00
|
|
|
def _get_cache_key_builder(
|
|
|
|
param_names: Sequence[str],
|
|
|
|
include_params: Sequence[bool],
|
|
|
|
param_defaults: Mapping[str, Any],
|
2020-10-30 05:43:17 -06:00
|
|
|
) -> Callable[[Sequence[Any], Mapping[str, Any]], CacheKey]:
|
|
|
|
"""Construct a function which will build cache keys suitable for a cached function
|
|
|
|
|
|
|
|
Args:
|
|
|
|
param_names: list of formal parameter names for the cached function
|
2022-03-09 11:07:41 -07:00
|
|
|
include_params: list of bools of whether to include the parameter name in the cache key
|
2020-10-30 05:43:17 -06:00
|
|
|
param_defaults: a mapping from parameter name to default value for that param
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A function which will take an (args, kwargs) pair and return a cache key
|
|
|
|
"""
|
|
|
|
|
|
|
|
# By default our cache key is a tuple, but if there is only one item
|
|
|
|
# then don't bother wrapping in a tuple. This is to save memory.
|
|
|
|
|
|
|
|
if len(param_names) == 1:
|
|
|
|
nm = param_names[0]
|
2022-03-09 11:07:41 -07:00
|
|
|
assert include_params[0] is True
|
2020-10-30 05:43:17 -06:00
|
|
|
|
|
|
|
def get_cache_key(args: Sequence[Any], kwargs: Mapping[str, Any]) -> CacheKey:
|
|
|
|
if nm in kwargs:
|
|
|
|
return kwargs[nm]
|
|
|
|
elif len(args):
|
|
|
|
return args[0]
|
|
|
|
else:
|
|
|
|
return param_defaults[nm]
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
|
|
|
def get_cache_key(args: Sequence[Any], kwargs: Mapping[str, Any]) -> CacheKey:
|
2022-03-09 11:07:41 -07:00
|
|
|
return tuple(
|
|
|
|
_get_cache_key_gen(
|
|
|
|
param_names, include_params, param_defaults, args, kwargs
|
|
|
|
)
|
|
|
|
)
|
2020-10-30 05:43:17 -06:00
|
|
|
|
|
|
|
return get_cache_key
|
|
|
|
|
|
|
|
|
|
|
|
def _get_cache_key_gen(
|
|
|
|
param_names: Iterable[str],
|
2022-03-09 11:07:41 -07:00
|
|
|
include_params: Iterable[bool],
|
2020-10-30 05:43:17 -06:00
|
|
|
param_defaults: Mapping[str, Any],
|
|
|
|
args: Sequence[Any],
|
|
|
|
kwargs: Mapping[str, Any],
|
|
|
|
) -> Iterable[Any]:
|
|
|
|
"""Given some args/kwargs return a generator that resolves into
|
|
|
|
the cache_key.
|
|
|
|
|
|
|
|
This is essentially the same operation as `inspect.getcallargs`, but optimised so
|
|
|
|
that we don't need to inspect the target function for each call.
|
|
|
|
"""
|
|
|
|
# We loop through each arg name, looking up if its in the `kwargs`,
|
|
|
|
# otherwise using the next argument in `args`. If there are no more
|
|
|
|
# args then we try looking the arg name up in the defaults.
|
|
|
|
pos = 0
|
2022-03-09 11:07:41 -07:00
|
|
|
for nm, inc in zip(param_names, include_params):
|
2020-10-30 05:43:17 -06:00
|
|
|
if nm in kwargs:
|
2022-03-09 11:07:41 -07:00
|
|
|
if inc:
|
|
|
|
yield kwargs[nm]
|
2020-10-30 05:43:17 -06:00
|
|
|
elif pos < len(args):
|
2022-03-09 11:07:41 -07:00
|
|
|
if inc:
|
|
|
|
yield args[pos]
|
2020-10-30 05:43:17 -06:00
|
|
|
pos += 1
|
|
|
|
else:
|
2022-03-09 11:07:41 -07:00
|
|
|
if inc:
|
|
|
|
yield param_defaults[nm]
|