2015-08-11 10:59:32 -06:00
|
|
|
# -*- coding: utf-8 -*-
|
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.
|
2018-07-09 00:09:20 -06:00
|
|
|
import functools
|
|
|
|
import inspect
|
2015-08-11 10:59:32 -06:00
|
|
|
import logging
|
2018-07-09 00:09:20 -06:00
|
|
|
import threading
|
|
|
|
from collections import namedtuple
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2018-07-09 00:09:20 -06:00
|
|
|
import six
|
|
|
|
from six import itervalues, string_types
|
|
|
|
|
|
|
|
from twisted.internet import defer
|
|
|
|
|
|
|
|
from synapse.util import logcontext, unwrapFirstError
|
2015-08-11 10:59:32 -06:00
|
|
|
from synapse.util.async import ObservableDeferred
|
2018-02-21 13:49:55 -07:00
|
|
|
from synapse.util.caches import get_cache_factor_for
|
2015-08-11 10:59:32 -06:00
|
|
|
from synapse.util.caches.lrucache import LruCache
|
2017-01-17 04:44:57 -07:00
|
|
|
from synapse.util.caches.treecache import TreeCache, iterate_tree_cache_entry
|
2017-05-04 07:18:46 -06:00
|
|
|
from synapse.util.stringutils import to_ascii
|
2015-08-12 03:13:35 -06:00
|
|
|
|
2017-04-25 03:23:11 -06:00
|
|
|
from . import register_cache
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
_CacheSentinel = object()
|
|
|
|
|
|
|
|
|
2017-01-17 04:18:13 -07:00
|
|
|
class CacheEntry(object):
|
|
|
|
__slots__ = [
|
2018-04-05 09:24:04 -06:00
|
|
|
"deferred", "callbacks", "invalidated"
|
2017-01-17 04:18:13 -07:00
|
|
|
]
|
|
|
|
|
2018-04-05 09:24:04 -06:00
|
|
|
def __init__(self, deferred, callbacks):
|
2017-01-17 04:18:13 -07:00
|
|
|
self.deferred = deferred
|
|
|
|
self.callbacks = set(callbacks)
|
|
|
|
self.invalidated = False
|
|
|
|
|
|
|
|
def invalidate(self):
|
|
|
|
if not self.invalidated:
|
|
|
|
self.invalidated = True
|
|
|
|
for callback in self.callbacks:
|
|
|
|
callback()
|
|
|
|
self.callbacks.clear()
|
2017-01-13 10:46:17 -07:00
|
|
|
|
|
|
|
|
2015-08-11 10:59:32 -06:00
|
|
|
class Cache(object):
|
2016-06-02 04:29:44 -06:00
|
|
|
__slots__ = (
|
|
|
|
"cache",
|
|
|
|
"max_entries",
|
|
|
|
"name",
|
|
|
|
"keylen",
|
|
|
|
"thread",
|
|
|
|
"metrics",
|
2017-01-17 04:18:13 -07:00
|
|
|
"_pending_deferred_cache",
|
2016-06-02 04:29:44 -06:00
|
|
|
)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2017-01-13 10:46:17 -07:00
|
|
|
def __init__(self, name, max_entries=1000, keylen=1, tree=False, iterable=False):
|
2016-08-19 04:59:29 -06:00
|
|
|
cache_type = TreeCache if tree else dict
|
2017-01-17 04:18:13 -07:00
|
|
|
self._pending_deferred_cache = cache_type()
|
|
|
|
|
2016-08-19 04:59:29 -06:00
|
|
|
self.cache = LruCache(
|
2017-01-13 10:46:17 -07:00
|
|
|
max_size=max_entries, keylen=keylen, cache_type=cache_type,
|
2017-04-25 03:23:11 -06:00
|
|
|
size_callback=(lambda d: len(d)) if iterable else None,
|
2018-02-01 10:57:51 -07:00
|
|
|
evicted_callback=self._on_evicted,
|
2016-08-19 04:59:29 -06:00
|
|
|
)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
self.name = name
|
|
|
|
self.keylen = keylen
|
|
|
|
self.thread = None
|
2018-05-22 15:28:23 -06:00
|
|
|
self.metrics = register_cache("cache", name, self.cache)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2018-02-01 10:57:51 -07:00
|
|
|
def _on_evicted(self, evicted_count):
|
|
|
|
self.metrics.inc_evictions(evicted_count)
|
|
|
|
|
2015-08-11 10:59:32 -06:00
|
|
|
def check_thread(self):
|
|
|
|
expected_thread = self.thread
|
|
|
|
if expected_thread is None:
|
|
|
|
self.thread = threading.current_thread()
|
|
|
|
else:
|
|
|
|
if expected_thread is not threading.current_thread():
|
|
|
|
raise ValueError(
|
|
|
|
"Cache objects can only be accessed from the main thread"
|
|
|
|
)
|
|
|
|
|
2017-05-08 09:06:17 -06:00
|
|
|
def get(self, key, default=_CacheSentinel, callback=None, update_metrics=True):
|
2017-04-25 03:23:11 -06:00
|
|
|
"""Looks the key up in the caches.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
key(tuple)
|
|
|
|
default: What is returned if key is not in the caches. If not
|
|
|
|
specified then function throws KeyError instead
|
|
|
|
callback(fn): Gets called when the entry in the cache is invalidated
|
2017-05-08 09:06:17 -06:00
|
|
|
update_metrics (bool): whether to update the cache hit rate metrics
|
2017-04-25 03:23:11 -06:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
Either a Deferred or the raw result
|
|
|
|
"""
|
2017-01-17 04:18:13 -07:00
|
|
|
callbacks = [callback] if callback else []
|
|
|
|
val = self._pending_deferred_cache.get(key, _CacheSentinel)
|
|
|
|
if val is not _CacheSentinel:
|
2018-04-05 09:24:04 -06:00
|
|
|
val.callbacks.update(callbacks)
|
|
|
|
if update_metrics:
|
|
|
|
self.metrics.inc_hits()
|
|
|
|
return val.deferred
|
2017-01-17 04:18:13 -07:00
|
|
|
|
|
|
|
val = self.cache.get(key, _CacheSentinel, callbacks=callbacks)
|
2015-08-11 10:59:32 -06:00
|
|
|
if val is not _CacheSentinel:
|
2016-06-02 04:29:44 -06:00
|
|
|
self.metrics.inc_hits()
|
2015-08-11 10:59:32 -06:00
|
|
|
return val
|
|
|
|
|
2017-05-08 09:06:17 -06:00
|
|
|
if update_metrics:
|
|
|
|
self.metrics.inc_misses()
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
if default is _CacheSentinel:
|
|
|
|
raise KeyError()
|
|
|
|
else:
|
|
|
|
return default
|
|
|
|
|
2017-01-17 04:18:13 -07:00
|
|
|
def set(self, key, value, callback=None):
|
|
|
|
callbacks = [callback] if callback else []
|
2015-08-11 10:59:32 -06:00
|
|
|
self.check_thread()
|
2017-01-17 04:18:13 -07:00
|
|
|
entry = CacheEntry(
|
|
|
|
deferred=value,
|
|
|
|
callbacks=callbacks,
|
|
|
|
)
|
|
|
|
|
|
|
|
existing_entry = self._pending_deferred_cache.pop(key, None)
|
|
|
|
if existing_entry:
|
|
|
|
existing_entry.invalidate()
|
|
|
|
|
|
|
|
self._pending_deferred_cache[key] = entry
|
|
|
|
|
|
|
|
def shuffle(result):
|
2018-04-05 09:24:04 -06:00
|
|
|
existing_entry = self._pending_deferred_cache.pop(key, None)
|
|
|
|
if existing_entry is entry:
|
|
|
|
self.cache.set(key, result, entry.callbacks)
|
2017-01-17 04:18:13 -07:00
|
|
|
else:
|
2018-04-05 09:24:04 -06:00
|
|
|
# oops, the _pending_deferred_cache has been updated since
|
|
|
|
# we started our query, so we are out of date.
|
|
|
|
#
|
|
|
|
# Better put back whatever we took out. (We do it this way
|
|
|
|
# round, rather than peeking into the _pending_deferred_cache
|
|
|
|
# and then removing on a match, to make the common case faster)
|
|
|
|
if existing_entry is not None:
|
|
|
|
self._pending_deferred_cache[key] = existing_entry
|
|
|
|
|
|
|
|
# we're not going to put this entry into the cache, so need
|
|
|
|
# to make sure that the invalidation callbacks are called.
|
|
|
|
# That was probably done when _pending_deferred_cache was
|
|
|
|
# updated, but it's possible that `set` was called without
|
|
|
|
# `invalidate` being previously called, in which case it may
|
|
|
|
# not have been. Either way, let's double-check now.
|
2017-01-17 04:18:13 -07:00
|
|
|
entry.invalidate()
|
|
|
|
return result
|
|
|
|
|
|
|
|
entry.deferred.addCallback(shuffle)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2016-08-19 04:18:26 -06:00
|
|
|
def prefill(self, key, value, callback=None):
|
2017-01-17 04:18:13 -07:00
|
|
|
callbacks = [callback] if callback else []
|
|
|
|
self.cache.set(key, value, callbacks=callbacks)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
def invalidate(self, key):
|
|
|
|
self.check_thread()
|
2018-04-05 09:24:04 -06:00
|
|
|
self.cache.pop(key, None)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2018-04-05 09:24:04 -06:00
|
|
|
# if we have a pending lookup for this key, remove it from the
|
|
|
|
# _pending_deferred_cache, which will (a) stop it being returned
|
|
|
|
# for future queries and (b) stop it being persisted as a proper entry
|
|
|
|
# in self.cache.
|
2017-01-17 04:18:13 -07:00
|
|
|
entry = self._pending_deferred_cache.pop(key, None)
|
2018-04-05 09:24:04 -06:00
|
|
|
|
|
|
|
# run the invalidation callbacks now, rather than waiting for the
|
|
|
|
# deferred to resolve.
|
2017-01-17 04:18:13 -07:00
|
|
|
if entry:
|
|
|
|
entry.invalidate()
|
|
|
|
|
2016-01-21 12:16:25 -07:00
|
|
|
def invalidate_many(self, key):
|
|
|
|
self.check_thread()
|
|
|
|
if not isinstance(key, tuple):
|
|
|
|
raise TypeError(
|
|
|
|
"The cache key must be a tuple not %r" % (type(key),)
|
|
|
|
)
|
|
|
|
self.cache.del_multi(key)
|
|
|
|
|
2018-04-05 09:24:04 -06:00
|
|
|
# if we have a pending lookup for this key, remove it from the
|
|
|
|
# _pending_deferred_cache, as above
|
2017-01-17 07:43:32 -07:00
|
|
|
entry_dict = self._pending_deferred_cache.pop(key, None)
|
|
|
|
if entry_dict is not None:
|
2017-01-17 04:44:57 -07:00
|
|
|
for entry in iterate_tree_cache_entry(entry_dict):
|
2017-01-17 04:18:13 -07:00
|
|
|
entry.invalidate()
|
|
|
|
|
2015-08-11 10:59:32 -06:00
|
|
|
def invalidate_all(self):
|
|
|
|
self.check_thread()
|
|
|
|
self.cache.clear()
|
2018-05-24 12:52:56 -06:00
|
|
|
for entry in itervalues(self._pending_deferred_cache):
|
2018-04-05 09:24:04 -06:00
|
|
|
entry.invalidate()
|
|
|
|
self._pending_deferred_cache.clear()
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
|
2017-03-22 07:54:20 -06:00
|
|
|
class _CacheDescriptorBase(object):
|
|
|
|
def __init__(self, orig, num_args, inlineCallbacks, cache_context=False):
|
|
|
|
self.orig = orig
|
|
|
|
|
|
|
|
if inlineCallbacks:
|
|
|
|
self.function_to_call = defer.inlineCallbacks(orig)
|
|
|
|
else:
|
|
|
|
self.function_to_call = orig
|
|
|
|
|
|
|
|
arg_spec = inspect.getargspec(orig)
|
|
|
|
all_args = arg_spec.args
|
|
|
|
|
|
|
|
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`"
|
|
|
|
)
|
|
|
|
|
|
|
|
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]
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
class CacheDescriptor(_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::
|
|
|
|
|
2016-08-19 08:02:38 -06:00
|
|
|
@cachedInlineCallbacks(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)
|
2016-08-19 04:18:26 -06:00
|
|
|
defer.returnValue(r1 + r2)
|
|
|
|
|
2017-03-22 07:54:20 -06:00
|
|
|
Args:
|
|
|
|
num_args (int): number of positional arguments (excluding ``self`` and
|
|
|
|
``cache_context``) to use as cache keys. Defaults to all named
|
|
|
|
args of the function.
|
2015-08-11 10:59:32 -06:00
|
|
|
"""
|
2017-03-22 07:54:20 -06:00
|
|
|
def __init__(self, orig, max_entries=1000, num_args=None, tree=False,
|
2017-01-13 10:46:17 -07:00
|
|
|
inlineCallbacks=False, cache_context=False, iterable=False):
|
2016-03-01 06:21:46 -07:00
|
|
|
|
2017-03-22 07:54:20 -06:00
|
|
|
super(CacheDescriptor, self).__init__(
|
|
|
|
orig, num_args=num_args, inlineCallbacks=inlineCallbacks,
|
|
|
|
cache_context=cache_context)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2018-02-21 13:49:55 -07:00
|
|
|
max_entries = int(max_entries * get_cache_factor_for(orig.__name__))
|
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
|
|
|
|
|
2016-04-06 06:08:05 -06:00
|
|
|
def __get__(self, obj, objtype=None):
|
|
|
|
cache = Cache(
|
2015-08-11 10:59:32 -06:00
|
|
|
name=self.orig.__name__,
|
|
|
|
max_entries=self.max_entries,
|
|
|
|
keylen=self.num_args,
|
2016-01-22 05:10:33 -07:00
|
|
|
tree=self.tree,
|
2017-01-13 10:46:17 -07:00
|
|
|
iterable=self.iterable,
|
2015-08-11 10:59:32 -06:00
|
|
|
)
|
|
|
|
|
2017-05-04 07:18:46 -06:00
|
|
|
def get_cache_key_gen(args, kwargs):
|
2017-03-28 04:14:15 -06:00
|
|
|
"""Given some args/kwargs return a generator that resolves into
|
|
|
|
the cache_key.
|
|
|
|
|
|
|
|
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
|
|
|
|
for nm in self.arg_names:
|
|
|
|
if nm in kwargs:
|
|
|
|
yield kwargs[nm]
|
|
|
|
elif pos < len(args):
|
|
|
|
yield args[pos]
|
|
|
|
pos += 1
|
|
|
|
else:
|
|
|
|
yield self.arg_defaults[nm]
|
|
|
|
|
2017-05-04 07:18:46 -06:00
|
|
|
# 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 self.num_args == 1:
|
|
|
|
nm = self.arg_names[0]
|
|
|
|
|
|
|
|
def get_cache_key(args, kwargs):
|
|
|
|
if nm in kwargs:
|
|
|
|
return kwargs[nm]
|
|
|
|
elif len(args):
|
|
|
|
return args[0]
|
|
|
|
else:
|
|
|
|
return self.arg_defaults[nm]
|
|
|
|
else:
|
|
|
|
def get_cache_key(args, kwargs):
|
|
|
|
return tuple(get_cache_key_gen(args, kwargs))
|
|
|
|
|
2015-08-11 10:59:32 -06:00
|
|
|
@functools.wraps(self.orig)
|
|
|
|
def wrapped(*args, **kwargs):
|
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
|
|
|
|
2016-08-19 08:58:52 -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(cache, cache_key)
|
2016-08-19 04:18:26 -06:00
|
|
|
|
2015-08-11 10:59:32 -06:00
|
|
|
try:
|
2016-08-19 08:13:58 -06:00
|
|
|
cached_result_d = cache.get(cache_key, callback=invalidate_callback)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2017-04-25 03:23:11 -06:00
|
|
|
if isinstance(cached_result_d, ObservableDeferred):
|
|
|
|
observer = cached_result_d.observe()
|
|
|
|
else:
|
|
|
|
observer = cached_result_d
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
except KeyError:
|
|
|
|
ret = defer.maybeDeferred(
|
2017-03-30 06:22:24 -06:00
|
|
|
logcontext.preserve_fn(self.function_to_call),
|
2015-08-11 10:59:32 -06:00
|
|
|
obj, *args, **kwargs
|
|
|
|
)
|
|
|
|
|
|
|
|
def onErr(f):
|
2016-04-06 06:08:05 -06:00
|
|
|
cache.invalidate(cache_key)
|
2015-08-11 10:59:32 -06:00
|
|
|
return f
|
|
|
|
|
|
|
|
ret.addErrback(onErr)
|
|
|
|
|
2018-05-24 12:52:56 -06:00
|
|
|
# If our cache_key is a string on py2, try to convert to ascii
|
|
|
|
# to save a bit of space in large caches. Py3 does this
|
|
|
|
# internally automatically.
|
|
|
|
if six.PY2 and isinstance(cache_key, string_types):
|
2017-05-04 07:18:46 -06:00
|
|
|
cache_key = to_ascii(cache_key)
|
|
|
|
|
2017-03-30 06:22:24 -06:00
|
|
|
result_d = ObservableDeferred(ret, consumeErrors=True)
|
|
|
|
cache.set(cache_key, result_d, callback=invalidate_callback)
|
|
|
|
observer = result_d.observe()
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2017-03-28 03:41:08 -06:00
|
|
|
if isinstance(observer, defer.Deferred):
|
|
|
|
return logcontext.make_deferred_yieldable(observer)
|
|
|
|
else:
|
|
|
|
return observer
|
2015-08-11 10:59:32 -06:00
|
|
|
|
2017-05-04 07:18:46 -06:00
|
|
|
if self.num_args == 1:
|
|
|
|
wrapped.invalidate = lambda key: cache.invalidate(key[0])
|
|
|
|
wrapped.prefill = lambda key, val: cache.prefill(key[0], val)
|
|
|
|
else:
|
|
|
|
wrapped.invalidate = cache.invalidate
|
|
|
|
wrapped.invalidate_all = cache.invalidate_all
|
|
|
|
wrapped.invalidate_many = cache.invalidate_many
|
|
|
|
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
|
|
|
|
|
|
|
obj.__dict__[self.orig.__name__] = wrapped
|
|
|
|
|
|
|
|
return wrapped
|
|
|
|
|
|
|
|
|
2017-03-22 07:54:20 -06:00
|
|
|
class CacheListDescriptor(_CacheDescriptorBase):
|
2015-08-11 10:59:32 -06:00
|
|
|
"""Wraps an existing cache to support bulk fetching of keys.
|
|
|
|
|
|
|
|
Given a list of keys it looks in the cache to find any hits, then passes
|
2017-03-30 06:22:24 -06:00
|
|
|
the list of missing keys to the wrapped function.
|
|
|
|
|
|
|
|
Once wrapped, the function returns either a Deferred which resolves to
|
|
|
|
the list of results, or (if all results were cached), just the list of
|
|
|
|
results.
|
2015-08-11 10:59:32 -06:00
|
|
|
"""
|
|
|
|
|
2017-03-22 07:54:20 -06:00
|
|
|
def __init__(self, orig, cached_method_name, list_name, num_args=None,
|
2016-04-06 06:08:05 -06:00
|
|
|
inlineCallbacks=False):
|
2015-08-11 10:59:32 -06:00
|
|
|
"""
|
|
|
|
Args:
|
|
|
|
orig (function)
|
2017-03-22 07:54:20 -06:00
|
|
|
cached_method_name (str): The name of the chached method.
|
2015-08-11 10:59:32 -06:00
|
|
|
list_name (str): Name of the argument which is the bulk lookup list
|
2017-03-22 07:54:20 -06:00
|
|
|
num_args (int): number of positional arguments (excluding ``self``,
|
|
|
|
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
|
|
|
inlineCallbacks (bool): Whether orig is a generator that should
|
|
|
|
be wrapped by defer.inlineCallbacks
|
|
|
|
"""
|
2017-03-22 07:54:20 -06:00
|
|
|
super(CacheListDescriptor, self).__init__(
|
|
|
|
orig, num_args=num_args, inlineCallbacks=inlineCallbacks)
|
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
|
|
|
)
|
|
|
|
|
|
|
|
def __get__(self, obj, objtype=None):
|
2017-05-22 08:04:42 -06:00
|
|
|
cached_method = getattr(obj, self.cached_method_name)
|
|
|
|
cache = cached_method.cache
|
|
|
|
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)
|
|
|
|
def wrapped(*args, **kwargs):
|
2016-08-19 08:13:58 -06:00
|
|
|
# If we're passed a cache_context then we'll want to call its invalidate()
|
|
|
|
# whenever we are invalidated
|
|
|
|
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]
|
|
|
|
|
|
|
|
# cached is a dict arg -> deferred, where deferred results in a
|
|
|
|
# 2-tuple (`arg`, `result`)
|
2016-06-01 11:01:22 -06:00
|
|
|
results = {}
|
|
|
|
cached_defers = {}
|
2015-08-11 10:59:32 -06:00
|
|
|
missing = []
|
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:
|
|
|
|
def cache_get(arg):
|
|
|
|
return cache.get(arg, callback=invalidate_callback)
|
|
|
|
else:
|
|
|
|
key = list(keyargs)
|
|
|
|
|
|
|
|
def cache_get(arg):
|
|
|
|
key[self.list_pos] = arg
|
|
|
|
return cache.get(tuple(key), callback=invalidate_callback)
|
|
|
|
|
2015-08-11 10:59:32 -06:00
|
|
|
for arg in list_args:
|
|
|
|
try:
|
2017-05-22 08:12:19 -06:00
|
|
|
res = cache_get(arg)
|
2017-05-22 08:04:42 -06:00
|
|
|
|
2017-04-25 03:23:11 -06:00
|
|
|
if not isinstance(res, ObservableDeferred):
|
|
|
|
results[arg] = res
|
|
|
|
elif not res.has_succeeded():
|
2016-06-01 11:01:22 -06:00
|
|
|
res = res.observe()
|
|
|
|
res.addCallback(lambda r, arg: (arg, r), arg)
|
|
|
|
cached_defers[arg] = res
|
|
|
|
else:
|
2016-06-02 04:52:32 -06:00
|
|
|
results[arg] = res.get_result()
|
2015-08-11 10:59:32 -06:00
|
|
|
except KeyError:
|
|
|
|
missing.append(arg)
|
|
|
|
|
|
|
|
if missing:
|
|
|
|
args_to_call = dict(arg_dict)
|
|
|
|
args_to_call[self.list_name] = missing
|
|
|
|
|
|
|
|
ret_d = defer.maybeDeferred(
|
2017-03-30 06:22:24 -06:00
|
|
|
logcontext.preserve_fn(self.function_to_call),
|
2015-08-11 10:59:32 -06:00
|
|
|
**args_to_call
|
|
|
|
)
|
|
|
|
|
|
|
|
ret_d = ObservableDeferred(ret_d)
|
|
|
|
|
|
|
|
# We need to create deferreds for each arg in the list so that
|
|
|
|
# we can insert the new deferred into the cache.
|
|
|
|
for arg in missing:
|
2017-03-30 06:22:24 -06:00
|
|
|
observer = ret_d.observe()
|
2015-08-18 04:11:33 -06:00
|
|
|
observer.addCallback(lambda r, arg: r.get(arg, None), arg)
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
observer = ObservableDeferred(observer)
|
|
|
|
|
2017-05-22 08:04:42 -06:00
|
|
|
if num_args == 1:
|
|
|
|
cache.set(
|
|
|
|
arg, observer,
|
|
|
|
callback=invalidate_callback
|
|
|
|
)
|
|
|
|
|
|
|
|
def invalidate(f, key):
|
|
|
|
cache.invalidate(key)
|
|
|
|
return f
|
|
|
|
observer.addErrback(invalidate, arg)
|
|
|
|
else:
|
|
|
|
key = list(keyargs)
|
|
|
|
key[self.list_pos] = arg
|
|
|
|
cache.set(
|
|
|
|
tuple(key), observer,
|
|
|
|
callback=invalidate_callback
|
|
|
|
)
|
|
|
|
|
|
|
|
def invalidate(f, key):
|
|
|
|
cache.invalidate(key)
|
|
|
|
return f
|
|
|
|
observer.addErrback(invalidate, tuple(key))
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
res = observer.observe()
|
|
|
|
res.addCallback(lambda r, arg: (arg, r), arg)
|
|
|
|
|
2016-06-01 11:01:22 -06:00
|
|
|
cached_defers[arg] = res
|
|
|
|
|
|
|
|
if cached_defers:
|
2016-06-03 04:47:07 -06:00
|
|
|
def update_results_dict(res):
|
|
|
|
results.update(res)
|
|
|
|
return results
|
|
|
|
|
2017-03-30 06:22:24 -06:00
|
|
|
return logcontext.make_deferred_yieldable(defer.gatherResults(
|
2018-05-31 03:03:47 -06:00
|
|
|
list(cached_defers.values()),
|
2016-06-01 11:01:22 -06:00
|
|
|
consumeErrors=True,
|
2016-06-03 04:47:07 -06:00
|
|
|
).addCallback(update_results_dict).addErrback(
|
2016-06-01 11:01:22 -06:00
|
|
|
unwrapFirstError
|
2016-06-03 04:47:07 -06:00
|
|
|
))
|
2016-06-01 11:01:22 -06:00
|
|
|
else:
|
|
|
|
return results
|
2015-08-11 10:59:32 -06:00
|
|
|
|
|
|
|
obj.__dict__[self.orig.__name__] = wrapped
|
|
|
|
|
|
|
|
return wrapped
|
|
|
|
|
|
|
|
|
2016-08-19 08:58:52 -06:00
|
|
|
class _CacheContext(namedtuple("_CacheContext", ("cache", "key"))):
|
2017-02-02 06:50:22 -07:00
|
|
|
# We rely on _CacheContext implementing __eq__ and __hash__ sensibly,
|
2017-02-02 07:47:15 -07:00
|
|
|
# which namedtuple does for us (i.e. two _CacheContext are the same if
|
|
|
|
# their caches and keys match). This is important in particular to
|
|
|
|
# dedupe when we add callbacks to lru cache nodes, otherwise the number
|
|
|
|
# of callbacks would grow.
|
2016-08-19 04:18:26 -06:00
|
|
|
def invalidate(self):
|
|
|
|
self.cache.invalidate(self.key)
|
|
|
|
|
|
|
|
|
2017-03-22 07:54:20 -06:00
|
|
|
def cached(max_entries=1000, num_args=None, tree=False, cache_context=False,
|
2017-01-13 10:46:17 -07:00
|
|
|
iterable=False):
|
2015-08-11 10:59:32 -06:00
|
|
|
return lambda orig: CacheDescriptor(
|
|
|
|
orig,
|
|
|
|
max_entries=max_entries,
|
|
|
|
num_args=num_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,
|
2015-08-11 10:59:32 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2017-03-22 07:54:20 -06:00
|
|
|
def cachedInlineCallbacks(max_entries=1000, num_args=None, tree=False,
|
|
|
|
cache_context=False, iterable=False):
|
2015-08-11 10:59:32 -06:00
|
|
|
return lambda orig: CacheDescriptor(
|
|
|
|
orig,
|
|
|
|
max_entries=max_entries,
|
|
|
|
num_args=num_args,
|
2016-01-22 05:10:33 -07:00
|
|
|
tree=tree,
|
2015-08-11 10:59:32 -06:00
|
|
|
inlineCallbacks=True,
|
2016-08-19 08:02:38 -06:00
|
|
|
cache_context=cache_context,
|
2017-01-13 10:46:17 -07:00
|
|
|
iterable=iterable,
|
2015-08-11 10:59:32 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2017-03-22 07:54:20 -06:00
|
|
|
def cachedList(cached_method_name, list_name, num_args=None, inlineCallbacks=False):
|
2015-08-12 09:42:46 -06:00
|
|
|
"""Creates a descriptor that wraps a function in a `CacheListDescriptor`.
|
|
|
|
|
|
|
|
Used to do batch lookups for an already created cache. A single argument
|
|
|
|
is specified as a list that is iterated through to lookup keys in the
|
|
|
|
original cache. A new list consisting of the keys that weren't in the cache
|
|
|
|
get passed to the original function, the result of which is stored in the
|
|
|
|
cache.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
cache (Cache): The underlying cache to use.
|
|
|
|
list_name (str): The name of the argument that is the list to use to
|
|
|
|
do batch lookups in the cache.
|
2017-03-22 07:54:20 -06:00
|
|
|
num_args (int): Number of arguments to use as the key in the cache
|
|
|
|
(including list_name). Defaults to all named parameters.
|
2015-08-12 09:42:46 -06:00
|
|
|
inlineCallbacks (bool): Should the function be wrapped in an
|
|
|
|
`defer.inlineCallbacks`?
|
|
|
|
|
|
|
|
Example:
|
|
|
|
|
|
|
|
class Example(object):
|
|
|
|
@cached(num_args=2)
|
|
|
|
def do_something(self, first_arg):
|
|
|
|
...
|
|
|
|
|
|
|
|
@cachedList(do_something.cache, list_name="second_args", num_args=2)
|
|
|
|
def batch_do_something(self, first_arg, second_args):
|
|
|
|
...
|
|
|
|
"""
|
2015-08-11 10:59:32 -06:00
|
|
|
return lambda orig: CacheListDescriptor(
|
|
|
|
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,
|
|
|
|
inlineCallbacks=inlineCallbacks,
|
|
|
|
)
|