2015-08-11 18:59:32 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
2016-01-07 05:26:29 +01:00
|
|
|
# Copyright 2015, 2016 OpenMarket Ltd
|
2015-08-11 18:59:32 +02: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.
|
|
|
|
import logging
|
|
|
|
|
|
|
|
from synapse.util.async import ObservableDeferred
|
|
|
|
from synapse.util import unwrapFirstError
|
|
|
|
from synapse.util.caches.lrucache import LruCache
|
2017-01-17 12:44:57 +01:00
|
|
|
from synapse.util.caches.treecache import TreeCache, iterate_tree_cache_entry
|
2016-02-04 11:22:44 +01:00
|
|
|
from synapse.util.logcontext import (
|
|
|
|
PreserveLoggingContext, preserve_context_over_deferred, preserve_context_over_fn
|
|
|
|
)
|
2015-08-12 11:13:35 +02:00
|
|
|
|
2016-06-02 12:29:44 +02:00
|
|
|
from . import DEBUG_CACHES, register_cache
|
2015-08-11 18:59:32 +02:00
|
|
|
|
|
|
|
from twisted.internet import defer
|
2016-08-19 16:58:52 +02:00
|
|
|
from collections import namedtuple
|
2015-08-11 18:59:32 +02:00
|
|
|
|
2016-03-01 13:56:39 +01:00
|
|
|
import os
|
2015-08-11 18:59:32 +02:00
|
|
|
import functools
|
|
|
|
import inspect
|
|
|
|
import threading
|
|
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
_CacheSentinel = object()
|
|
|
|
|
|
|
|
|
2016-03-01 13:56:39 +01:00
|
|
|
CACHE_SIZE_FACTOR = float(os.environ.get("SYNAPSE_CACHE_FACTOR", 0.1))
|
|
|
|
|
|
|
|
|
2017-01-17 12:18:13 +01:00
|
|
|
class CacheEntry(object):
|
|
|
|
__slots__ = [
|
|
|
|
"deferred", "sequence", "callbacks", "invalidated"
|
|
|
|
]
|
|
|
|
|
|
|
|
def __init__(self, deferred, sequence, callbacks):
|
|
|
|
self.deferred = deferred
|
|
|
|
self.sequence = sequence
|
|
|
|
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 18:46:17 +01:00
|
|
|
|
|
|
|
|
2015-08-11 18:59:32 +02:00
|
|
|
class Cache(object):
|
2016-06-02 12:29:44 +02:00
|
|
|
__slots__ = (
|
|
|
|
"cache",
|
|
|
|
"max_entries",
|
|
|
|
"name",
|
|
|
|
"keylen",
|
|
|
|
"sequence",
|
|
|
|
"thread",
|
|
|
|
"metrics",
|
2017-01-17 12:18:13 +01:00
|
|
|
"_pending_deferred_cache",
|
2016-06-02 12:29:44 +02:00
|
|
|
)
|
2015-08-11 18:59:32 +02:00
|
|
|
|
2017-01-13 18:46:17 +01:00
|
|
|
def __init__(self, name, max_entries=1000, keylen=1, tree=False, iterable=False):
|
2016-08-19 12:59:29 +02:00
|
|
|
cache_type = TreeCache if tree else dict
|
2017-01-17 12:18:13 +01:00
|
|
|
self._pending_deferred_cache = cache_type()
|
|
|
|
|
2016-08-19 12:59:29 +02:00
|
|
|
self.cache = LruCache(
|
2017-01-13 18:46:17 +01:00
|
|
|
max_size=max_entries, keylen=keylen, cache_type=cache_type,
|
2017-01-17 12:18:13 +01:00
|
|
|
size_callback=(lambda d: len(d.result)) if iterable else None,
|
2016-08-19 12:59:29 +02:00
|
|
|
)
|
2015-08-11 18:59:32 +02:00
|
|
|
|
|
|
|
self.name = name
|
|
|
|
self.keylen = keylen
|
|
|
|
self.sequence = 0
|
|
|
|
self.thread = None
|
2016-06-02 12:29:44 +02:00
|
|
|
self.metrics = register_cache(name, self.cache)
|
2015-08-11 18:59:32 +02: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"
|
|
|
|
)
|
|
|
|
|
2016-08-19 12:18:26 +02:00
|
|
|
def get(self, key, default=_CacheSentinel, callback=None):
|
2017-01-17 12:18:13 +01:00
|
|
|
callbacks = [callback] if callback else []
|
|
|
|
val = self._pending_deferred_cache.get(key, _CacheSentinel)
|
|
|
|
if val is not _CacheSentinel:
|
|
|
|
if val.sequence == self.sequence:
|
|
|
|
val.callbacks.update(callbacks)
|
|
|
|
self.metrics.inc_hits()
|
|
|
|
return val.deferred
|
|
|
|
|
|
|
|
val = self.cache.get(key, _CacheSentinel, callbacks=callbacks)
|
2015-08-11 18:59:32 +02:00
|
|
|
if val is not _CacheSentinel:
|
2016-06-02 12:29:44 +02:00
|
|
|
self.metrics.inc_hits()
|
2015-08-11 18:59:32 +02:00
|
|
|
return val
|
|
|
|
|
2016-06-02 12:29:44 +02:00
|
|
|
self.metrics.inc_misses()
|
2015-08-11 18:59:32 +02:00
|
|
|
|
|
|
|
if default is _CacheSentinel:
|
|
|
|
raise KeyError()
|
|
|
|
else:
|
|
|
|
return default
|
|
|
|
|
2017-01-17 12:18:13 +01:00
|
|
|
def set(self, key, value, callback=None):
|
|
|
|
callbacks = [callback] if callback else []
|
2015-08-11 18:59:32 +02:00
|
|
|
self.check_thread()
|
2017-01-17 12:18:13 +01:00
|
|
|
entry = CacheEntry(
|
|
|
|
deferred=value,
|
|
|
|
sequence=self.sequence,
|
|
|
|
callbacks=callbacks,
|
|
|
|
)
|
|
|
|
|
|
|
|
entry.callbacks.update(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):
|
|
|
|
if self.sequence == entry.sequence:
|
|
|
|
existing_entry = self._pending_deferred_cache.pop(key, None)
|
|
|
|
if existing_entry is entry:
|
|
|
|
self.cache.set(key, entry.deferred, entry.callbacks)
|
|
|
|
else:
|
|
|
|
entry.invalidate()
|
|
|
|
else:
|
|
|
|
entry.invalidate()
|
|
|
|
return result
|
|
|
|
|
|
|
|
entry.deferred.addCallback(shuffle)
|
2015-08-11 18:59:32 +02:00
|
|
|
|
2016-08-19 12:18:26 +02:00
|
|
|
def prefill(self, key, value, callback=None):
|
2017-01-17 12:18:13 +01:00
|
|
|
callbacks = [callback] if callback else []
|
|
|
|
self.cache.set(key, value, callbacks=callbacks)
|
2015-08-11 18:59:32 +02:00
|
|
|
|
|
|
|
def invalidate(self, key):
|
|
|
|
self.check_thread()
|
|
|
|
if not isinstance(key, tuple):
|
2015-08-12 11:30:30 +02:00
|
|
|
raise TypeError(
|
|
|
|
"The cache key must be a tuple not %r" % (type(key),)
|
|
|
|
)
|
2015-08-11 18:59:32 +02:00
|
|
|
|
|
|
|
# Increment the sequence number so that any SELECT statements that
|
|
|
|
# raced with the INSERT don't update the cache (SYN-369)
|
|
|
|
self.sequence += 1
|
2017-01-17 12:18:13 +01:00
|
|
|
entry = self._pending_deferred_cache.pop(key, None)
|
|
|
|
if entry:
|
|
|
|
entry.invalidate()
|
|
|
|
|
2015-08-11 18:59:32 +02:00
|
|
|
self.cache.pop(key, None)
|
|
|
|
|
2016-01-21 20:16:25 +01: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.sequence += 1
|
|
|
|
self.cache.del_multi(key)
|
|
|
|
|
2017-01-17 15:43:32 +01:00
|
|
|
entry_dict = self._pending_deferred_cache.pop(key, None)
|
|
|
|
if entry_dict is not None:
|
2017-01-17 12:44:57 +01:00
|
|
|
for entry in iterate_tree_cache_entry(entry_dict):
|
2017-01-17 12:18:13 +01:00
|
|
|
entry.invalidate()
|
|
|
|
|
2015-08-11 18:59:32 +02:00
|
|
|
def invalidate_all(self):
|
|
|
|
self.check_thread()
|
|
|
|
self.sequence += 1
|
|
|
|
self.cache.clear()
|
|
|
|
|
|
|
|
|
|
|
|
class CacheDescriptor(object):
|
|
|
|
""" 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 12:18:26 +02: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 16:02:38 +02:00
|
|
|
@cachedInlineCallbacks(cache_context=True)
|
2016-08-19 12:18:26 +02:00
|
|
|
def foo(self, key, cache_context):
|
2016-08-19 16:13:58 +02:00
|
|
|
r1 = yield self.bar1(key, on_invalidate=cache_context.invalidate)
|
|
|
|
r2 = yield self.bar2(key, on_invalidate=cache_context.invalidate)
|
2016-08-19 12:18:26 +02:00
|
|
|
defer.returnValue(r1 + r2)
|
|
|
|
|
2015-08-11 18:59:32 +02:00
|
|
|
"""
|
2016-08-19 12:59:29 +02:00
|
|
|
def __init__(self, orig, max_entries=1000, num_args=1, tree=False,
|
2017-01-13 18:46:17 +01:00
|
|
|
inlineCallbacks=False, cache_context=False, iterable=False):
|
2016-03-01 14:21:46 +01:00
|
|
|
max_entries = int(max_entries * CACHE_SIZE_FACTOR)
|
|
|
|
|
2015-08-11 18:59:32 +02:00
|
|
|
self.orig = orig
|
|
|
|
|
|
|
|
if inlineCallbacks:
|
|
|
|
self.function_to_call = defer.inlineCallbacks(orig)
|
|
|
|
else:
|
|
|
|
self.function_to_call = orig
|
|
|
|
|
|
|
|
self.max_entries = max_entries
|
|
|
|
self.num_args = num_args
|
2016-01-22 13:10:33 +01:00
|
|
|
self.tree = tree
|
2015-08-11 18:59:32 +02:00
|
|
|
|
2017-01-13 18:46:17 +01:00
|
|
|
self.iterable = iterable
|
|
|
|
|
2016-08-19 12:18:26 +02:00
|
|
|
all_args = inspect.getargspec(orig)
|
|
|
|
self.arg_names = all_args.args[1:num_args + 1]
|
|
|
|
|
2016-08-19 16:02:38 +02:00
|
|
|
if "cache_context" in all_args.args:
|
|
|
|
if not cache_context:
|
|
|
|
raise ValueError(
|
|
|
|
"Cannot have a 'cache_context' arg without setting"
|
|
|
|
" cache_context=True"
|
|
|
|
)
|
|
|
|
try:
|
|
|
|
self.arg_names.remove("cache_context")
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
elif cache_context:
|
|
|
|
raise ValueError(
|
|
|
|
"Cannot have cache_context=True without having an arg"
|
|
|
|
" named `cache_context`"
|
|
|
|
)
|
2016-08-19 12:18:26 +02:00
|
|
|
|
2016-08-19 16:02:38 +02:00
|
|
|
self.add_cache_context = cache_context
|
2015-08-11 18:59:32 +02:00
|
|
|
|
|
|
|
if len(self.arg_names) < self.num_args:
|
|
|
|
raise Exception(
|
|
|
|
"Not enough explicit positional arguments to key off of for %r."
|
2016-08-19 16:02:38 +02:00
|
|
|
" (@cached cannot key off of *args or **kwargs)"
|
2015-08-11 18:59:32 +02:00
|
|
|
% (orig.__name__,)
|
|
|
|
)
|
|
|
|
|
2016-04-06 14:08:05 +02:00
|
|
|
def __get__(self, obj, objtype=None):
|
|
|
|
cache = Cache(
|
2015-08-11 18:59:32 +02:00
|
|
|
name=self.orig.__name__,
|
|
|
|
max_entries=self.max_entries,
|
|
|
|
keylen=self.num_args,
|
2016-01-22 13:10:33 +01:00
|
|
|
tree=self.tree,
|
2017-01-13 18:46:17 +01:00
|
|
|
iterable=self.iterable,
|
2015-08-11 18:59:32 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
@functools.wraps(self.orig)
|
|
|
|
def wrapped(*args, **kwargs):
|
2016-08-19 16:02:38 +02:00
|
|
|
# If we're passed a cache_context then we'll want to call its invalidate()
|
|
|
|
# whenever we are invalidated
|
2016-08-19 16:13:58 +02:00
|
|
|
invalidate_callback = kwargs.pop("on_invalidate", None)
|
2016-08-19 12:18:26 +02:00
|
|
|
|
2016-08-19 16:58:52 +02:00
|
|
|
# Add temp cache_context so inspect.getcallargs doesn't explode
|
2016-08-19 12:18:26 +02:00
|
|
|
if self.add_cache_context:
|
2016-08-19 16:58:52 +02:00
|
|
|
kwargs["cache_context"] = None
|
2016-08-19 12:18:26 +02:00
|
|
|
|
2015-08-11 18:59:32 +02:00
|
|
|
arg_dict = inspect.getcallargs(self.orig, obj, *args, **kwargs)
|
|
|
|
cache_key = tuple(arg_dict[arg_nm] for arg_nm in self.arg_names)
|
2016-08-19 12:18:26 +02:00
|
|
|
|
2016-08-19 16:58:52 +02: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 12:18:26 +02:00
|
|
|
|
2015-08-11 18:59:32 +02:00
|
|
|
try:
|
2016-08-19 16:13:58 +02:00
|
|
|
cached_result_d = cache.get(cache_key, callback=invalidate_callback)
|
2015-08-11 18:59:32 +02:00
|
|
|
|
|
|
|
observer = cached_result_d.observe()
|
|
|
|
if DEBUG_CACHES:
|
|
|
|
@defer.inlineCallbacks
|
|
|
|
def check_result(cached_result):
|
|
|
|
actual_result = yield self.function_to_call(obj, *args, **kwargs)
|
|
|
|
if actual_result != cached_result:
|
|
|
|
logger.error(
|
|
|
|
"Stale cache entry %s%r: cached: %r, actual %r",
|
|
|
|
self.orig.__name__, cache_key,
|
|
|
|
cached_result, actual_result,
|
|
|
|
)
|
|
|
|
raise ValueError("Stale cache entry")
|
|
|
|
defer.returnValue(cached_result)
|
|
|
|
observer.addCallback(check_result)
|
|
|
|
|
2016-02-04 11:22:44 +01:00
|
|
|
return preserve_context_over_deferred(observer)
|
2015-08-11 18:59:32 +02:00
|
|
|
except KeyError:
|
|
|
|
ret = defer.maybeDeferred(
|
2016-02-04 11:22:44 +01:00
|
|
|
preserve_context_over_fn,
|
2015-08-11 18:59:32 +02:00
|
|
|
self.function_to_call,
|
|
|
|
obj, *args, **kwargs
|
|
|
|
)
|
|
|
|
|
|
|
|
def onErr(f):
|
2016-04-06 14:08:05 +02:00
|
|
|
cache.invalidate(cache_key)
|
2015-08-11 18:59:32 +02:00
|
|
|
return f
|
|
|
|
|
|
|
|
ret.addErrback(onErr)
|
|
|
|
|
|
|
|
ret = ObservableDeferred(ret, consumeErrors=True)
|
2017-01-17 12:18:13 +01:00
|
|
|
cache.set(cache_key, ret, callback=invalidate_callback)
|
2015-08-11 18:59:32 +02:00
|
|
|
|
2016-02-04 11:22:44 +01:00
|
|
|
return preserve_context_over_deferred(ret.observe())
|
2015-08-11 18:59:32 +02:00
|
|
|
|
2016-04-06 14:08:05 +02:00
|
|
|
wrapped.invalidate = cache.invalidate
|
|
|
|
wrapped.invalidate_all = cache.invalidate_all
|
|
|
|
wrapped.invalidate_many = cache.invalidate_many
|
|
|
|
wrapped.prefill = cache.prefill
|
|
|
|
wrapped.cache = cache
|
2015-08-11 18:59:32 +02:00
|
|
|
|
|
|
|
obj.__dict__[self.orig.__name__] = wrapped
|
|
|
|
|
|
|
|
return wrapped
|
|
|
|
|
|
|
|
|
|
|
|
class CacheListDescriptor(object):
|
|
|
|
"""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
|
|
|
|
the list of missing keys to the wrapped fucntion.
|
|
|
|
"""
|
|
|
|
|
2016-04-06 14:08:05 +02:00
|
|
|
def __init__(self, orig, cached_method_name, list_name, num_args=1,
|
|
|
|
inlineCallbacks=False):
|
2015-08-11 18:59:32 +02:00
|
|
|
"""
|
|
|
|
Args:
|
|
|
|
orig (function)
|
2016-04-06 14:08:05 +02:00
|
|
|
method_name (str); The name of the chached method.
|
2015-08-11 18:59:32 +02:00
|
|
|
list_name (str): Name of the argument which is the bulk lookup list
|
|
|
|
num_args (int)
|
|
|
|
inlineCallbacks (bool): Whether orig is a generator that should
|
|
|
|
be wrapped by defer.inlineCallbacks
|
|
|
|
"""
|
|
|
|
self.orig = orig
|
|
|
|
|
|
|
|
if inlineCallbacks:
|
|
|
|
self.function_to_call = defer.inlineCallbacks(orig)
|
|
|
|
else:
|
|
|
|
self.function_to_call = orig
|
|
|
|
|
|
|
|
self.num_args = num_args
|
|
|
|
self.list_name = list_name
|
|
|
|
|
2016-02-02 18:18:50 +01:00
|
|
|
self.arg_names = inspect.getargspec(orig).args[1:num_args + 1]
|
2015-08-11 18:59:32 +02:00
|
|
|
self.list_pos = self.arg_names.index(self.list_name)
|
|
|
|
|
2016-04-06 14:08:05 +02:00
|
|
|
self.cached_method_name = cached_method_name
|
2015-08-11 18:59:32 +02:00
|
|
|
|
|
|
|
self.sentinel = object()
|
|
|
|
|
|
|
|
if len(self.arg_names) < self.num_args:
|
|
|
|
raise Exception(
|
|
|
|
"Not enough explicit positional arguments to key off of for %r."
|
|
|
|
" (@cached cannot key off of *args or **kwars)"
|
|
|
|
% (orig.__name__,)
|
|
|
|
)
|
|
|
|
|
|
|
|
if self.list_name not in self.arg_names:
|
|
|
|
raise Exception(
|
|
|
|
"Couldn't see arguments %r for %r."
|
2016-04-06 14:08:05 +02:00
|
|
|
% (self.list_name, cached_method_name,)
|
2015-08-11 18:59:32 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
def __get__(self, obj, objtype=None):
|
|
|
|
|
2016-04-06 14:08:05 +02:00
|
|
|
cache = getattr(obj, self.cached_method_name).cache
|
|
|
|
|
2015-08-11 18:59:32 +02:00
|
|
|
@functools.wraps(self.orig)
|
|
|
|
def wrapped(*args, **kwargs):
|
2016-08-19 16:13:58 +02: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 12:18:26 +02:00
|
|
|
|
2015-08-11 18:59:32 +02: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 19:01:22 +02:00
|
|
|
results = {}
|
|
|
|
cached_defers = {}
|
2015-08-11 18:59:32 +02:00
|
|
|
missing = []
|
|
|
|
for arg in list_args:
|
|
|
|
key = list(keyargs)
|
|
|
|
key[self.list_pos] = arg
|
|
|
|
|
|
|
|
try:
|
2016-08-19 16:13:58 +02:00
|
|
|
res = cache.get(tuple(key), callback=invalidate_callback)
|
2016-06-02 12:52:32 +02:00
|
|
|
if not res.has_succeeded():
|
2016-06-01 19:01:22 +02:00
|
|
|
res = res.observe()
|
|
|
|
res.addCallback(lambda r, arg: (arg, r), arg)
|
|
|
|
cached_defers[arg] = res
|
|
|
|
else:
|
2016-06-02 12:52:32 +02:00
|
|
|
results[arg] = res.get_result()
|
2015-08-11 18:59:32 +02: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(
|
2016-02-04 11:22:44 +01:00
|
|
|
preserve_context_over_fn,
|
2015-08-11 18:59:32 +02:00
|
|
|
self.function_to_call,
|
|
|
|
**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:
|
2016-02-04 11:22:44 +01:00
|
|
|
with PreserveLoggingContext():
|
|
|
|
observer = ret_d.observe()
|
2015-08-18 12:11:33 +02:00
|
|
|
observer.addCallback(lambda r, arg: r.get(arg, None), arg)
|
2015-08-11 18:59:32 +02:00
|
|
|
|
|
|
|
observer = ObservableDeferred(observer)
|
|
|
|
|
|
|
|
key = list(keyargs)
|
|
|
|
key[self.list_pos] = arg
|
2017-01-17 12:18:13 +01:00
|
|
|
cache.set(
|
|
|
|
tuple(key), observer,
|
2016-08-19 16:13:58 +02:00
|
|
|
callback=invalidate_callback
|
2016-08-19 12:18:26 +02:00
|
|
|
)
|
2015-08-11 18:59:32 +02:00
|
|
|
|
|
|
|
def invalidate(f, key):
|
2016-04-06 14:08:05 +02:00
|
|
|
cache.invalidate(key)
|
2015-08-11 18:59:32 +02:00
|
|
|
return f
|
|
|
|
observer.addErrback(invalidate, tuple(key))
|
|
|
|
|
|
|
|
res = observer.observe()
|
|
|
|
res.addCallback(lambda r, arg: (arg, r), arg)
|
|
|
|
|
2016-06-01 19:01:22 +02:00
|
|
|
cached_defers[arg] = res
|
|
|
|
|
|
|
|
if cached_defers:
|
2016-06-03 12:47:07 +02:00
|
|
|
def update_results_dict(res):
|
|
|
|
results.update(res)
|
|
|
|
return results
|
|
|
|
|
2016-06-01 19:01:22 +02:00
|
|
|
return preserve_context_over_deferred(defer.gatherResults(
|
|
|
|
cached_defers.values(),
|
|
|
|
consumeErrors=True,
|
2016-06-03 12:47:07 +02:00
|
|
|
).addCallback(update_results_dict).addErrback(
|
2016-06-01 19:01:22 +02:00
|
|
|
unwrapFirstError
|
2016-06-03 12:47:07 +02:00
|
|
|
))
|
2016-06-01 19:01:22 +02:00
|
|
|
else:
|
|
|
|
return results
|
2015-08-11 18:59:32 +02:00
|
|
|
|
|
|
|
obj.__dict__[self.orig.__name__] = wrapped
|
|
|
|
|
|
|
|
return wrapped
|
|
|
|
|
|
|
|
|
2016-08-19 16:58:52 +02:00
|
|
|
class _CacheContext(namedtuple("_CacheContext", ("cache", "key"))):
|
2017-02-02 14:50:22 +01:00
|
|
|
# We rely on _CacheContext implementing __eq__ and __hash__ sensibly,
|
2017-02-02 15:47:15 +01: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 12:18:26 +02:00
|
|
|
def invalidate(self):
|
|
|
|
self.cache.invalidate(self.key)
|
|
|
|
|
|
|
|
|
2017-01-13 18:46:17 +01:00
|
|
|
def cached(max_entries=1000, num_args=1, tree=False, cache_context=False,
|
|
|
|
iterable=False):
|
2015-08-11 18:59:32 +02:00
|
|
|
return lambda orig: CacheDescriptor(
|
|
|
|
orig,
|
|
|
|
max_entries=max_entries,
|
|
|
|
num_args=num_args,
|
2016-01-22 13:10:33 +01:00
|
|
|
tree=tree,
|
2016-08-19 16:02:38 +02:00
|
|
|
cache_context=cache_context,
|
2017-01-13 18:46:17 +01:00
|
|
|
iterable=iterable,
|
2015-08-11 18:59:32 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2017-01-13 18:46:17 +01:00
|
|
|
def cachedInlineCallbacks(max_entries=1000, num_args=1, tree=False, cache_context=False,
|
|
|
|
iterable=False):
|
2015-08-11 18:59:32 +02:00
|
|
|
return lambda orig: CacheDescriptor(
|
|
|
|
orig,
|
|
|
|
max_entries=max_entries,
|
|
|
|
num_args=num_args,
|
2016-01-22 13:10:33 +01:00
|
|
|
tree=tree,
|
2015-08-11 18:59:32 +02:00
|
|
|
inlineCallbacks=True,
|
2016-08-19 16:02:38 +02:00
|
|
|
cache_context=cache_context,
|
2017-01-13 18:46:17 +01:00
|
|
|
iterable=iterable,
|
2015-08-11 18:59:32 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2016-04-06 14:08:05 +02:00
|
|
|
def cachedList(cached_method_name, list_name, num_args=1, inlineCallbacks=False):
|
2015-08-12 17:42:46 +02: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.
|
|
|
|
num_args (int): Number of arguments to use as the key in the cache.
|
|
|
|
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 18:59:32 +02:00
|
|
|
return lambda orig: CacheListDescriptor(
|
|
|
|
orig,
|
2016-04-06 14:08:05 +02:00
|
|
|
cached_method_name=cached_method_name,
|
2015-08-11 18:59:32 +02:00
|
|
|
list_name=list_name,
|
|
|
|
num_args=num_args,
|
|
|
|
inlineCallbacks=inlineCallbacks,
|
|
|
|
)
|