async_helpers.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. # Copyright 2014-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 collections
  16. import inspect
  17. import itertools
  18. import logging
  19. from contextlib import contextmanager
  20. from typing import (
  21. Any,
  22. Awaitable,
  23. Callable,
  24. Dict,
  25. Generic,
  26. Hashable,
  27. Iterable,
  28. List,
  29. Optional,
  30. Set,
  31. TypeVar,
  32. Union,
  33. )
  34. import attr
  35. from typing_extensions import ContextManager
  36. from twisted.internet import defer
  37. from twisted.internet.base import ReactorBase
  38. from twisted.internet.defer import CancelledError
  39. from twisted.internet.interfaces import IReactorTime
  40. from twisted.python import failure
  41. from twisted.python.failure import Failure
  42. from synapse.logging.context import (
  43. PreserveLoggingContext,
  44. make_deferred_yieldable,
  45. run_in_background,
  46. )
  47. from synapse.util import Clock, unwrapFirstError
  48. logger = logging.getLogger(__name__)
  49. _T = TypeVar("_T")
  50. class ObservableDeferred(Generic[_T]):
  51. """Wraps a deferred object so that we can add observer deferreds. These
  52. observer deferreds do not affect the callback chain of the original
  53. deferred.
  54. If consumeErrors is true errors will be captured from the origin deferred.
  55. Cancelling or otherwise resolving an observer will not affect the original
  56. ObservableDeferred.
  57. NB that it does not attempt to do anything with logcontexts; in general
  58. you should probably make_deferred_yieldable the deferreds
  59. returned by `observe`, and ensure that the original deferred runs its
  60. callbacks in the sentinel logcontext.
  61. """
  62. __slots__ = ["_deferred", "_observers", "_result"]
  63. def __init__(self, deferred: "defer.Deferred[_T]", consumeErrors: bool = False):
  64. object.__setattr__(self, "_deferred", deferred)
  65. object.__setattr__(self, "_result", None)
  66. object.__setattr__(self, "_observers", set())
  67. def callback(r):
  68. object.__setattr__(self, "_result", (True, r))
  69. while self._observers:
  70. observer = self._observers.pop()
  71. try:
  72. observer.callback(r)
  73. except Exception as e:
  74. logger.exception(
  75. "%r threw an exception on .callback(%r), ignoring...",
  76. observer,
  77. r,
  78. exc_info=e,
  79. )
  80. return r
  81. def errback(f):
  82. object.__setattr__(self, "_result", (False, f))
  83. while self._observers:
  84. # This is a little bit of magic to correctly propagate stack
  85. # traces when we `await` on one of the observer deferreds.
  86. f.value.__failure__ = f
  87. observer = self._observers.pop()
  88. try:
  89. observer.errback(f)
  90. except Exception as e:
  91. logger.exception(
  92. "%r threw an exception on .errback(%r), ignoring...",
  93. observer,
  94. f,
  95. exc_info=e,
  96. )
  97. if consumeErrors:
  98. return None
  99. else:
  100. return f
  101. deferred.addCallbacks(callback, errback)
  102. def observe(self) -> "defer.Deferred[_T]":
  103. """Observe the underlying deferred.
  104. This returns a brand new deferred that is resolved when the underlying
  105. deferred is resolved. Interacting with the returned deferred does not
  106. effect the underlying deferred.
  107. """
  108. if not self._result:
  109. d: "defer.Deferred[_T]" = defer.Deferred()
  110. def remove(r):
  111. self._observers.discard(d)
  112. return r
  113. d.addBoth(remove)
  114. self._observers.add(d)
  115. return d
  116. else:
  117. success, res = self._result
  118. return defer.succeed(res) if success else defer.fail(res)
  119. def observers(self) -> "List[defer.Deferred[_T]]":
  120. return self._observers
  121. def has_called(self) -> bool:
  122. return self._result is not None
  123. def has_succeeded(self) -> bool:
  124. return self._result is not None and self._result[0] is True
  125. def get_result(self) -> Union[_T, Failure]:
  126. return self._result[1]
  127. def __getattr__(self, name: str) -> Any:
  128. return getattr(self._deferred, name)
  129. def __setattr__(self, name: str, value: Any) -> None:
  130. setattr(self._deferred, name, value)
  131. def __repr__(self) -> str:
  132. return "<ObservableDeferred object at %s, result=%r, _deferred=%r>" % (
  133. id(self),
  134. self._result,
  135. self._deferred,
  136. )
  137. T = TypeVar("T")
  138. def concurrently_execute(
  139. func: Callable[[T], Any], args: Iterable[T], limit: int
  140. ) -> defer.Deferred:
  141. """Executes the function with each argument concurrently while limiting
  142. the number of concurrent executions.
  143. Args:
  144. func: Function to execute, should return a deferred or coroutine.
  145. args: List of arguments to pass to func, each invocation of func
  146. gets a single argument.
  147. limit: Maximum number of conccurent executions.
  148. Returns:
  149. Deferred: Resolved when all function invocations have finished.
  150. """
  151. it = iter(args)
  152. async def _concurrently_execute_inner(value: T) -> None:
  153. try:
  154. while True:
  155. await maybe_awaitable(func(value))
  156. value = next(it)
  157. except StopIteration:
  158. pass
  159. # We use `itertools.islice` to handle the case where the number of args is
  160. # less than the limit, avoiding needlessly spawning unnecessary background
  161. # tasks.
  162. return make_deferred_yieldable(
  163. defer.gatherResults(
  164. [
  165. run_in_background(_concurrently_execute_inner, value)
  166. for value in itertools.islice(it, limit)
  167. ],
  168. consumeErrors=True,
  169. )
  170. ).addErrback(unwrapFirstError)
  171. def yieldable_gather_results(
  172. func: Callable, iter: Iterable, *args: Any, **kwargs: Any
  173. ) -> defer.Deferred:
  174. """Executes the function with each argument concurrently.
  175. Args:
  176. func: Function to execute that returns a Deferred
  177. iter: An iterable that yields items that get passed as the first
  178. argument to the function
  179. *args: Arguments to be passed to each call to func
  180. **kwargs: Keyword arguments to be passed to each call to func
  181. Returns
  182. Deferred[list]: Resolved when all functions have been invoked, or errors if
  183. one of the function calls fails.
  184. """
  185. return make_deferred_yieldable(
  186. defer.gatherResults(
  187. [run_in_background(func, item, *args, **kwargs) for item in iter],
  188. consumeErrors=True,
  189. )
  190. ).addErrback(unwrapFirstError)
  191. @attr.s(slots=True)
  192. class _LinearizerEntry:
  193. # The number of things executing.
  194. count = attr.ib(type=int)
  195. # Deferreds for the things blocked from executing.
  196. deferreds = attr.ib(type=collections.OrderedDict)
  197. class Linearizer:
  198. """Limits concurrent access to resources based on a key. Useful to ensure
  199. only a few things happen at a time on a given resource.
  200. Example:
  201. with await limiter.queue("test_key"):
  202. # do some work.
  203. """
  204. def __init__(
  205. self,
  206. name: Optional[str] = None,
  207. max_count: int = 1,
  208. clock: Optional[Clock] = None,
  209. ):
  210. """
  211. Args:
  212. max_count: The maximum number of concurrent accesses
  213. """
  214. if name is None:
  215. self.name: Union[str, int] = id(self)
  216. else:
  217. self.name = name
  218. if not clock:
  219. from twisted.internet import reactor
  220. assert isinstance(reactor, ReactorBase)
  221. clock = Clock(reactor)
  222. self._clock = clock
  223. self.max_count = max_count
  224. # key_to_defer is a map from the key to a _LinearizerEntry.
  225. self.key_to_defer: Dict[Hashable, _LinearizerEntry] = {}
  226. def is_queued(self, key: Hashable) -> bool:
  227. """Checks whether there is a process queued up waiting"""
  228. entry = self.key_to_defer.get(key)
  229. if not entry:
  230. # No entry so nothing is waiting.
  231. return False
  232. # There are waiting deferreds only in the OrderedDict of deferreds is
  233. # non-empty.
  234. return bool(entry.deferreds)
  235. def queue(self, key: Hashable) -> defer.Deferred:
  236. # we avoid doing defer.inlineCallbacks here, so that cancellation works correctly.
  237. # (https://twistedmatrix.com/trac/ticket/4632 meant that cancellations were not
  238. # propagated inside inlineCallbacks until Twisted 18.7)
  239. entry = self.key_to_defer.setdefault(
  240. key, _LinearizerEntry(0, collections.OrderedDict())
  241. )
  242. # If the number of things executing is greater than the maximum
  243. # then add a deferred to the list of blocked items
  244. # When one of the things currently executing finishes it will callback
  245. # this item so that it can continue executing.
  246. if entry.count >= self.max_count:
  247. res = self._await_lock(key)
  248. else:
  249. logger.debug(
  250. "Acquired uncontended linearizer lock %r for key %r", self.name, key
  251. )
  252. entry.count += 1
  253. res = defer.succeed(None)
  254. # once we successfully get the lock, we need to return a context manager which
  255. # will release the lock.
  256. @contextmanager
  257. def _ctx_manager(_):
  258. try:
  259. yield
  260. finally:
  261. logger.debug("Releasing linearizer lock %r for key %r", self.name, key)
  262. # We've finished executing so check if there are any things
  263. # blocked waiting to execute and start one of them
  264. entry.count -= 1
  265. if entry.deferreds:
  266. (next_def, _) = entry.deferreds.popitem(last=False)
  267. # we need to run the next thing in the sentinel context.
  268. with PreserveLoggingContext():
  269. next_def.callback(None)
  270. elif entry.count == 0:
  271. # We were the last thing for this key: remove it from the
  272. # map.
  273. del self.key_to_defer[key]
  274. res.addCallback(_ctx_manager)
  275. return res
  276. def _await_lock(self, key: Hashable) -> defer.Deferred:
  277. """Helper for queue: adds a deferred to the queue
  278. Assumes that we've already checked that we've reached the limit of the number
  279. of lock-holders we allow. Creates a new deferred which is added to the list, and
  280. adds some management around cancellations.
  281. Returns the deferred, which will callback once we have secured the lock.
  282. """
  283. entry = self.key_to_defer[key]
  284. logger.debug("Waiting to acquire linearizer lock %r for key %r", self.name, key)
  285. new_defer = make_deferred_yieldable(defer.Deferred())
  286. entry.deferreds[new_defer] = 1
  287. def cb(_r):
  288. logger.debug("Acquired linearizer lock %r for key %r", self.name, key)
  289. entry.count += 1
  290. # if the code holding the lock completes synchronously, then it
  291. # will recursively run the next claimant on the list. That can
  292. # relatively rapidly lead to stack exhaustion. This is essentially
  293. # the same problem as http://twistedmatrix.com/trac/ticket/9304.
  294. #
  295. # In order to break the cycle, we add a cheeky sleep(0) here to
  296. # ensure that we fall back to the reactor between each iteration.
  297. #
  298. # (This needs to happen while we hold the lock, and the context manager's exit
  299. # code must be synchronous, so this is the only sensible place.)
  300. return self._clock.sleep(0)
  301. def eb(e):
  302. logger.info("defer %r got err %r", new_defer, e)
  303. if isinstance(e, CancelledError):
  304. logger.debug(
  305. "Cancelling wait for linearizer lock %r for key %r", self.name, key
  306. )
  307. else:
  308. logger.warning(
  309. "Unexpected exception waiting for linearizer lock %r for key %r",
  310. self.name,
  311. key,
  312. )
  313. # we just have to take ourselves back out of the queue.
  314. del entry.deferreds[new_defer]
  315. return e
  316. new_defer.addCallbacks(cb, eb)
  317. return new_defer
  318. class ReadWriteLock:
  319. """An async read write lock.
  320. Example:
  321. with await read_write_lock.read("test_key"):
  322. # do some work
  323. """
  324. # IMPLEMENTATION NOTES
  325. #
  326. # We track the most recent queued reader and writer deferreds (which get
  327. # resolved when they release the lock).
  328. #
  329. # Read: We know its safe to acquire a read lock when the latest writer has
  330. # been resolved. The new reader is appended to the list of latest readers.
  331. #
  332. # Write: We know its safe to acquire the write lock when both the latest
  333. # writers and readers have been resolved. The new writer replaces the latest
  334. # writer.
  335. def __init__(self) -> None:
  336. # Latest readers queued
  337. self.key_to_current_readers: Dict[str, Set[defer.Deferred]] = {}
  338. # Latest writer queued
  339. self.key_to_current_writer: Dict[str, defer.Deferred] = {}
  340. async def read(self, key: str) -> ContextManager:
  341. new_defer: "defer.Deferred[None]" = defer.Deferred()
  342. curr_readers = self.key_to_current_readers.setdefault(key, set())
  343. curr_writer = self.key_to_current_writer.get(key, None)
  344. curr_readers.add(new_defer)
  345. # We wait for the latest writer to finish writing. We can safely ignore
  346. # any existing readers... as they're readers.
  347. if curr_writer:
  348. await make_deferred_yieldable(curr_writer)
  349. @contextmanager
  350. def _ctx_manager():
  351. try:
  352. yield
  353. finally:
  354. new_defer.callback(None)
  355. self.key_to_current_readers.get(key, set()).discard(new_defer)
  356. return _ctx_manager()
  357. async def write(self, key: str) -> ContextManager:
  358. new_defer: "defer.Deferred[None]" = defer.Deferred()
  359. curr_readers = self.key_to_current_readers.get(key, set())
  360. curr_writer = self.key_to_current_writer.get(key, None)
  361. # We wait on all latest readers and writer.
  362. to_wait_on = list(curr_readers)
  363. if curr_writer:
  364. to_wait_on.append(curr_writer)
  365. # We can clear the list of current readers since the new writer waits
  366. # for them to finish.
  367. curr_readers.clear()
  368. self.key_to_current_writer[key] = new_defer
  369. await make_deferred_yieldable(defer.gatherResults(to_wait_on))
  370. @contextmanager
  371. def _ctx_manager():
  372. try:
  373. yield
  374. finally:
  375. new_defer.callback(None)
  376. if self.key_to_current_writer[key] == new_defer:
  377. self.key_to_current_writer.pop(key)
  378. return _ctx_manager()
  379. R = TypeVar("R")
  380. def timeout_deferred(
  381. deferred: "defer.Deferred[_T]", timeout: float, reactor: IReactorTime
  382. ) -> "defer.Deferred[_T]":
  383. """The in built twisted `Deferred.addTimeout` fails to time out deferreds
  384. that have a canceller that throws exceptions. This method creates a new
  385. deferred that wraps and times out the given deferred, correctly handling
  386. the case where the given deferred's canceller throws.
  387. (See https://twistedmatrix.com/trac/ticket/9534)
  388. NOTE: Unlike `Deferred.addTimeout`, this function returns a new deferred.
  389. NOTE: the TimeoutError raised by the resultant deferred is
  390. twisted.internet.defer.TimeoutError, which is *different* to the built-in
  391. TimeoutError, as well as various other TimeoutErrors you might have imported.
  392. Args:
  393. deferred: The Deferred to potentially timeout.
  394. timeout: Timeout in seconds
  395. reactor: The twisted reactor to use
  396. Returns:
  397. A new Deferred, which will errback with defer.TimeoutError on timeout.
  398. """
  399. new_d: "defer.Deferred[_T]" = defer.Deferred()
  400. timed_out = [False]
  401. def time_it_out() -> None:
  402. timed_out[0] = True
  403. try:
  404. deferred.cancel()
  405. except Exception: # if we throw any exception it'll break time outs
  406. logger.exception("Canceller failed during timeout")
  407. # the cancel() call should have set off a chain of errbacks which
  408. # will have errbacked new_d, but in case it hasn't, errback it now.
  409. if not new_d.called:
  410. new_d.errback(defer.TimeoutError("Timed out after %gs" % (timeout,)))
  411. delayed_call = reactor.callLater(timeout, time_it_out)
  412. def convert_cancelled(value: failure.Failure):
  413. # if the original deferred was cancelled, and our timeout has fired, then
  414. # the reason it was cancelled was due to our timeout. Turn the CancelledError
  415. # into a TimeoutError.
  416. if timed_out[0] and value.check(CancelledError):
  417. raise defer.TimeoutError("Timed out after %gs" % (timeout,))
  418. return value
  419. deferred.addErrback(convert_cancelled)
  420. def cancel_timeout(result):
  421. # stop the pending call to cancel the deferred if it's been fired
  422. if delayed_call.active():
  423. delayed_call.cancel()
  424. return result
  425. deferred.addBoth(cancel_timeout)
  426. def success_cb(val):
  427. if not new_d.called:
  428. new_d.callback(val)
  429. def failure_cb(val):
  430. if not new_d.called:
  431. new_d.errback(val)
  432. deferred.addCallbacks(success_cb, failure_cb)
  433. return new_d
  434. # This class can't be generic because it uses slots with attrs.
  435. # See: https://github.com/python-attrs/attrs/issues/313
  436. @attr.s(slots=True, frozen=True)
  437. class DoneAwaitable: # should be: Generic[R]
  438. """Simple awaitable that returns the provided value."""
  439. value = attr.ib(type=Any) # should be: R
  440. def __await__(self):
  441. return self
  442. def __iter__(self) -> "DoneAwaitable":
  443. return self
  444. def __next__(self) -> None:
  445. raise StopIteration(self.value)
  446. def maybe_awaitable(value: Union[Awaitable[R], R]) -> Awaitable[R]:
  447. """Convert a value to an awaitable if not already an awaitable."""
  448. if inspect.isawaitable(value):
  449. assert isinstance(value, Awaitable)
  450. return value
  451. return DoneAwaitable(value)