descriptors.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from synapse.util.async import ObservableDeferred
  17. from synapse.util import unwrapFirstError, logcontext
  18. from synapse.util.caches.lrucache import LruCache
  19. from synapse.util.caches.treecache import TreeCache, iterate_tree_cache_entry
  20. from . import DEBUG_CACHES, register_cache
  21. from twisted.internet import defer
  22. from collections import namedtuple
  23. import os
  24. import functools
  25. import inspect
  26. import threading
  27. logger = logging.getLogger(__name__)
  28. _CacheSentinel = object()
  29. CACHE_SIZE_FACTOR = float(os.environ.get("SYNAPSE_CACHE_FACTOR", 0.1))
  30. class CacheEntry(object):
  31. __slots__ = [
  32. "deferred", "sequence", "callbacks", "invalidated"
  33. ]
  34. def __init__(self, deferred, sequence, callbacks):
  35. self.deferred = deferred
  36. self.sequence = sequence
  37. self.callbacks = set(callbacks)
  38. self.invalidated = False
  39. def invalidate(self):
  40. if not self.invalidated:
  41. self.invalidated = True
  42. for callback in self.callbacks:
  43. callback()
  44. self.callbacks.clear()
  45. class Cache(object):
  46. __slots__ = (
  47. "cache",
  48. "max_entries",
  49. "name",
  50. "keylen",
  51. "sequence",
  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, keylen=keylen, cache_type=cache_type,
  61. size_callback=(lambda d: len(d.result)) if iterable else None,
  62. )
  63. self.name = name
  64. self.keylen = keylen
  65. self.sequence = 0
  66. self.thread = None
  67. self.metrics = register_cache(name, self.cache)
  68. def check_thread(self):
  69. expected_thread = self.thread
  70. if expected_thread is None:
  71. self.thread = threading.current_thread()
  72. else:
  73. if expected_thread is not threading.current_thread():
  74. raise ValueError(
  75. "Cache objects can only be accessed from the main thread"
  76. )
  77. def get(self, key, default=_CacheSentinel, callback=None):
  78. callbacks = [callback] if callback else []
  79. val = self._pending_deferred_cache.get(key, _CacheSentinel)
  80. if val is not _CacheSentinel:
  81. if val.sequence == self.sequence:
  82. val.callbacks.update(callbacks)
  83. self.metrics.inc_hits()
  84. return val.deferred
  85. val = self.cache.get(key, _CacheSentinel, callbacks=callbacks)
  86. if val is not _CacheSentinel:
  87. self.metrics.inc_hits()
  88. return val
  89. self.metrics.inc_misses()
  90. if default is _CacheSentinel:
  91. raise KeyError()
  92. else:
  93. return default
  94. def set(self, key, value, callback=None):
  95. callbacks = [callback] if callback else []
  96. self.check_thread()
  97. entry = CacheEntry(
  98. deferred=value,
  99. sequence=self.sequence,
  100. callbacks=callbacks,
  101. )
  102. entry.callbacks.update(callbacks)
  103. existing_entry = self._pending_deferred_cache.pop(key, None)
  104. if existing_entry:
  105. existing_entry.invalidate()
  106. self._pending_deferred_cache[key] = entry
  107. def shuffle(result):
  108. if self.sequence == entry.sequence:
  109. existing_entry = self._pending_deferred_cache.pop(key, None)
  110. if existing_entry is entry:
  111. self.cache.set(key, entry.deferred, entry.callbacks)
  112. else:
  113. entry.invalidate()
  114. else:
  115. entry.invalidate()
  116. return result
  117. entry.deferred.addCallback(shuffle)
  118. def prefill(self, key, value, callback=None):
  119. callbacks = [callback] if callback else []
  120. self.cache.set(key, value, callbacks=callbacks)
  121. def invalidate(self, key):
  122. self.check_thread()
  123. if not isinstance(key, tuple):
  124. raise TypeError(
  125. "The cache key must be a tuple not %r" % (type(key),)
  126. )
  127. # Increment the sequence number so that any SELECT statements that
  128. # raced with the INSERT don't update the cache (SYN-369)
  129. self.sequence += 1
  130. entry = self._pending_deferred_cache.pop(key, None)
  131. if entry:
  132. entry.invalidate()
  133. self.cache.pop(key, None)
  134. def invalidate_many(self, key):
  135. self.check_thread()
  136. if not isinstance(key, tuple):
  137. raise TypeError(
  138. "The cache key must be a tuple not %r" % (type(key),)
  139. )
  140. self.sequence += 1
  141. self.cache.del_multi(key)
  142. entry_dict = self._pending_deferred_cache.pop(key, None)
  143. if entry_dict is not None:
  144. for entry in iterate_tree_cache_entry(entry_dict):
  145. entry.invalidate()
  146. def invalidate_all(self):
  147. self.check_thread()
  148. self.sequence += 1
  149. self.cache.clear()
  150. class _CacheDescriptorBase(object):
  151. def __init__(self, orig, num_args, inlineCallbacks, cache_context=False):
  152. self.orig = orig
  153. if inlineCallbacks:
  154. self.function_to_call = defer.inlineCallbacks(orig)
  155. else:
  156. self.function_to_call = orig
  157. arg_spec = inspect.getargspec(orig)
  158. all_args = arg_spec.args
  159. if "cache_context" in all_args:
  160. if not cache_context:
  161. raise ValueError(
  162. "Cannot have a 'cache_context' arg without setting"
  163. " cache_context=True"
  164. )
  165. elif cache_context:
  166. raise ValueError(
  167. "Cannot have cache_context=True without having an arg"
  168. " named `cache_context`"
  169. )
  170. if num_args is None:
  171. num_args = len(all_args) - 1
  172. if cache_context:
  173. num_args -= 1
  174. if len(all_args) < num_args + 1:
  175. raise Exception(
  176. "Not enough explicit positional arguments to key off for %r: "
  177. "got %i args, but wanted %i. (@cached cannot key off *args or "
  178. "**kwargs)"
  179. % (orig.__name__, len(all_args), num_args)
  180. )
  181. self.num_args = num_args
  182. self.arg_names = all_args[1:num_args + 1]
  183. if "cache_context" in self.arg_names:
  184. raise Exception(
  185. "cache_context arg cannot be included among the cache keys"
  186. )
  187. self.add_cache_context = cache_context
  188. class CacheDescriptor(_CacheDescriptorBase):
  189. """ A method decorator that applies a memoizing cache around the function.
  190. This caches deferreds, rather than the results themselves. Deferreds that
  191. fail are removed from the cache.
  192. The function is presumed to take zero or more arguments, which are used in
  193. a tuple as the key for the cache. Hits are served directly from the cache;
  194. misses use the function body to generate the value.
  195. The wrapped function has an additional member, a callable called
  196. "invalidate". This can be used to remove individual entries from the cache.
  197. The wrapped function has another additional callable, called "prefill",
  198. which can be used to insert values into the cache specifically, without
  199. calling the calculation function.
  200. Cached functions can be "chained" (i.e. a cached function can call other cached
  201. functions and get appropriately invalidated when they called caches are
  202. invalidated) by adding a special "cache_context" argument to the function
  203. and passing that as a kwarg to all caches called. For example::
  204. @cachedInlineCallbacks(cache_context=True)
  205. def foo(self, key, cache_context):
  206. r1 = yield self.bar1(key, on_invalidate=cache_context.invalidate)
  207. r2 = yield self.bar2(key, on_invalidate=cache_context.invalidate)
  208. defer.returnValue(r1 + r2)
  209. Args:
  210. num_args (int): number of positional arguments (excluding ``self`` and
  211. ``cache_context``) to use as cache keys. Defaults to all named
  212. args of the function.
  213. """
  214. def __init__(self, orig, max_entries=1000, num_args=None, tree=False,
  215. inlineCallbacks=False, cache_context=False, iterable=False):
  216. super(CacheDescriptor, self).__init__(
  217. orig, num_args=num_args, inlineCallbacks=inlineCallbacks,
  218. cache_context=cache_context)
  219. max_entries = int(max_entries * CACHE_SIZE_FACTOR)
  220. self.max_entries = max_entries
  221. self.tree = tree
  222. self.iterable = iterable
  223. def __get__(self, obj, objtype=None):
  224. cache = Cache(
  225. name=self.orig.__name__,
  226. max_entries=self.max_entries,
  227. keylen=self.num_args,
  228. tree=self.tree,
  229. iterable=self.iterable,
  230. )
  231. @functools.wraps(self.orig)
  232. def wrapped(*args, **kwargs):
  233. # If we're passed a cache_context then we'll want to call its invalidate()
  234. # whenever we are invalidated
  235. invalidate_callback = kwargs.pop("on_invalidate", None)
  236. # Add temp cache_context so inspect.getcallargs doesn't explode
  237. if self.add_cache_context:
  238. kwargs["cache_context"] = None
  239. arg_dict = inspect.getcallargs(self.orig, obj, *args, **kwargs)
  240. cache_key = tuple(arg_dict[arg_nm] for arg_nm in self.arg_names)
  241. # Add our own `cache_context` to argument list if the wrapped function
  242. # has asked for one
  243. if self.add_cache_context:
  244. kwargs["cache_context"] = _CacheContext(cache, cache_key)
  245. try:
  246. cached_result_d = cache.get(cache_key, callback=invalidate_callback)
  247. observer = cached_result_d.observe()
  248. if DEBUG_CACHES:
  249. @defer.inlineCallbacks
  250. def check_result(cached_result):
  251. actual_result = yield self.function_to_call(obj, *args, **kwargs)
  252. if actual_result != cached_result:
  253. logger.error(
  254. "Stale cache entry %s%r: cached: %r, actual %r",
  255. self.orig.__name__, cache_key,
  256. cached_result, actual_result,
  257. )
  258. raise ValueError("Stale cache entry")
  259. defer.returnValue(cached_result)
  260. observer.addCallback(check_result)
  261. except KeyError:
  262. ret = defer.maybeDeferred(
  263. logcontext.preserve_fn(self.function_to_call),
  264. obj, *args, **kwargs
  265. )
  266. def onErr(f):
  267. cache.invalidate(cache_key)
  268. return f
  269. ret.addErrback(onErr)
  270. result_d = ObservableDeferred(ret, consumeErrors=True)
  271. cache.set(cache_key, result_d, callback=invalidate_callback)
  272. observer = result_d.observe()
  273. if isinstance(observer, defer.Deferred):
  274. return logcontext.make_deferred_yieldable(observer)
  275. else:
  276. return observer
  277. wrapped.invalidate = cache.invalidate
  278. wrapped.invalidate_all = cache.invalidate_all
  279. wrapped.invalidate_many = cache.invalidate_many
  280. wrapped.prefill = cache.prefill
  281. wrapped.cache = cache
  282. obj.__dict__[self.orig.__name__] = wrapped
  283. return wrapped
  284. class CacheListDescriptor(_CacheDescriptorBase):
  285. """Wraps an existing cache to support bulk fetching of keys.
  286. Given a list of keys it looks in the cache to find any hits, then passes
  287. the list of missing keys to the wrapped function.
  288. Once wrapped, the function returns either a Deferred which resolves to
  289. the list of results, or (if all results were cached), just the list of
  290. results.
  291. """
  292. def __init__(self, orig, cached_method_name, list_name, num_args=None,
  293. inlineCallbacks=False):
  294. """
  295. Args:
  296. orig (function)
  297. cached_method_name (str): The name of the chached method.
  298. list_name (str): Name of the argument which is the bulk lookup list
  299. num_args (int): number of positional arguments (excluding ``self``,
  300. but including list_name) to use as cache keys. Defaults to all
  301. named args of the function.
  302. inlineCallbacks (bool): Whether orig is a generator that should
  303. be wrapped by defer.inlineCallbacks
  304. """
  305. super(CacheListDescriptor, self).__init__(
  306. orig, num_args=num_args, inlineCallbacks=inlineCallbacks)
  307. self.list_name = list_name
  308. self.list_pos = self.arg_names.index(self.list_name)
  309. self.cached_method_name = cached_method_name
  310. self.sentinel = object()
  311. if self.list_name not in self.arg_names:
  312. raise Exception(
  313. "Couldn't see arguments %r for %r."
  314. % (self.list_name, cached_method_name,)
  315. )
  316. def __get__(self, obj, objtype=None):
  317. cache = getattr(obj, self.cached_method_name).cache
  318. @functools.wraps(self.orig)
  319. def wrapped(*args, **kwargs):
  320. # If we're passed a cache_context then we'll want to call its invalidate()
  321. # whenever we are invalidated
  322. invalidate_callback = kwargs.pop("on_invalidate", None)
  323. arg_dict = inspect.getcallargs(self.orig, obj, *args, **kwargs)
  324. keyargs = [arg_dict[arg_nm] for arg_nm in self.arg_names]
  325. list_args = arg_dict[self.list_name]
  326. # cached is a dict arg -> deferred, where deferred results in a
  327. # 2-tuple (`arg`, `result`)
  328. results = {}
  329. cached_defers = {}
  330. missing = []
  331. for arg in list_args:
  332. key = list(keyargs)
  333. key[self.list_pos] = arg
  334. try:
  335. res = cache.get(tuple(key), callback=invalidate_callback)
  336. if not res.has_succeeded():
  337. res = res.observe()
  338. res.addCallback(lambda r, arg: (arg, r), arg)
  339. cached_defers[arg] = res
  340. else:
  341. results[arg] = res.get_result()
  342. except KeyError:
  343. missing.append(arg)
  344. if missing:
  345. args_to_call = dict(arg_dict)
  346. args_to_call[self.list_name] = missing
  347. ret_d = defer.maybeDeferred(
  348. logcontext.preserve_fn(self.function_to_call),
  349. **args_to_call
  350. )
  351. ret_d = ObservableDeferred(ret_d)
  352. # We need to create deferreds for each arg in the list so that
  353. # we can insert the new deferred into the cache.
  354. for arg in missing:
  355. observer = ret_d.observe()
  356. observer.addCallback(lambda r, arg: r.get(arg, None), arg)
  357. observer = ObservableDeferred(observer)
  358. key = list(keyargs)
  359. key[self.list_pos] = arg
  360. cache.set(
  361. tuple(key), observer,
  362. callback=invalidate_callback
  363. )
  364. def invalidate(f, key):
  365. cache.invalidate(key)
  366. return f
  367. observer.addErrback(invalidate, tuple(key))
  368. res = observer.observe()
  369. res.addCallback(lambda r, arg: (arg, r), arg)
  370. cached_defers[arg] = res
  371. if cached_defers:
  372. def update_results_dict(res):
  373. results.update(res)
  374. return results
  375. return logcontext.make_deferred_yieldable(defer.gatherResults(
  376. cached_defers.values(),
  377. consumeErrors=True,
  378. ).addCallback(update_results_dict).addErrback(
  379. unwrapFirstError
  380. ))
  381. else:
  382. return results
  383. obj.__dict__[self.orig.__name__] = wrapped
  384. return wrapped
  385. class _CacheContext(namedtuple("_CacheContext", ("cache", "key"))):
  386. # We rely on _CacheContext implementing __eq__ and __hash__ sensibly,
  387. # which namedtuple does for us (i.e. two _CacheContext are the same if
  388. # their caches and keys match). This is important in particular to
  389. # dedupe when we add callbacks to lru cache nodes, otherwise the number
  390. # of callbacks would grow.
  391. def invalidate(self):
  392. self.cache.invalidate(self.key)
  393. def cached(max_entries=1000, num_args=None, tree=False, cache_context=False,
  394. iterable=False):
  395. return lambda orig: CacheDescriptor(
  396. orig,
  397. max_entries=max_entries,
  398. num_args=num_args,
  399. tree=tree,
  400. cache_context=cache_context,
  401. iterable=iterable,
  402. )
  403. def cachedInlineCallbacks(max_entries=1000, num_args=None, tree=False,
  404. cache_context=False, iterable=False):
  405. return lambda orig: CacheDescriptor(
  406. orig,
  407. max_entries=max_entries,
  408. num_args=num_args,
  409. tree=tree,
  410. inlineCallbacks=True,
  411. cache_context=cache_context,
  412. iterable=iterable,
  413. )
  414. def cachedList(cached_method_name, list_name, num_args=None, inlineCallbacks=False):
  415. """Creates a descriptor that wraps a function in a `CacheListDescriptor`.
  416. Used to do batch lookups for an already created cache. A single argument
  417. is specified as a list that is iterated through to lookup keys in the
  418. original cache. A new list consisting of the keys that weren't in the cache
  419. get passed to the original function, the result of which is stored in the
  420. cache.
  421. Args:
  422. cache (Cache): The underlying cache to use.
  423. list_name (str): The name of the argument that is the list to use to
  424. do batch lookups in the cache.
  425. num_args (int): Number of arguments to use as the key in the cache
  426. (including list_name). Defaults to all named parameters.
  427. inlineCallbacks (bool): Should the function be wrapped in an
  428. `defer.inlineCallbacks`?
  429. Example:
  430. class Example(object):
  431. @cached(num_args=2)
  432. def do_something(self, first_arg):
  433. ...
  434. @cachedList(do_something.cache, list_name="second_args", num_args=2)
  435. def batch_do_something(self, first_arg, second_args):
  436. ...
  437. """
  438. return lambda orig: CacheListDescriptor(
  439. orig,
  440. cached_method_name=cached_method_name,
  441. list_name=list_name,
  442. num_args=num_args,
  443. inlineCallbacks=inlineCallbacks,
  444. )