async_helpers.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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 abc
  16. import collections
  17. import inspect
  18. import itertools
  19. import logging
  20. from contextlib import asynccontextmanager, contextmanager
  21. from typing import (
  22. Any,
  23. AsyncIterator,
  24. Awaitable,
  25. Callable,
  26. Collection,
  27. Dict,
  28. Generic,
  29. Hashable,
  30. Iterable,
  31. Iterator,
  32. List,
  33. Optional,
  34. Set,
  35. Tuple,
  36. TypeVar,
  37. Union,
  38. cast,
  39. overload,
  40. )
  41. import attr
  42. from typing_extensions import AsyncContextManager, Literal
  43. from twisted.internet import defer
  44. from twisted.internet.defer import CancelledError
  45. from twisted.internet.interfaces import IReactorTime
  46. from twisted.python.failure import Failure
  47. from synapse.logging.context import (
  48. PreserveLoggingContext,
  49. make_deferred_yieldable,
  50. run_in_background,
  51. )
  52. from synapse.util import Clock
  53. logger = logging.getLogger(__name__)
  54. _T = TypeVar("_T")
  55. class AbstractObservableDeferred(Generic[_T], metaclass=abc.ABCMeta):
  56. """Abstract base class defining the consumer interface of ObservableDeferred"""
  57. __slots__ = ()
  58. @abc.abstractmethod
  59. def observe(self) -> "defer.Deferred[_T]":
  60. """Add a new observer for this ObservableDeferred
  61. This returns a brand new deferred that is resolved when the underlying
  62. deferred is resolved. Interacting with the returned deferred does not
  63. effect the underlying deferred.
  64. Note that the returned Deferred doesn't follow the Synapse logcontext rules -
  65. you will probably want to `make_deferred_yieldable` it.
  66. """
  67. ...
  68. class ObservableDeferred(Generic[_T], AbstractObservableDeferred[_T]):
  69. """Wraps a deferred object so that we can add observer deferreds. These
  70. observer deferreds do not affect the callback chain of the original
  71. deferred.
  72. If consumeErrors is true errors will be captured from the origin deferred.
  73. Cancelling or otherwise resolving an observer will not affect the original
  74. ObservableDeferred.
  75. NB that it does not attempt to do anything with logcontexts; in general
  76. you should probably make_deferred_yieldable the deferreds
  77. returned by `observe`, and ensure that the original deferred runs its
  78. callbacks in the sentinel logcontext.
  79. """
  80. __slots__ = ["_deferred", "_observers", "_result"]
  81. _deferred: "defer.Deferred[_T]"
  82. _observers: Union[List["defer.Deferred[_T]"], Tuple[()]]
  83. _result: Union[None, Tuple[Literal[True], _T], Tuple[Literal[False], Failure]]
  84. def __init__(self, deferred: "defer.Deferred[_T]", consumeErrors: bool = False):
  85. object.__setattr__(self, "_deferred", deferred)
  86. object.__setattr__(self, "_result", None)
  87. object.__setattr__(self, "_observers", [])
  88. def callback(r: _T) -> _T:
  89. object.__setattr__(self, "_result", (True, r))
  90. # once we have set _result, no more entries will be added to _observers,
  91. # so it's safe to replace it with the empty tuple.
  92. observers = self._observers
  93. object.__setattr__(self, "_observers", ())
  94. for observer in observers:
  95. try:
  96. observer.callback(r)
  97. except Exception as e:
  98. logger.exception(
  99. "%r threw an exception on .callback(%r), ignoring...",
  100. observer,
  101. r,
  102. exc_info=e,
  103. )
  104. return r
  105. def errback(f: Failure) -> Optional[Failure]:
  106. object.__setattr__(self, "_result", (False, f))
  107. # once we have set _result, no more entries will be added to _observers,
  108. # so it's safe to replace it with the empty tuple.
  109. observers = self._observers
  110. object.__setattr__(self, "_observers", ())
  111. for observer in observers:
  112. # This is a little bit of magic to correctly propagate stack
  113. # traces when we `await` on one of the observer deferreds.
  114. f.value.__failure__ = f # type: ignore[union-attr]
  115. try:
  116. observer.errback(f)
  117. except Exception as e:
  118. logger.exception(
  119. "%r threw an exception on .errback(%r), ignoring...",
  120. observer,
  121. f,
  122. exc_info=e,
  123. )
  124. if consumeErrors:
  125. return None
  126. else:
  127. return f
  128. deferred.addCallbacks(callback, errback)
  129. def observe(self) -> "defer.Deferred[_T]":
  130. """Observe the underlying deferred.
  131. This returns a brand new deferred that is resolved when the underlying
  132. deferred is resolved. Interacting with the returned deferred does not
  133. effect the underlying deferred.
  134. """
  135. if not self._result:
  136. assert isinstance(self._observers, list)
  137. d: "defer.Deferred[_T]" = defer.Deferred()
  138. self._observers.append(d)
  139. return d
  140. elif self._result[0]:
  141. return defer.succeed(self._result[1])
  142. else:
  143. return defer.fail(self._result[1])
  144. def observers(self) -> "Collection[defer.Deferred[_T]]":
  145. return self._observers
  146. def has_called(self) -> bool:
  147. return self._result is not None
  148. def has_succeeded(self) -> bool:
  149. return self._result is not None and self._result[0] is True
  150. def get_result(self) -> Union[_T, Failure]:
  151. if self._result is None:
  152. raise ValueError(f"{self!r} has no result yet")
  153. return self._result[1]
  154. def __getattr__(self, name: str) -> Any:
  155. return getattr(self._deferred, name)
  156. def __setattr__(self, name: str, value: Any) -> None:
  157. setattr(self._deferred, name, value)
  158. def __repr__(self) -> str:
  159. return "<ObservableDeferred object at %s, result=%r, _deferred=%r>" % (
  160. id(self),
  161. self._result,
  162. self._deferred,
  163. )
  164. T = TypeVar("T")
  165. async def concurrently_execute(
  166. func: Callable[[T], Any], args: Iterable[T], limit: int
  167. ) -> None:
  168. """Executes the function with each argument concurrently while limiting
  169. the number of concurrent executions.
  170. Args:
  171. func: Function to execute, should return a deferred or coroutine.
  172. args: List of arguments to pass to func, each invocation of func
  173. gets a single argument.
  174. limit: Maximum number of conccurent executions.
  175. Returns:
  176. Deferred: Resolved when all function invocations have finished.
  177. """
  178. it = iter(args)
  179. async def _concurrently_execute_inner(value: T) -> None:
  180. try:
  181. while True:
  182. await maybe_awaitable(func(value))
  183. value = next(it)
  184. except StopIteration:
  185. pass
  186. # We use `itertools.islice` to handle the case where the number of args is
  187. # less than the limit, avoiding needlessly spawning unnecessary background
  188. # tasks.
  189. await yieldable_gather_results(
  190. _concurrently_execute_inner, (value for value in itertools.islice(it, limit))
  191. )
  192. async def yieldable_gather_results(
  193. func: Callable[..., Awaitable[T]], iter: Iterable, *args: Any, **kwargs: Any
  194. ) -> List[T]:
  195. """Executes the function with each argument concurrently.
  196. Args:
  197. func: Function to execute that returns a Deferred
  198. iter: An iterable that yields items that get passed as the first
  199. argument to the function
  200. *args: Arguments to be passed to each call to func
  201. **kwargs: Keyword arguments to be passed to each call to func
  202. Returns
  203. A list containing the results of the function
  204. """
  205. try:
  206. return await make_deferred_yieldable(
  207. defer.gatherResults(
  208. [run_in_background(func, item, *args, **kwargs) for item in iter],
  209. consumeErrors=True,
  210. )
  211. )
  212. except defer.FirstError as dfe:
  213. # unwrap the error from defer.gatherResults.
  214. # The raised exception's traceback only includes func() etc if
  215. # the 'await' happens before the exception is thrown - ie if the failure
  216. # happens *asynchronously* - otherwise Twisted throws away the traceback as it
  217. # could be large.
  218. #
  219. # We could maybe reconstruct a fake traceback from Failure.frames. Or maybe
  220. # we could throw Twisted into the fires of Mordor.
  221. # suppress exception chaining, because the FirstError doesn't tell us anything
  222. # very interesting.
  223. assert isinstance(dfe.subFailure.value, BaseException)
  224. raise dfe.subFailure.value from None
  225. T1 = TypeVar("T1")
  226. T2 = TypeVar("T2")
  227. T3 = TypeVar("T3")
  228. @overload
  229. def gather_results(
  230. deferredList: Tuple[()], consumeErrors: bool = ...
  231. ) -> "defer.Deferred[Tuple[()]]":
  232. ...
  233. @overload
  234. def gather_results(
  235. deferredList: Tuple["defer.Deferred[T1]"],
  236. consumeErrors: bool = ...,
  237. ) -> "defer.Deferred[Tuple[T1]]":
  238. ...
  239. @overload
  240. def gather_results(
  241. deferredList: Tuple["defer.Deferred[T1]", "defer.Deferred[T2]"],
  242. consumeErrors: bool = ...,
  243. ) -> "defer.Deferred[Tuple[T1, T2]]":
  244. ...
  245. @overload
  246. def gather_results(
  247. deferredList: Tuple[
  248. "defer.Deferred[T1]", "defer.Deferred[T2]", "defer.Deferred[T3]"
  249. ],
  250. consumeErrors: bool = ...,
  251. ) -> "defer.Deferred[Tuple[T1, T2, T3]]":
  252. ...
  253. def gather_results( # type: ignore[misc]
  254. deferredList: Tuple["defer.Deferred[T1]", ...],
  255. consumeErrors: bool = False,
  256. ) -> "defer.Deferred[Tuple[T1, ...]]":
  257. """Combines a tuple of `Deferred`s into a single `Deferred`.
  258. Wraps `defer.gatherResults` to provide type annotations that support heterogenous
  259. lists of `Deferred`s.
  260. """
  261. # The `type: ignore[misc]` above suppresses
  262. # "Overloaded function implementation cannot produce return type of signature 1/2/3"
  263. deferred = defer.gatherResults(deferredList, consumeErrors=consumeErrors)
  264. return deferred.addCallback(tuple)
  265. @attr.s(slots=True, auto_attribs=True)
  266. class _LinearizerEntry:
  267. # The number of things executing.
  268. count: int
  269. # Deferreds for the things blocked from executing.
  270. deferreds: collections.OrderedDict
  271. class Linearizer:
  272. """Limits concurrent access to resources based on a key. Useful to ensure
  273. only a few things happen at a time on a given resource.
  274. Example:
  275. with await limiter.queue("test_key"):
  276. # do some work.
  277. """
  278. def __init__(
  279. self,
  280. name: Optional[str] = None,
  281. max_count: int = 1,
  282. clock: Optional[Clock] = None,
  283. ):
  284. """
  285. Args:
  286. max_count: The maximum number of concurrent accesses
  287. """
  288. if name is None:
  289. self.name: Union[str, int] = id(self)
  290. else:
  291. self.name = name
  292. if not clock:
  293. from twisted.internet import reactor
  294. clock = Clock(cast(IReactorTime, reactor))
  295. self._clock = clock
  296. self.max_count = max_count
  297. # key_to_defer is a map from the key to a _LinearizerEntry.
  298. self.key_to_defer: Dict[Hashable, _LinearizerEntry] = {}
  299. def is_queued(self, key: Hashable) -> bool:
  300. """Checks whether there is a process queued up waiting"""
  301. entry = self.key_to_defer.get(key)
  302. if not entry:
  303. # No entry so nothing is waiting.
  304. return False
  305. # There are waiting deferreds only in the OrderedDict of deferreds is
  306. # non-empty.
  307. return bool(entry.deferreds)
  308. def queue(self, key: Hashable) -> defer.Deferred:
  309. # we avoid doing defer.inlineCallbacks here, so that cancellation works correctly.
  310. # (https://twistedmatrix.com/trac/ticket/4632 meant that cancellations were not
  311. # propagated inside inlineCallbacks until Twisted 18.7)
  312. entry = self.key_to_defer.setdefault(
  313. key, _LinearizerEntry(0, collections.OrderedDict())
  314. )
  315. # If the number of things executing is greater than the maximum
  316. # then add a deferred to the list of blocked items
  317. # When one of the things currently executing finishes it will callback
  318. # this item so that it can continue executing.
  319. if entry.count >= self.max_count:
  320. res = self._await_lock(key)
  321. else:
  322. logger.debug(
  323. "Acquired uncontended linearizer lock %r for key %r", self.name, key
  324. )
  325. entry.count += 1
  326. res = defer.succeed(None)
  327. # once we successfully get the lock, we need to return a context manager which
  328. # will release the lock.
  329. @contextmanager
  330. def _ctx_manager(_: None) -> Iterator[None]:
  331. try:
  332. yield
  333. finally:
  334. logger.debug("Releasing linearizer lock %r for key %r", self.name, key)
  335. # We've finished executing so check if there are any things
  336. # blocked waiting to execute and start one of them
  337. entry.count -= 1
  338. if entry.deferreds:
  339. (next_def, _) = entry.deferreds.popitem(last=False)
  340. # we need to run the next thing in the sentinel context.
  341. with PreserveLoggingContext():
  342. next_def.callback(None)
  343. elif entry.count == 0:
  344. # We were the last thing for this key: remove it from the
  345. # map.
  346. del self.key_to_defer[key]
  347. res.addCallback(_ctx_manager)
  348. return res
  349. def _await_lock(self, key: Hashable) -> defer.Deferred:
  350. """Helper for queue: adds a deferred to the queue
  351. Assumes that we've already checked that we've reached the limit of the number
  352. of lock-holders we allow. Creates a new deferred which is added to the list, and
  353. adds some management around cancellations.
  354. Returns the deferred, which will callback once we have secured the lock.
  355. """
  356. entry = self.key_to_defer[key]
  357. logger.debug("Waiting to acquire linearizer lock %r for key %r", self.name, key)
  358. new_defer: "defer.Deferred[None]" = make_deferred_yieldable(defer.Deferred())
  359. entry.deferreds[new_defer] = 1
  360. def cb(_r: None) -> "defer.Deferred[None]":
  361. logger.debug("Acquired linearizer lock %r for key %r", self.name, key)
  362. entry.count += 1
  363. # if the code holding the lock completes synchronously, then it
  364. # will recursively run the next claimant on the list. That can
  365. # relatively rapidly lead to stack exhaustion. This is essentially
  366. # the same problem as http://twistedmatrix.com/trac/ticket/9304.
  367. #
  368. # In order to break the cycle, we add a cheeky sleep(0) here to
  369. # ensure that we fall back to the reactor between each iteration.
  370. #
  371. # (This needs to happen while we hold the lock, and the context manager's exit
  372. # code must be synchronous, so this is the only sensible place.)
  373. return self._clock.sleep(0)
  374. def eb(e: Failure) -> Failure:
  375. logger.info("defer %r got err %r", new_defer, e)
  376. if isinstance(e, CancelledError):
  377. logger.debug(
  378. "Cancelling wait for linearizer lock %r for key %r", self.name, key
  379. )
  380. else:
  381. logger.warning(
  382. "Unexpected exception waiting for linearizer lock %r for key %r",
  383. self.name,
  384. key,
  385. )
  386. # we just have to take ourselves back out of the queue.
  387. del entry.deferreds[new_defer]
  388. return e
  389. new_defer.addCallbacks(cb, eb)
  390. return new_defer
  391. class ReadWriteLock:
  392. """An async read write lock.
  393. Example:
  394. async with read_write_lock.read("test_key"):
  395. # do some work
  396. """
  397. # IMPLEMENTATION NOTES
  398. #
  399. # We track the most recent queued reader and writer deferreds (which get
  400. # resolved when they release the lock).
  401. #
  402. # Read: We know its safe to acquire a read lock when the latest writer has
  403. # been resolved. The new reader is appended to the list of latest readers.
  404. #
  405. # Write: We know its safe to acquire the write lock when both the latest
  406. # writers and readers have been resolved. The new writer replaces the latest
  407. # writer.
  408. def __init__(self) -> None:
  409. # Latest readers queued
  410. self.key_to_current_readers: Dict[str, Set[defer.Deferred]] = {}
  411. # Latest writer queued
  412. self.key_to_current_writer: Dict[str, defer.Deferred] = {}
  413. def read(self, key: str) -> AsyncContextManager:
  414. @asynccontextmanager
  415. async def _ctx_manager() -> AsyncIterator[None]:
  416. new_defer: "defer.Deferred[None]" = defer.Deferred()
  417. curr_readers = self.key_to_current_readers.setdefault(key, set())
  418. curr_writer = self.key_to_current_writer.get(key, None)
  419. curr_readers.add(new_defer)
  420. try:
  421. # We wait for the latest writer to finish writing. We can safely ignore
  422. # any existing readers... as they're readers.
  423. # May raise a `CancelledError` if the `Deferred` wrapping us is
  424. # cancelled. The `Deferred` we are waiting on must not be cancelled,
  425. # since we do not own it.
  426. if curr_writer:
  427. await make_deferred_yieldable(stop_cancellation(curr_writer))
  428. yield
  429. finally:
  430. with PreserveLoggingContext():
  431. new_defer.callback(None)
  432. self.key_to_current_readers.get(key, set()).discard(new_defer)
  433. return _ctx_manager()
  434. def write(self, key: str) -> AsyncContextManager:
  435. @asynccontextmanager
  436. async def _ctx_manager() -> AsyncIterator[None]:
  437. new_defer: "defer.Deferred[None]" = defer.Deferred()
  438. curr_readers = self.key_to_current_readers.get(key, set())
  439. curr_writer = self.key_to_current_writer.get(key, None)
  440. # We wait on all latest readers and writer.
  441. to_wait_on = list(curr_readers)
  442. if curr_writer:
  443. to_wait_on.append(curr_writer)
  444. # We can clear the list of current readers since `new_defer` waits
  445. # for them to finish.
  446. curr_readers.clear()
  447. self.key_to_current_writer[key] = new_defer
  448. to_wait_on_defer = defer.gatherResults(to_wait_on)
  449. try:
  450. # Wait for all current readers and the latest writer to finish.
  451. # May raise a `CancelledError` immediately after the wait if the
  452. # `Deferred` wrapping us is cancelled. We must only release the lock
  453. # once we have acquired it, hence the use of `delay_cancellation`
  454. # rather than `stop_cancellation`.
  455. await make_deferred_yieldable(delay_cancellation(to_wait_on_defer))
  456. yield
  457. finally:
  458. # Release the lock.
  459. with PreserveLoggingContext():
  460. new_defer.callback(None)
  461. # `self.key_to_current_writer[key]` may be missing if there was another
  462. # writer waiting for us and it completed entirely within the
  463. # `new_defer.callback()` call above.
  464. if self.key_to_current_writer.get(key) == new_defer:
  465. self.key_to_current_writer.pop(key)
  466. return _ctx_manager()
  467. R = TypeVar("R")
  468. def timeout_deferred(
  469. deferred: "defer.Deferred[_T]", timeout: float, reactor: IReactorTime
  470. ) -> "defer.Deferred[_T]":
  471. """The in built twisted `Deferred.addTimeout` fails to time out deferreds
  472. that have a canceller that throws exceptions. This method creates a new
  473. deferred that wraps and times out the given deferred, correctly handling
  474. the case where the given deferred's canceller throws.
  475. (See https://twistedmatrix.com/trac/ticket/9534)
  476. NOTE: Unlike `Deferred.addTimeout`, this function returns a new deferred.
  477. NOTE: the TimeoutError raised by the resultant deferred is
  478. twisted.internet.defer.TimeoutError, which is *different* to the built-in
  479. TimeoutError, as well as various other TimeoutErrors you might have imported.
  480. Args:
  481. deferred: The Deferred to potentially timeout.
  482. timeout: Timeout in seconds
  483. reactor: The twisted reactor to use
  484. Returns:
  485. A new Deferred, which will errback with defer.TimeoutError on timeout.
  486. """
  487. new_d: "defer.Deferred[_T]" = defer.Deferred()
  488. timed_out = [False]
  489. def time_it_out() -> None:
  490. timed_out[0] = True
  491. try:
  492. deferred.cancel()
  493. except Exception: # if we throw any exception it'll break time outs
  494. logger.exception("Canceller failed during timeout")
  495. # the cancel() call should have set off a chain of errbacks which
  496. # will have errbacked new_d, but in case it hasn't, errback it now.
  497. if not new_d.called:
  498. new_d.errback(defer.TimeoutError("Timed out after %gs" % (timeout,)))
  499. delayed_call = reactor.callLater(timeout, time_it_out)
  500. def convert_cancelled(value: Failure) -> Failure:
  501. # if the original deferred was cancelled, and our timeout has fired, then
  502. # the reason it was cancelled was due to our timeout. Turn the CancelledError
  503. # into a TimeoutError.
  504. if timed_out[0] and value.check(CancelledError):
  505. raise defer.TimeoutError("Timed out after %gs" % (timeout,))
  506. return value
  507. deferred.addErrback(convert_cancelled)
  508. def cancel_timeout(result: _T) -> _T:
  509. # stop the pending call to cancel the deferred if it's been fired
  510. if delayed_call.active():
  511. delayed_call.cancel()
  512. return result
  513. deferred.addBoth(cancel_timeout)
  514. def success_cb(val: _T) -> None:
  515. if not new_d.called:
  516. new_d.callback(val)
  517. def failure_cb(val: Failure) -> None:
  518. if not new_d.called:
  519. new_d.errback(val)
  520. deferred.addCallbacks(success_cb, failure_cb)
  521. return new_d
  522. # This class can't be generic because it uses slots with attrs.
  523. # See: https://github.com/python-attrs/attrs/issues/313
  524. @attr.s(slots=True, frozen=True, auto_attribs=True)
  525. class DoneAwaitable: # should be: Generic[R]
  526. """Simple awaitable that returns the provided value."""
  527. value: Any # should be: R
  528. def __await__(self) -> Any:
  529. return self
  530. def __iter__(self) -> "DoneAwaitable":
  531. return self
  532. def __next__(self) -> None:
  533. raise StopIteration(self.value)
  534. def maybe_awaitable(value: Union[Awaitable[R], R]) -> Awaitable[R]:
  535. """Convert a value to an awaitable if not already an awaitable."""
  536. if inspect.isawaitable(value):
  537. assert isinstance(value, Awaitable)
  538. return value
  539. return DoneAwaitable(value)
  540. def stop_cancellation(deferred: "defer.Deferred[T]") -> "defer.Deferred[T]":
  541. """Prevent a `Deferred` from being cancelled by wrapping it in another `Deferred`.
  542. Args:
  543. deferred: The `Deferred` to protect against cancellation. Must not follow the
  544. Synapse logcontext rules.
  545. Returns:
  546. A new `Deferred`, which will contain the result of the original `Deferred`.
  547. The new `Deferred` will not propagate cancellation through to the original.
  548. When cancelled, the new `Deferred` will fail with a `CancelledError`.
  549. The new `Deferred` will not follow the Synapse logcontext rules and should be
  550. wrapped with `make_deferred_yieldable`.
  551. """
  552. new_deferred: "defer.Deferred[T]" = defer.Deferred()
  553. deferred.chainDeferred(new_deferred)
  554. return new_deferred
  555. def delay_cancellation(deferred: "defer.Deferred[T]") -> "defer.Deferred[T]":
  556. """Delay cancellation of a `Deferred` until it resolves.
  557. Has the same effect as `stop_cancellation`, but the returned `Deferred` will not
  558. resolve with a `CancelledError` until the original `Deferred` resolves.
  559. Args:
  560. deferred: The `Deferred` to protect against cancellation. May optionally follow
  561. the Synapse logcontext rules.
  562. Returns:
  563. A new `Deferred`, which will contain the result of the original `Deferred`.
  564. The new `Deferred` will not propagate cancellation through to the original.
  565. When cancelled, the new `Deferred` will wait until the original `Deferred`
  566. resolves before failing with a `CancelledError`.
  567. The new `Deferred` will follow the Synapse logcontext rules if `deferred`
  568. follows the Synapse logcontext rules. Otherwise the new `Deferred` should be
  569. wrapped with `make_deferred_yieldable`.
  570. """
  571. def handle_cancel(new_deferred: "defer.Deferred[T]") -> None:
  572. # before the new deferred is cancelled, we `pause` it to stop the cancellation
  573. # propagating. we then `unpause` it once the wrapped deferred completes, to
  574. # propagate the exception.
  575. new_deferred.pause()
  576. new_deferred.errback(Failure(CancelledError()))
  577. deferred.addBoth(lambda _: new_deferred.unpause())
  578. new_deferred: "defer.Deferred[T]" = defer.Deferred(handle_cancel)
  579. deferred.chainDeferred(new_deferred)
  580. return new_deferred