descriptors.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import functools
  17. import inspect
  18. import logging
  19. import threading
  20. from collections import namedtuple
  21. import six
  22. from six import itervalues, string_types
  23. from twisted.internet import defer
  24. from synapse.logging.context import make_deferred_yieldable, preserve_fn
  25. from synapse.util import unwrapFirstError
  26. from synapse.util.async_helpers import ObservableDeferred
  27. from synapse.util.caches import get_cache_factor_for
  28. from synapse.util.caches.lrucache import LruCache
  29. from synapse.util.caches.treecache import TreeCache, iterate_tree_cache_entry
  30. from synapse.util.stringutils import to_ascii
  31. from . import register_cache
  32. logger = logging.getLogger(__name__)
  33. _CacheSentinel = object()
  34. class CacheEntry(object):
  35. __slots__ = ["deferred", "callbacks", "invalidated"]
  36. def __init__(self, deferred, callbacks):
  37. self.deferred = deferred
  38. self.callbacks = set(callbacks)
  39. self.invalidated = False
  40. def invalidate(self):
  41. if not self.invalidated:
  42. self.invalidated = True
  43. for callback in self.callbacks:
  44. callback()
  45. self.callbacks.clear()
  46. class Cache(object):
  47. __slots__ = (
  48. "cache",
  49. "max_entries",
  50. "name",
  51. "keylen",
  52. "thread",
  53. "metrics",
  54. "_pending_deferred_cache",
  55. )
  56. def __init__(self, name, max_entries=1000, keylen=1, tree=False, iterable=False):
  57. cache_type = TreeCache if tree else dict
  58. self._pending_deferred_cache = cache_type()
  59. self.cache = LruCache(
  60. max_size=max_entries,
  61. keylen=keylen,
  62. cache_type=cache_type,
  63. size_callback=(lambda d: len(d)) if iterable else None,
  64. evicted_callback=self._on_evicted,
  65. )
  66. self.name = name
  67. self.keylen = keylen
  68. self.thread = None
  69. self.metrics = register_cache("cache", name, self.cache)
  70. def _on_evicted(self, evicted_count):
  71. self.metrics.inc_evictions(evicted_count)
  72. def check_thread(self):
  73. expected_thread = self.thread
  74. if expected_thread is None:
  75. self.thread = threading.current_thread()
  76. else:
  77. if expected_thread is not threading.current_thread():
  78. raise ValueError(
  79. "Cache objects can only be accessed from the main thread"
  80. )
  81. def get(self, key, default=_CacheSentinel, callback=None, update_metrics=True):
  82. """Looks the key up in the caches.
  83. Args:
  84. key(tuple)
  85. default: What is returned if key is not in the caches. If not
  86. specified then function throws KeyError instead
  87. callback(fn): Gets called when the entry in the cache is invalidated
  88. update_metrics (bool): whether to update the cache hit rate metrics
  89. Returns:
  90. Either a Deferred or the raw result
  91. """
  92. callbacks = [callback] if callback else []
  93. val = self._pending_deferred_cache.get(key, _CacheSentinel)
  94. if val is not _CacheSentinel:
  95. val.callbacks.update(callbacks)
  96. if update_metrics:
  97. self.metrics.inc_hits()
  98. return val.deferred
  99. val = self.cache.get(key, _CacheSentinel, callbacks=callbacks)
  100. if val is not _CacheSentinel:
  101. self.metrics.inc_hits()
  102. return val
  103. if update_metrics:
  104. self.metrics.inc_misses()
  105. if default is _CacheSentinel:
  106. raise KeyError()
  107. else:
  108. return default
  109. def set(self, key, value, callback=None):
  110. callbacks = [callback] if callback else []
  111. self.check_thread()
  112. entry = CacheEntry(deferred=value, callbacks=callbacks)
  113. existing_entry = self._pending_deferred_cache.pop(key, None)
  114. if existing_entry:
  115. existing_entry.invalidate()
  116. self._pending_deferred_cache[key] = entry
  117. def shuffle(result):
  118. existing_entry = self._pending_deferred_cache.pop(key, None)
  119. if existing_entry is entry:
  120. self.cache.set(key, result, entry.callbacks)
  121. else:
  122. # oops, the _pending_deferred_cache has been updated since
  123. # we started our query, so we are out of date.
  124. #
  125. # Better put back whatever we took out. (We do it this way
  126. # round, rather than peeking into the _pending_deferred_cache
  127. # and then removing on a match, to make the common case faster)
  128. if existing_entry is not None:
  129. self._pending_deferred_cache[key] = existing_entry
  130. # we're not going to put this entry into the cache, so need
  131. # to make sure that the invalidation callbacks are called.
  132. # That was probably done when _pending_deferred_cache was
  133. # updated, but it's possible that `set` was called without
  134. # `invalidate` being previously called, in which case it may
  135. # not have been. Either way, let's double-check now.
  136. entry.invalidate()
  137. return result
  138. entry.deferred.addCallback(shuffle)
  139. def prefill(self, key, value, callback=None):
  140. callbacks = [callback] if callback else []
  141. self.cache.set(key, value, callbacks=callbacks)
  142. def invalidate(self, key):
  143. self.check_thread()
  144. self.cache.pop(key, None)
  145. # if we have a pending lookup for this key, remove it from the
  146. # _pending_deferred_cache, which will (a) stop it being returned
  147. # for future queries and (b) stop it being persisted as a proper entry
  148. # in self.cache.
  149. entry = self._pending_deferred_cache.pop(key, None)
  150. # run the invalidation callbacks now, rather than waiting for the
  151. # deferred to resolve.
  152. if entry:
  153. entry.invalidate()
  154. def invalidate_many(self, key):
  155. self.check_thread()
  156. if not isinstance(key, tuple):
  157. raise TypeError("The cache key must be a tuple not %r" % (type(key),))
  158. self.cache.del_multi(key)
  159. # if we have a pending lookup for this key, remove it from the
  160. # _pending_deferred_cache, as above
  161. entry_dict = self._pending_deferred_cache.pop(key, None)
  162. if entry_dict is not None:
  163. for entry in iterate_tree_cache_entry(entry_dict):
  164. entry.invalidate()
  165. def invalidate_all(self):
  166. self.check_thread()
  167. self.cache.clear()
  168. for entry in itervalues(self._pending_deferred_cache):
  169. entry.invalidate()
  170. self._pending_deferred_cache.clear()
  171. class _CacheDescriptorBase(object):
  172. def __init__(self, orig, num_args, inlineCallbacks, cache_context=False):
  173. self.orig = orig
  174. if inlineCallbacks:
  175. self.function_to_call = defer.inlineCallbacks(orig)
  176. else:
  177. self.function_to_call = orig
  178. arg_spec = inspect.getargspec(orig)
  179. all_args = arg_spec.args
  180. if "cache_context" in all_args:
  181. if not cache_context:
  182. raise ValueError(
  183. "Cannot have a 'cache_context' arg without setting"
  184. " cache_context=True"
  185. )
  186. elif cache_context:
  187. raise ValueError(
  188. "Cannot have cache_context=True without having an arg"
  189. " named `cache_context`"
  190. )
  191. if num_args is None:
  192. num_args = len(all_args) - 1
  193. if cache_context:
  194. num_args -= 1
  195. if len(all_args) < num_args + 1:
  196. raise Exception(
  197. "Not enough explicit positional arguments to key off for %r: "
  198. "got %i args, but wanted %i. (@cached cannot key off *args or "
  199. "**kwargs)" % (orig.__name__, len(all_args), num_args)
  200. )
  201. self.num_args = num_args
  202. # list of the names of the args used as the cache key
  203. self.arg_names = all_args[1 : num_args + 1]
  204. # self.arg_defaults is a map of arg name to its default value for each
  205. # argument that has a default value
  206. if arg_spec.defaults:
  207. self.arg_defaults = dict(
  208. zip(all_args[-len(arg_spec.defaults) :], arg_spec.defaults)
  209. )
  210. else:
  211. self.arg_defaults = {}
  212. if "cache_context" in self.arg_names:
  213. raise Exception("cache_context arg cannot be included among the cache keys")
  214. self.add_cache_context = cache_context
  215. class CacheDescriptor(_CacheDescriptorBase):
  216. """ A method decorator that applies a memoizing cache around the function.
  217. This caches deferreds, rather than the results themselves. Deferreds that
  218. fail are removed from the cache.
  219. The function is presumed to take zero or more arguments, which are used in
  220. a tuple as the key for the cache. Hits are served directly from the cache;
  221. misses use the function body to generate the value.
  222. The wrapped function has an additional member, a callable called
  223. "invalidate". This can be used to remove individual entries from the cache.
  224. The wrapped function has another additional callable, called "prefill",
  225. which can be used to insert values into the cache specifically, without
  226. calling the calculation function.
  227. Cached functions can be "chained" (i.e. a cached function can call other cached
  228. functions and get appropriately invalidated when they called caches are
  229. invalidated) by adding a special "cache_context" argument to the function
  230. and passing that as a kwarg to all caches called. For example::
  231. @cachedInlineCallbacks(cache_context=True)
  232. def foo(self, key, cache_context):
  233. r1 = yield self.bar1(key, on_invalidate=cache_context.invalidate)
  234. r2 = yield self.bar2(key, on_invalidate=cache_context.invalidate)
  235. defer.returnValue(r1 + r2)
  236. Args:
  237. num_args (int): number of positional arguments (excluding ``self`` and
  238. ``cache_context``) to use as cache keys. Defaults to all named
  239. args of the function.
  240. """
  241. def __init__(
  242. self,
  243. orig,
  244. max_entries=1000,
  245. num_args=None,
  246. tree=False,
  247. inlineCallbacks=False,
  248. cache_context=False,
  249. iterable=False,
  250. ):
  251. super(CacheDescriptor, self).__init__(
  252. orig,
  253. num_args=num_args,
  254. inlineCallbacks=inlineCallbacks,
  255. cache_context=cache_context,
  256. )
  257. max_entries = int(max_entries * get_cache_factor_for(orig.__name__))
  258. self.max_entries = max_entries
  259. self.tree = tree
  260. self.iterable = iterable
  261. def __get__(self, obj, objtype=None):
  262. cache = Cache(
  263. name=self.orig.__name__,
  264. max_entries=self.max_entries,
  265. keylen=self.num_args,
  266. tree=self.tree,
  267. iterable=self.iterable,
  268. )
  269. def get_cache_key_gen(args, kwargs):
  270. """Given some args/kwargs return a generator that resolves into
  271. the cache_key.
  272. We loop through each arg name, looking up if its in the `kwargs`,
  273. otherwise using the next argument in `args`. If there are no more
  274. args then we try looking the arg name up in the defaults
  275. """
  276. pos = 0
  277. for nm in self.arg_names:
  278. if nm in kwargs:
  279. yield kwargs[nm]
  280. elif pos < len(args):
  281. yield args[pos]
  282. pos += 1
  283. else:
  284. yield self.arg_defaults[nm]
  285. # By default our cache key is a tuple, but if there is only one item
  286. # then don't bother wrapping in a tuple. This is to save memory.
  287. if self.num_args == 1:
  288. nm = self.arg_names[0]
  289. def get_cache_key(args, kwargs):
  290. if nm in kwargs:
  291. return kwargs[nm]
  292. elif len(args):
  293. return args[0]
  294. else:
  295. return self.arg_defaults[nm]
  296. else:
  297. def get_cache_key(args, kwargs):
  298. return tuple(get_cache_key_gen(args, kwargs))
  299. @functools.wraps(self.orig)
  300. def wrapped(*args, **kwargs):
  301. # If we're passed a cache_context then we'll want to call its invalidate()
  302. # whenever we are invalidated
  303. invalidate_callback = kwargs.pop("on_invalidate", None)
  304. cache_key = get_cache_key(args, kwargs)
  305. # Add our own `cache_context` to argument list if the wrapped function
  306. # has asked for one
  307. if self.add_cache_context:
  308. kwargs["cache_context"] = _CacheContext(cache, cache_key)
  309. try:
  310. cached_result_d = cache.get(cache_key, callback=invalidate_callback)
  311. if isinstance(cached_result_d, ObservableDeferred):
  312. observer = cached_result_d.observe()
  313. else:
  314. observer = cached_result_d
  315. except KeyError:
  316. ret = defer.maybeDeferred(
  317. preserve_fn(self.function_to_call), obj, *args, **kwargs
  318. )
  319. def onErr(f):
  320. cache.invalidate(cache_key)
  321. return f
  322. ret.addErrback(onErr)
  323. # If our cache_key is a string on py2, try to convert to ascii
  324. # to save a bit of space in large caches. Py3 does this
  325. # internally automatically.
  326. if six.PY2 and isinstance(cache_key, string_types):
  327. cache_key = to_ascii(cache_key)
  328. result_d = ObservableDeferred(ret, consumeErrors=True)
  329. cache.set(cache_key, result_d, callback=invalidate_callback)
  330. observer = result_d.observe()
  331. if isinstance(observer, defer.Deferred):
  332. return make_deferred_yieldable(observer)
  333. else:
  334. return observer
  335. if self.num_args == 1:
  336. wrapped.invalidate = lambda key: cache.invalidate(key[0])
  337. wrapped.prefill = lambda key, val: cache.prefill(key[0], val)
  338. else:
  339. wrapped.invalidate = cache.invalidate
  340. wrapped.invalidate_all = cache.invalidate_all
  341. wrapped.invalidate_many = cache.invalidate_many
  342. wrapped.prefill = cache.prefill
  343. wrapped.invalidate_all = cache.invalidate_all
  344. wrapped.cache = cache
  345. wrapped.num_args = self.num_args
  346. obj.__dict__[self.orig.__name__] = wrapped
  347. return wrapped
  348. class CacheListDescriptor(_CacheDescriptorBase):
  349. """Wraps an existing cache to support bulk fetching of keys.
  350. Given a list of keys it looks in the cache to find any hits, then passes
  351. the list of missing keys to the wrapped function.
  352. Once wrapped, the function returns either a Deferred which resolves to
  353. the list of results, or (if all results were cached), just the list of
  354. results.
  355. """
  356. def __init__(
  357. self, orig, cached_method_name, list_name, num_args=None, inlineCallbacks=False
  358. ):
  359. """
  360. Args:
  361. orig (function)
  362. cached_method_name (str): The name of the chached method.
  363. list_name (str): Name of the argument which is the bulk lookup list
  364. num_args (int): number of positional arguments (excluding ``self``,
  365. but including list_name) to use as cache keys. Defaults to all
  366. named args of the function.
  367. inlineCallbacks (bool): Whether orig is a generator that should
  368. be wrapped by defer.inlineCallbacks
  369. """
  370. super(CacheListDescriptor, self).__init__(
  371. orig, num_args=num_args, inlineCallbacks=inlineCallbacks
  372. )
  373. self.list_name = list_name
  374. self.list_pos = self.arg_names.index(self.list_name)
  375. self.cached_method_name = cached_method_name
  376. self.sentinel = object()
  377. if self.list_name not in self.arg_names:
  378. raise Exception(
  379. "Couldn't see arguments %r for %r."
  380. % (self.list_name, cached_method_name)
  381. )
  382. def __get__(self, obj, objtype=None):
  383. cached_method = getattr(obj, self.cached_method_name)
  384. cache = cached_method.cache
  385. num_args = cached_method.num_args
  386. @functools.wraps(self.orig)
  387. def wrapped(*args, **kwargs):
  388. # If we're passed a cache_context then we'll want to call its
  389. # invalidate() whenever we are invalidated
  390. invalidate_callback = kwargs.pop("on_invalidate", None)
  391. arg_dict = inspect.getcallargs(self.orig, obj, *args, **kwargs)
  392. keyargs = [arg_dict[arg_nm] for arg_nm in self.arg_names]
  393. list_args = arg_dict[self.list_name]
  394. results = {}
  395. def update_results_dict(res, arg):
  396. results[arg] = res
  397. # list of deferreds to wait for
  398. cached_defers = []
  399. missing = set()
  400. # If the cache takes a single arg then that is used as the key,
  401. # otherwise a tuple is used.
  402. if num_args == 1:
  403. def arg_to_cache_key(arg):
  404. return arg
  405. else:
  406. keylist = list(keyargs)
  407. def arg_to_cache_key(arg):
  408. keylist[self.list_pos] = arg
  409. return tuple(keylist)
  410. for arg in list_args:
  411. try:
  412. res = cache.get(arg_to_cache_key(arg), callback=invalidate_callback)
  413. if not isinstance(res, ObservableDeferred):
  414. results[arg] = res
  415. elif not res.has_succeeded():
  416. res = res.observe()
  417. res.addCallback(update_results_dict, arg)
  418. cached_defers.append(res)
  419. else:
  420. results[arg] = res.get_result()
  421. except KeyError:
  422. missing.add(arg)
  423. if missing:
  424. # we need an observable deferred for each entry in the list,
  425. # which we put in the cache. Each deferred resolves with the
  426. # relevant result for that key.
  427. deferreds_map = {}
  428. for arg in missing:
  429. deferred = defer.Deferred()
  430. deferreds_map[arg] = deferred
  431. key = arg_to_cache_key(arg)
  432. observable = ObservableDeferred(deferred)
  433. cache.set(key, observable, callback=invalidate_callback)
  434. def complete_all(res):
  435. # the wrapped function has completed. It returns a
  436. # a dict. We can now resolve the observable deferreds in
  437. # the cache and update our own result map.
  438. for e in missing:
  439. val = res.get(e, None)
  440. deferreds_map[e].callback(val)
  441. results[e] = val
  442. def errback(f):
  443. # the wrapped function has failed. Invalidate any cache
  444. # entries we're supposed to be populating, and fail
  445. # their deferreds.
  446. for e in missing:
  447. key = arg_to_cache_key(e)
  448. cache.invalidate(key)
  449. deferreds_map[e].errback(f)
  450. # return the failure, to propagate to our caller.
  451. return f
  452. args_to_call = dict(arg_dict)
  453. args_to_call[self.list_name] = list(missing)
  454. cached_defers.append(
  455. defer.maybeDeferred(
  456. preserve_fn(self.function_to_call), **args_to_call
  457. ).addCallbacks(complete_all, errback)
  458. )
  459. if cached_defers:
  460. d = defer.gatherResults(cached_defers, consumeErrors=True).addCallbacks(
  461. lambda _: results, unwrapFirstError
  462. )
  463. return make_deferred_yieldable(d)
  464. else:
  465. return results
  466. obj.__dict__[self.orig.__name__] = wrapped
  467. return wrapped
  468. class _CacheContext(namedtuple("_CacheContext", ("cache", "key"))):
  469. # We rely on _CacheContext implementing __eq__ and __hash__ sensibly,
  470. # which namedtuple does for us (i.e. two _CacheContext are the same if
  471. # their caches and keys match). This is important in particular to
  472. # dedupe when we add callbacks to lru cache nodes, otherwise the number
  473. # of callbacks would grow.
  474. def invalidate(self):
  475. self.cache.invalidate(self.key)
  476. def cached(
  477. max_entries=1000, num_args=None, tree=False, cache_context=False, iterable=False
  478. ):
  479. return lambda orig: CacheDescriptor(
  480. orig,
  481. max_entries=max_entries,
  482. num_args=num_args,
  483. tree=tree,
  484. cache_context=cache_context,
  485. iterable=iterable,
  486. )
  487. def cachedInlineCallbacks(
  488. max_entries=1000, num_args=None, tree=False, cache_context=False, iterable=False
  489. ):
  490. return lambda orig: CacheDescriptor(
  491. orig,
  492. max_entries=max_entries,
  493. num_args=num_args,
  494. tree=tree,
  495. inlineCallbacks=True,
  496. cache_context=cache_context,
  497. iterable=iterable,
  498. )
  499. def cachedList(cached_method_name, list_name, num_args=None, inlineCallbacks=False):
  500. """Creates a descriptor that wraps a function in a `CacheListDescriptor`.
  501. Used to do batch lookups for an already created cache. A single argument
  502. is specified as a list that is iterated through to lookup keys in the
  503. original cache. A new list consisting of the keys that weren't in the cache
  504. get passed to the original function, the result of which is stored in the
  505. cache.
  506. Args:
  507. cached_method_name (str): The name of the single-item lookup method.
  508. This is only used to find the cache to use.
  509. list_name (str): The name of the argument that is the list to use to
  510. do batch lookups in the cache.
  511. num_args (int): Number of arguments to use as the key in the cache
  512. (including list_name). Defaults to all named parameters.
  513. inlineCallbacks (bool): Should the function be wrapped in an
  514. `defer.inlineCallbacks`?
  515. Example:
  516. class Example(object):
  517. @cached(num_args=2)
  518. def do_something(self, first_arg):
  519. ...
  520. @cachedList(do_something.cache, list_name="second_args", num_args=2)
  521. def batch_do_something(self, first_arg, second_args):
  522. ...
  523. """
  524. return lambda orig: CacheListDescriptor(
  525. orig,
  526. cached_method_name=cached_method_name,
  527. list_name=list_name,
  528. num_args=num_args,
  529. inlineCallbacks=inlineCallbacks,
  530. )