You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

658 lines
23 KiB

  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. # Copyright 2018 New Vector 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 functools
  16. import inspect
  17. import logging
  18. from typing import (
  19. Any,
  20. Awaitable,
  21. Callable,
  22. Collection,
  23. Dict,
  24. Generic,
  25. Hashable,
  26. Iterable,
  27. List,
  28. Mapping,
  29. Optional,
  30. Sequence,
  31. Tuple,
  32. Type,
  33. TypeVar,
  34. Union,
  35. cast,
  36. )
  37. from weakref import WeakValueDictionary
  38. import attr
  39. from twisted.internet import defer
  40. from twisted.python.failure import Failure
  41. from synapse.logging.context import make_deferred_yieldable, preserve_fn
  42. from synapse.util import unwrapFirstError
  43. from synapse.util.async_helpers import delay_cancellation
  44. from synapse.util.caches.deferred_cache import DeferredCache
  45. from synapse.util.caches.lrucache import LruCache
  46. logger = logging.getLogger(__name__)
  47. CacheKey = Union[Tuple, Any]
  48. F = TypeVar("F", bound=Callable[..., Any])
  49. class CachedFunction(Generic[F]):
  50. invalidate: Callable[[Tuple[Any, ...]], None]
  51. invalidate_all: Callable[[], None]
  52. prefill: Callable[[Tuple[Any, ...], Any], None]
  53. cache: Any = None
  54. num_args: Any = None
  55. __name__: str
  56. # Note: This function signature is actually fiddled with by the synapse mypy
  57. # plugin to a) make it a bound method, and b) remove any `cache_context` arg.
  58. __call__: F
  59. class _CacheDescriptorBase:
  60. def __init__(
  61. self,
  62. orig: Callable[..., Any],
  63. num_args: Optional[int],
  64. uncached_args: Optional[Collection[str]] = None,
  65. cache_context: bool = False,
  66. name: Optional[str] = None,
  67. ):
  68. self.orig = orig
  69. self.name = name or orig.__name__
  70. arg_spec = inspect.getfullargspec(orig)
  71. all_args = arg_spec.args
  72. # There's no reason that keyword-only arguments couldn't be supported,
  73. # but right now they're buggy so do not allow them.
  74. if arg_spec.kwonlyargs:
  75. raise ValueError(
  76. "_CacheDescriptorBase does not support keyword-only arguments."
  77. )
  78. if "cache_context" in all_args:
  79. if not cache_context:
  80. raise ValueError(
  81. "Cannot have a 'cache_context' arg without setting"
  82. " cache_context=True"
  83. )
  84. elif cache_context:
  85. raise ValueError(
  86. "Cannot have cache_context=True without having an arg"
  87. " named `cache_context`"
  88. )
  89. if num_args is not None and uncached_args is not None:
  90. raise ValueError("Cannot provide both num_args and uncached_args")
  91. if num_args is None:
  92. num_args = len(all_args) - 1
  93. if cache_context:
  94. num_args -= 1
  95. if len(all_args) < num_args + 1:
  96. raise Exception(
  97. "Not enough explicit positional arguments to key off for %r: "
  98. "got %i args, but wanted %i. (@cached cannot key off *args or "
  99. "**kwargs)" % (orig.__name__, len(all_args), num_args)
  100. )
  101. self.num_args = num_args
  102. # list of the names of the args used as the cache key
  103. self.arg_names = all_args[1 : num_args + 1]
  104. # If there are args to not cache on, filter them out (and fix the size of num_args).
  105. if uncached_args is not None:
  106. include_arg_in_cache_key = [n not in uncached_args for n in self.arg_names]
  107. else:
  108. include_arg_in_cache_key = [True] * len(self.arg_names)
  109. # self.arg_defaults is a map of arg name to its default value for each
  110. # argument that has a default value
  111. if arg_spec.defaults:
  112. self.arg_defaults = dict(
  113. zip(all_args[-len(arg_spec.defaults) :], arg_spec.defaults)
  114. )
  115. else:
  116. self.arg_defaults = {}
  117. if "cache_context" in self.arg_names:
  118. raise Exception("cache_context arg cannot be included among the cache keys")
  119. self.add_cache_context = cache_context
  120. self.cache_key_builder = _get_cache_key_builder(
  121. self.arg_names, include_arg_in_cache_key, self.arg_defaults
  122. )
  123. class DeferredCacheDescriptor(_CacheDescriptorBase):
  124. """A method decorator that applies a memoizing cache around the function.
  125. This caches deferreds, rather than the results themselves. Deferreds that
  126. fail are removed from the cache.
  127. The function is presumed to take zero or more arguments, which are used in
  128. a tuple as the key for the cache. Hits are served directly from the cache;
  129. misses use the function body to generate the value.
  130. The wrapped function has an additional member, a callable called
  131. "invalidate". This can be used to remove individual entries from the cache.
  132. The wrapped function has another additional callable, called "prefill",
  133. which can be used to insert values into the cache specifically, without
  134. calling the calculation function.
  135. Cached functions can be "chained" (i.e. a cached function can call other cached
  136. functions and get appropriately invalidated when they called caches are
  137. invalidated) by adding a special "cache_context" argument to the function
  138. and passing that as a kwarg to all caches called. For example::
  139. @cached(cache_context=True)
  140. def foo(self, key, cache_context):
  141. r1 = yield self.bar1(key, on_invalidate=cache_context.invalidate)
  142. r2 = yield self.bar2(key, on_invalidate=cache_context.invalidate)
  143. return r1 + r2
  144. Args:
  145. orig:
  146. max_entries:
  147. num_args: number of positional arguments (excluding ``self`` and
  148. ``cache_context``) to use as cache keys. Defaults to all named
  149. args of the function.
  150. uncached_args: a list of argument names to not use as the cache key.
  151. (``self`` and ``cache_context`` are always ignored.) Cannot be used
  152. with num_args.
  153. tree:
  154. cache_context:
  155. iterable:
  156. prune_unread_entries: If True, cache entries that haven't been read recently
  157. will be evicted from the cache in the background. Set to False to opt-out
  158. of this behaviour.
  159. """
  160. def __init__(
  161. self,
  162. orig: Callable[..., Any],
  163. max_entries: int = 1000,
  164. num_args: Optional[int] = None,
  165. uncached_args: Optional[Collection[str]] = None,
  166. tree: bool = False,
  167. cache_context: bool = False,
  168. iterable: bool = False,
  169. prune_unread_entries: bool = True,
  170. name: Optional[str] = None,
  171. ):
  172. super().__init__(
  173. orig,
  174. num_args=num_args,
  175. uncached_args=uncached_args,
  176. cache_context=cache_context,
  177. name=name,
  178. )
  179. if tree and self.num_args < 2:
  180. raise RuntimeError(
  181. "tree=True is nonsensical for cached functions with a single parameter"
  182. )
  183. self.max_entries = max_entries
  184. self.tree = tree
  185. self.iterable = iterable
  186. self.prune_unread_entries = prune_unread_entries
  187. def __get__(
  188. self, obj: Optional[Any], owner: Optional[Type]
  189. ) -> Callable[..., "defer.Deferred[Any]"]:
  190. cache: DeferredCache[CacheKey, Any] = DeferredCache(
  191. name=self.name,
  192. max_entries=self.max_entries,
  193. tree=self.tree,
  194. iterable=self.iterable,
  195. prune_unread_entries=self.prune_unread_entries,
  196. )
  197. get_cache_key = self.cache_key_builder
  198. @functools.wraps(self.orig)
  199. def _wrapped(*args: Any, **kwargs: Any) -> "defer.Deferred[Any]":
  200. # If we're passed a cache_context then we'll want to call its invalidate()
  201. # whenever we are invalidated
  202. invalidate_callback = kwargs.pop("on_invalidate", None)
  203. cache_key = get_cache_key(args, kwargs)
  204. try:
  205. ret = cache.get(cache_key, callback=invalidate_callback)
  206. except KeyError:
  207. # Add our own `cache_context` to argument list if the wrapped function
  208. # has asked for one
  209. if self.add_cache_context:
  210. kwargs["cache_context"] = _CacheContext.get_instance(
  211. cache, cache_key
  212. )
  213. ret = defer.maybeDeferred(preserve_fn(self.orig), obj, *args, **kwargs)
  214. ret = cache.set(cache_key, ret, callback=invalidate_callback)
  215. # We started a new call to `self.orig`, so we must always wait for it to
  216. # complete. Otherwise we might mark our current logging context as
  217. # finished while `self.orig` is still using it in the background.
  218. ret = delay_cancellation(ret)
  219. return make_deferred_yieldable(ret)
  220. wrapped = cast(CachedFunction, _wrapped)
  221. if self.num_args == 1:
  222. assert not self.tree
  223. wrapped.invalidate = lambda key: cache.invalidate(key[0])
  224. wrapped.prefill = lambda key, val: cache.prefill(key[0], val)
  225. else:
  226. wrapped.invalidate = cache.invalidate
  227. wrapped.prefill = cache.prefill
  228. wrapped.invalidate_all = cache.invalidate_all
  229. wrapped.cache = cache
  230. wrapped.num_args = self.num_args
  231. obj.__dict__[self.name] = wrapped
  232. return wrapped
  233. class DeferredCacheListDescriptor(_CacheDescriptorBase):
  234. """Wraps an existing cache to support bulk fetching of keys.
  235. Given an iterable of keys it looks in the cache to find any hits, then passes
  236. the set of missing keys to the wrapped function.
  237. Once wrapped, the function returns a Deferred which resolves to a Dict mapping from
  238. input key to output value.
  239. """
  240. def __init__(
  241. self,
  242. orig: Callable[..., Awaitable[Dict]],
  243. cached_method_name: str,
  244. list_name: str,
  245. num_args: Optional[int] = None,
  246. name: Optional[str] = None,
  247. ):
  248. """
  249. Args:
  250. orig
  251. cached_method_name: The name of the cached method.
  252. list_name: Name of the argument which is the bulk lookup list
  253. num_args: number of positional arguments (excluding ``self``,
  254. but including list_name) to use as cache keys. Defaults to all
  255. named args of the function.
  256. """
  257. super().__init__(orig, num_args=num_args, uncached_args=None, name=name)
  258. self.list_name = list_name
  259. self.list_pos = self.arg_names.index(self.list_name)
  260. self.cached_method_name = cached_method_name
  261. self.sentinel = object()
  262. if self.list_name not in self.arg_names:
  263. raise Exception(
  264. "Couldn't see arguments %r for %r."
  265. % (self.list_name, cached_method_name)
  266. )
  267. def __get__(
  268. self, obj: Optional[Any], objtype: Optional[Type] = None
  269. ) -> Callable[..., "defer.Deferred[Dict[Hashable, Any]]"]:
  270. cached_method = getattr(obj, self.cached_method_name)
  271. cache: DeferredCache[CacheKey, Any] = cached_method.cache
  272. num_args = cached_method.num_args
  273. if num_args != self.num_args:
  274. raise TypeError(
  275. "Number of args (%s) does not match underlying cache_method_name=%s (%s)."
  276. % (self.num_args, self.cached_method_name, num_args)
  277. )
  278. @functools.wraps(self.orig)
  279. def wrapped(*args: Any, **kwargs: Any) -> "defer.Deferred[Dict]":
  280. # If we're passed a cache_context then we'll want to call its
  281. # invalidate() whenever we are invalidated
  282. invalidate_callback = kwargs.pop("on_invalidate", None)
  283. arg_dict = inspect.getcallargs(self.orig, obj, *args, **kwargs)
  284. keyargs = [arg_dict[arg_nm] for arg_nm in self.arg_names]
  285. list_args = arg_dict[self.list_name]
  286. # If the cache takes a single arg then that is used as the key,
  287. # otherwise a tuple is used.
  288. if num_args == 1:
  289. def arg_to_cache_key(arg: Hashable) -> Hashable:
  290. return arg
  291. def cache_key_to_arg(key: tuple) -> Hashable:
  292. return key
  293. else:
  294. keylist = list(keyargs)
  295. def arg_to_cache_key(arg: Hashable) -> Hashable:
  296. keylist[self.list_pos] = arg
  297. return tuple(keylist)
  298. def cache_key_to_arg(key: tuple) -> Hashable:
  299. return key[self.list_pos]
  300. cache_keys = [arg_to_cache_key(arg) for arg in list_args]
  301. immediate_results, pending_deferred, missing = cache.get_bulk(
  302. cache_keys, callback=invalidate_callback
  303. )
  304. results = {cache_key_to_arg(key): v for key, v in immediate_results.items()}
  305. cached_defers: List["defer.Deferred[Any]"] = []
  306. if pending_deferred:
  307. def update_results(r: Dict) -> None:
  308. for k, v in r.items():
  309. results[cache_key_to_arg(k)] = v
  310. pending_deferred.addCallback(update_results)
  311. cached_defers.append(pending_deferred)
  312. if missing:
  313. cache_entry = cache.start_bulk_input(missing, invalidate_callback)
  314. def complete_all(res: Dict[Hashable, Any]) -> None:
  315. missing_results = {}
  316. for key in missing:
  317. arg = cache_key_to_arg(key)
  318. val = res.get(arg, None)
  319. results[arg] = val
  320. missing_results[key] = val
  321. cache_entry.complete_bulk(cache, missing_results)
  322. def errback_all(f: Failure) -> None:
  323. cache_entry.error_bulk(cache, missing, f)
  324. args_to_call = dict(arg_dict)
  325. args_to_call[self.list_name] = {
  326. cache_key_to_arg(key) for key in missing
  327. }
  328. # dispatch the call, and attach the two handlers
  329. missing_d = defer.maybeDeferred(
  330. preserve_fn(self.orig), **args_to_call
  331. ).addCallbacks(complete_all, errback_all)
  332. cached_defers.append(missing_d)
  333. if cached_defers:
  334. d = defer.gatherResults(cached_defers, consumeErrors=True).addCallbacks(
  335. lambda _: results, unwrapFirstError
  336. )
  337. if missing:
  338. # We started a new call to `self.orig`, so we must always wait for it to
  339. # complete. Otherwise we might mark our current logging context as
  340. # finished while `self.orig` is still using it in the background.
  341. d = delay_cancellation(d)
  342. return make_deferred_yieldable(d)
  343. else:
  344. return defer.succeed(results)
  345. obj.__dict__[self.name] = wrapped
  346. return wrapped
  347. class _CacheContext:
  348. """Holds cache information from the cached function higher in the calling order.
  349. Can be used to invalidate the higher level cache entry if something changes
  350. on a lower level.
  351. """
  352. Cache = Union[DeferredCache, LruCache]
  353. _cache_context_objects: """WeakValueDictionary[
  354. Tuple["_CacheContext.Cache", CacheKey], "_CacheContext"
  355. ]""" = WeakValueDictionary()
  356. def __init__(self, cache: "_CacheContext.Cache", cache_key: CacheKey) -> None:
  357. self._cache = cache
  358. self._cache_key = cache_key
  359. def invalidate(self) -> None:
  360. """Invalidates the cache entry referred to by the context."""
  361. self._cache.invalidate(self._cache_key)
  362. @classmethod
  363. def get_instance(
  364. cls, cache: "_CacheContext.Cache", cache_key: CacheKey
  365. ) -> "_CacheContext":
  366. """Returns an instance constructed with the given arguments.
  367. A new instance is only created if none already exists.
  368. """
  369. # We make sure there are no identical _CacheContext instances. This is
  370. # important in particular to dedupe when we add callbacks to lru cache
  371. # nodes, otherwise the number of callbacks would grow.
  372. return cls._cache_context_objects.setdefault(
  373. (cache, cache_key), cls(cache, cache_key)
  374. )
  375. @attr.s(auto_attribs=True, slots=True, frozen=True)
  376. class _CachedFunctionDescriptor:
  377. """Helper for `@cached`, we name it so that we can hook into it with mypy
  378. plugin."""
  379. max_entries: int
  380. num_args: Optional[int]
  381. uncached_args: Optional[Collection[str]]
  382. tree: bool
  383. cache_context: bool
  384. iterable: bool
  385. prune_unread_entries: bool
  386. name: Optional[str]
  387. def __call__(self, orig: F) -> CachedFunction[F]:
  388. d = DeferredCacheDescriptor(
  389. orig,
  390. max_entries=self.max_entries,
  391. num_args=self.num_args,
  392. uncached_args=self.uncached_args,
  393. tree=self.tree,
  394. cache_context=self.cache_context,
  395. iterable=self.iterable,
  396. prune_unread_entries=self.prune_unread_entries,
  397. name=self.name,
  398. )
  399. return cast(CachedFunction[F], d)
  400. def cached(
  401. *,
  402. max_entries: int = 1000,
  403. num_args: Optional[int] = None,
  404. uncached_args: Optional[Collection[str]] = None,
  405. tree: bool = False,
  406. cache_context: bool = False,
  407. iterable: bool = False,
  408. prune_unread_entries: bool = True,
  409. name: Optional[str] = None,
  410. ) -> _CachedFunctionDescriptor:
  411. return _CachedFunctionDescriptor(
  412. max_entries=max_entries,
  413. num_args=num_args,
  414. uncached_args=uncached_args,
  415. tree=tree,
  416. cache_context=cache_context,
  417. iterable=iterable,
  418. prune_unread_entries=prune_unread_entries,
  419. name=name,
  420. )
  421. @attr.s(auto_attribs=True, slots=True, frozen=True)
  422. class _CachedListFunctionDescriptor:
  423. """Helper for `@cachedList`, we name it so that we can hook into it with mypy
  424. plugin."""
  425. cached_method_name: str
  426. list_name: str
  427. num_args: Optional[int] = None
  428. name: Optional[str] = None
  429. def __call__(self, orig: F) -> CachedFunction[F]:
  430. d = DeferredCacheListDescriptor(
  431. orig,
  432. cached_method_name=self.cached_method_name,
  433. list_name=self.list_name,
  434. num_args=self.num_args,
  435. name=self.name,
  436. )
  437. return cast(CachedFunction[F], d)
  438. def cachedList(
  439. *,
  440. cached_method_name: str,
  441. list_name: str,
  442. num_args: Optional[int] = None,
  443. name: Optional[str] = None,
  444. ) -> _CachedListFunctionDescriptor:
  445. """Creates a descriptor that wraps a function in a `DeferredCacheListDescriptor`.
  446. Used to do batch lookups for an already created cache. One of the arguments
  447. is specified as a list that is iterated through to lookup keys in the
  448. original cache. A new tuple consisting of the (deduplicated) keys that weren't in
  449. the cache gets passed to the original function, which is expected to results
  450. in a map of key to value for each passed value. The new results are stored in the
  451. original cache. Note that any missing values are cached as None.
  452. Args:
  453. cached_method_name: The name of the single-item lookup method.
  454. This is only used to find the cache to use.
  455. list_name: The name of the argument that is the iterable to use to
  456. do batch lookups in the cache.
  457. num_args: Number of arguments to use as the key in the cache
  458. (including list_name). Defaults to all named parameters.
  459. Example:
  460. class Example:
  461. @cached()
  462. def do_something(self, first_arg, second_arg):
  463. ...
  464. @cachedList(cached_method_name="do_something", list_name="second_args")
  465. def batch_do_something(self, first_arg, second_args):
  466. ...
  467. """
  468. return _CachedListFunctionDescriptor(
  469. cached_method_name=cached_method_name,
  470. list_name=list_name,
  471. num_args=num_args,
  472. name=name,
  473. )
  474. def _get_cache_key_builder(
  475. param_names: Sequence[str],
  476. include_params: Sequence[bool],
  477. param_defaults: Mapping[str, Any],
  478. ) -> Callable[[Sequence[Any], Mapping[str, Any]], CacheKey]:
  479. """Construct a function which will build cache keys suitable for a cached function
  480. Args:
  481. param_names: list of formal parameter names for the cached function
  482. include_params: list of bools of whether to include the parameter name in the cache key
  483. param_defaults: a mapping from parameter name to default value for that param
  484. Returns:
  485. A function which will take an (args, kwargs) pair and return a cache key
  486. """
  487. # By default our cache key is a tuple, but if there is only one item
  488. # then don't bother wrapping in a tuple. This is to save memory.
  489. if len(param_names) == 1:
  490. nm = param_names[0]
  491. assert include_params[0] is True
  492. def get_cache_key(args: Sequence[Any], kwargs: Mapping[str, Any]) -> CacheKey:
  493. if nm in kwargs:
  494. return kwargs[nm]
  495. elif len(args):
  496. return args[0]
  497. else:
  498. return param_defaults[nm]
  499. else:
  500. def get_cache_key(args: Sequence[Any], kwargs: Mapping[str, Any]) -> CacheKey:
  501. return tuple(
  502. _get_cache_key_gen(
  503. param_names, include_params, param_defaults, args, kwargs
  504. )
  505. )
  506. return get_cache_key
  507. def _get_cache_key_gen(
  508. param_names: Iterable[str],
  509. include_params: Iterable[bool],
  510. param_defaults: Mapping[str, Any],
  511. args: Sequence[Any],
  512. kwargs: Mapping[str, Any],
  513. ) -> Iterable[Any]:
  514. """Given some args/kwargs return a generator that resolves into
  515. the cache_key.
  516. This is essentially the same operation as `inspect.getcallargs`, but optimised so
  517. that we don't need to inspect the target function for each call.
  518. """
  519. # We loop through each arg name, looking up if its in the `kwargs`,
  520. # otherwise using the next argument in `args`. If there are no more
  521. # args then we try looking the arg name up in the defaults.
  522. pos = 0
  523. for nm, inc in zip(param_names, include_params):
  524. if nm in kwargs:
  525. if inc:
  526. yield kwargs[nm]
  527. elif pos < len(args):
  528. if inc:
  529. yield args[pos]
  530. pos += 1
  531. else:
  532. if inc:
  533. yield param_defaults[nm]