async_helpers.py 17 KB

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