async_helpers.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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 asyncio
  17. import collections
  18. import inspect
  19. import itertools
  20. import logging
  21. from contextlib import asynccontextmanager
  22. from typing import (
  23. Any,
  24. AsyncIterator,
  25. Awaitable,
  26. Callable,
  27. Collection,
  28. Coroutine,
  29. Dict,
  30. Generic,
  31. Hashable,
  32. Iterable,
  33. List,
  34. Optional,
  35. Set,
  36. Tuple,
  37. TypeVar,
  38. Union,
  39. cast,
  40. overload,
  41. )
  42. import attr
  43. from typing_extensions import AsyncContextManager, Literal
  44. from twisted.internet import defer
  45. from twisted.internet.defer import CancelledError
  46. from twisted.internet.interfaces import IReactorTime
  47. from twisted.python.failure import Failure
  48. from synapse.logging.context import (
  49. PreserveLoggingContext,
  50. make_deferred_yieldable,
  51. run_in_background,
  52. )
  53. from synapse.util import Clock
  54. logger = logging.getLogger(__name__)
  55. _T = TypeVar("_T")
  56. class AbstractObservableDeferred(Generic[_T], metaclass=abc.ABCMeta):
  57. """Abstract base class defining the consumer interface of ObservableDeferred"""
  58. __slots__ = ()
  59. @abc.abstractmethod
  60. def observe(self) -> "defer.Deferred[_T]":
  61. """Add a new observer for this ObservableDeferred
  62. This returns a brand new deferred that is resolved when the underlying
  63. deferred is resolved. Interacting with the returned deferred does not
  64. effect the underlying deferred.
  65. Note that the returned Deferred doesn't follow the Synapse logcontext rules -
  66. you will probably want to `make_deferred_yieldable` it.
  67. """
  68. ...
  69. class ObservableDeferred(Generic[_T], AbstractObservableDeferred[_T]):
  70. """Wraps a deferred object so that we can add observer deferreds. These
  71. observer deferreds do not affect the callback chain of the original
  72. deferred.
  73. If consumeErrors is true errors will be captured from the origin deferred.
  74. Cancelling or otherwise resolving an observer will not affect the original
  75. ObservableDeferred.
  76. NB that it does not attempt to do anything with logcontexts; in general
  77. you should probably make_deferred_yieldable the deferreds
  78. returned by `observe`, and ensure that the original deferred runs its
  79. callbacks in the sentinel logcontext.
  80. """
  81. __slots__ = ["_deferred", "_observers", "_result"]
  82. _deferred: "defer.Deferred[_T]"
  83. _observers: Union[List["defer.Deferred[_T]"], Tuple[()]]
  84. _result: Union[None, Tuple[Literal[True], _T], Tuple[Literal[False], Failure]]
  85. def __init__(self, deferred: "defer.Deferred[_T]", consumeErrors: bool = False):
  86. object.__setattr__(self, "_deferred", deferred)
  87. object.__setattr__(self, "_result", None)
  88. object.__setattr__(self, "_observers", [])
  89. def callback(r: _T) -> _T:
  90. object.__setattr__(self, "_result", (True, r))
  91. # once we have set _result, no more entries will be added to _observers,
  92. # so it's safe to replace it with the empty tuple.
  93. observers = self._observers
  94. object.__setattr__(self, "_observers", ())
  95. for observer in observers:
  96. try:
  97. observer.callback(r)
  98. except Exception as e:
  99. logger.exception(
  100. "%r threw an exception on .callback(%r), ignoring...",
  101. observer,
  102. r,
  103. exc_info=e,
  104. )
  105. return r
  106. def errback(f: Failure) -> Optional[Failure]:
  107. object.__setattr__(self, "_result", (False, f))
  108. # once we have set _result, no more entries will be added to _observers,
  109. # so it's safe to replace it with the empty tuple.
  110. observers = self._observers
  111. object.__setattr__(self, "_observers", ())
  112. for observer in observers:
  113. # This is a little bit of magic to correctly propagate stack
  114. # traces when we `await` on one of the observer deferreds.
  115. f.value.__failure__ = f # type: ignore[union-attr]
  116. try:
  117. observer.errback(f)
  118. except Exception as e:
  119. logger.exception(
  120. "%r threw an exception on .errback(%r), ignoring...",
  121. observer,
  122. f,
  123. exc_info=e,
  124. )
  125. if consumeErrors:
  126. return None
  127. else:
  128. return f
  129. deferred.addCallbacks(callback, errback)
  130. def observe(self) -> "defer.Deferred[_T]":
  131. """Observe the underlying deferred.
  132. This returns a brand new deferred that is resolved when the underlying
  133. deferred is resolved. Interacting with the returned deferred does not
  134. effect the underlying deferred.
  135. """
  136. if not self._result:
  137. assert isinstance(self._observers, list)
  138. d: "defer.Deferred[_T]" = defer.Deferred()
  139. self._observers.append(d)
  140. return d
  141. elif self._result[0]:
  142. return defer.succeed(self._result[1])
  143. else:
  144. return defer.fail(self._result[1])
  145. def observers(self) -> "Collection[defer.Deferred[_T]]":
  146. return self._observers
  147. def has_called(self) -> bool:
  148. return self._result is not None
  149. def has_succeeded(self) -> bool:
  150. return self._result is not None and self._result[0] is True
  151. def get_result(self) -> Union[_T, Failure]:
  152. if self._result is None:
  153. raise ValueError(f"{self!r} has no result yet")
  154. return self._result[1]
  155. def __getattr__(self, name: str) -> Any:
  156. return getattr(self._deferred, name)
  157. def __setattr__(self, name: str, value: Any) -> None:
  158. setattr(self._deferred, name, value)
  159. def __repr__(self) -> str:
  160. return "<ObservableDeferred object at %s, result=%r, _deferred=%r>" % (
  161. id(self),
  162. self._result,
  163. self._deferred,
  164. )
  165. T = TypeVar("T")
  166. async def concurrently_execute(
  167. func: Callable[[T], Any], args: Iterable[T], limit: int
  168. ) -> None:
  169. """Executes the function with each argument concurrently while limiting
  170. the number of concurrent executions.
  171. Args:
  172. func: Function to execute, should return a deferred or coroutine.
  173. args: List of arguments to pass to func, each invocation of func
  174. gets a single argument.
  175. limit: Maximum number of conccurent executions.
  176. Returns:
  177. Deferred: Resolved when all function invocations have finished.
  178. """
  179. it = iter(args)
  180. async def _concurrently_execute_inner(value: T) -> None:
  181. try:
  182. while True:
  183. await maybe_awaitable(func(value))
  184. value = next(it)
  185. except StopIteration:
  186. pass
  187. # We use `itertools.islice` to handle the case where the number of args is
  188. # less than the limit, avoiding needlessly spawning unnecessary background
  189. # tasks.
  190. await yieldable_gather_results(
  191. _concurrently_execute_inner, (value for value in itertools.islice(it, limit))
  192. )
  193. async def yieldable_gather_results(
  194. func: Callable[..., Awaitable[T]], iter: Iterable, *args: Any, **kwargs: Any
  195. ) -> List[T]:
  196. """Executes the function with each argument concurrently.
  197. Args:
  198. func: Function to execute that returns a Deferred
  199. iter: An iterable that yields items that get passed as the first
  200. argument to the function
  201. *args: Arguments to be passed to each call to func
  202. **kwargs: Keyword arguments to be passed to each call to func
  203. Returns
  204. A list containing the results of the function
  205. """
  206. try:
  207. return await make_deferred_yieldable(
  208. defer.gatherResults(
  209. [run_in_background(func, item, *args, **kwargs) for item in iter],
  210. consumeErrors=True,
  211. )
  212. )
  213. except defer.FirstError as dfe:
  214. # unwrap the error from defer.gatherResults.
  215. # The raised exception's traceback only includes func() etc if
  216. # the 'await' happens before the exception is thrown - ie if the failure
  217. # happens *asynchronously* - otherwise Twisted throws away the traceback as it
  218. # could be large.
  219. #
  220. # We could maybe reconstruct a fake traceback from Failure.frames. Or maybe
  221. # we could throw Twisted into the fires of Mordor.
  222. # suppress exception chaining, because the FirstError doesn't tell us anything
  223. # very interesting.
  224. assert isinstance(dfe.subFailure.value, BaseException)
  225. raise dfe.subFailure.value from None
  226. T1 = TypeVar("T1")
  227. T2 = TypeVar("T2")
  228. T3 = TypeVar("T3")
  229. @overload
  230. def gather_results(
  231. deferredList: Tuple[()], consumeErrors: bool = ...
  232. ) -> "defer.Deferred[Tuple[()]]":
  233. ...
  234. @overload
  235. def gather_results(
  236. deferredList: Tuple["defer.Deferred[T1]"],
  237. consumeErrors: bool = ...,
  238. ) -> "defer.Deferred[Tuple[T1]]":
  239. ...
  240. @overload
  241. def gather_results(
  242. deferredList: Tuple["defer.Deferred[T1]", "defer.Deferred[T2]"],
  243. consumeErrors: bool = ...,
  244. ) -> "defer.Deferred[Tuple[T1, T2]]":
  245. ...
  246. @overload
  247. def gather_results(
  248. deferredList: Tuple[
  249. "defer.Deferred[T1]", "defer.Deferred[T2]", "defer.Deferred[T3]"
  250. ],
  251. consumeErrors: bool = ...,
  252. ) -> "defer.Deferred[Tuple[T1, T2, T3]]":
  253. ...
  254. def gather_results( # type: ignore[misc]
  255. deferredList: Tuple["defer.Deferred[T1]", ...],
  256. consumeErrors: bool = False,
  257. ) -> "defer.Deferred[Tuple[T1, ...]]":
  258. """Combines a tuple of `Deferred`s into a single `Deferred`.
  259. Wraps `defer.gatherResults` to provide type annotations that support heterogenous
  260. lists of `Deferred`s.
  261. """
  262. # The `type: ignore[misc]` above suppresses
  263. # "Overloaded function implementation cannot produce return type of signature 1/2/3"
  264. deferred = defer.gatherResults(deferredList, consumeErrors=consumeErrors)
  265. return deferred.addCallback(tuple)
  266. @attr.s(slots=True, auto_attribs=True)
  267. class _LinearizerEntry:
  268. # The number of things executing.
  269. count: int
  270. # Deferreds for the things blocked from executing.
  271. deferreds: collections.OrderedDict
  272. class Linearizer:
  273. """Limits concurrent access to resources based on a key. Useful to ensure
  274. only a few things happen at a time on a given resource.
  275. Example:
  276. async with limiter.queue("test_key"):
  277. # do some work.
  278. """
  279. def __init__(
  280. self,
  281. name: Optional[str] = None,
  282. max_count: int = 1,
  283. clock: Optional[Clock] = None,
  284. ):
  285. """
  286. Args:
  287. max_count: The maximum number of concurrent accesses
  288. """
  289. if name is None:
  290. self.name: Union[str, int] = id(self)
  291. else:
  292. self.name = name
  293. if not clock:
  294. from twisted.internet import reactor
  295. clock = Clock(cast(IReactorTime, reactor))
  296. self._clock = clock
  297. self.max_count = max_count
  298. # key_to_defer is a map from the key to a _LinearizerEntry.
  299. self.key_to_defer: Dict[Hashable, _LinearizerEntry] = {}
  300. def is_queued(self, key: Hashable) -> bool:
  301. """Checks whether there is a process queued up waiting"""
  302. entry = self.key_to_defer.get(key)
  303. if not entry:
  304. # No entry so nothing is waiting.
  305. return False
  306. # There are waiting deferreds only in the OrderedDict of deferreds is
  307. # non-empty.
  308. return bool(entry.deferreds)
  309. def queue(self, key: Hashable) -> AsyncContextManager[None]:
  310. @asynccontextmanager
  311. async def _ctx_manager() -> AsyncIterator[None]:
  312. entry = await self._acquire_lock(key)
  313. try:
  314. yield
  315. finally:
  316. self._release_lock(key, entry)
  317. return _ctx_manager()
  318. async def _acquire_lock(self, key: Hashable) -> _LinearizerEntry:
  319. """Acquires a linearizer lock, waiting if necessary.
  320. Returns once we have secured the lock.
  321. """
  322. entry = self.key_to_defer.setdefault(
  323. key, _LinearizerEntry(0, collections.OrderedDict())
  324. )
  325. if entry.count < self.max_count:
  326. # The number of things executing is less than the maximum.
  327. logger.debug(
  328. "Acquired uncontended linearizer lock %r for key %r", self.name, key
  329. )
  330. entry.count += 1
  331. return entry
  332. # Otherwise, the number of things executing is at the maximum and we have to
  333. # add a deferred to the list of blocked items.
  334. # When one of the things currently executing finishes it will callback
  335. # this item so that it can continue executing.
  336. logger.debug("Waiting to acquire linearizer lock %r for key %r", self.name, key)
  337. new_defer: "defer.Deferred[None]" = make_deferred_yieldable(defer.Deferred())
  338. entry.deferreds[new_defer] = 1
  339. try:
  340. await new_defer
  341. except Exception as e:
  342. logger.info("defer %r got err %r", new_defer, e)
  343. if isinstance(e, CancelledError):
  344. logger.debug(
  345. "Cancelling wait for linearizer lock %r for key %r",
  346. self.name,
  347. key,
  348. )
  349. else:
  350. logger.warning(
  351. "Unexpected exception waiting for linearizer lock %r for key %r",
  352. self.name,
  353. key,
  354. )
  355. # we just have to take ourselves back out of the queue.
  356. del entry.deferreds[new_defer]
  357. raise
  358. logger.debug("Acquired linearizer lock %r for key %r", self.name, key)
  359. entry.count += 1
  360. # if the code holding the lock completes synchronously, then it
  361. # will recursively run the next claimant on the list. That can
  362. # relatively rapidly lead to stack exhaustion. This is essentially
  363. # the same problem as http://twistedmatrix.com/trac/ticket/9304.
  364. #
  365. # In order to break the cycle, we add a cheeky sleep(0) here to
  366. # ensure that we fall back to the reactor between each iteration.
  367. #
  368. # This needs to happen while we hold the lock. We could put it on the
  369. # exit path, but that would slow down the uncontended case.
  370. try:
  371. await self._clock.sleep(0)
  372. except CancelledError:
  373. self._release_lock(key, entry)
  374. raise
  375. return entry
  376. def _release_lock(self, key: Hashable, entry: _LinearizerEntry) -> None:
  377. """Releases a held linearizer lock."""
  378. logger.debug("Releasing linearizer lock %r for key %r", self.name, key)
  379. # We've finished executing so check if there are any things
  380. # blocked waiting to execute and start one of them
  381. entry.count -= 1
  382. if entry.deferreds:
  383. (next_def, _) = entry.deferreds.popitem(last=False)
  384. # we need to run the next thing in the sentinel context.
  385. with PreserveLoggingContext():
  386. next_def.callback(None)
  387. elif entry.count == 0:
  388. # We were the last thing for this key: remove it from the
  389. # map.
  390. del self.key_to_defer[key]
  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. @overload
  556. def delay_cancellation(awaitable: "defer.Deferred[T]") -> "defer.Deferred[T]":
  557. ...
  558. @overload
  559. def delay_cancellation(awaitable: Coroutine[Any, Any, T]) -> "defer.Deferred[T]":
  560. ...
  561. @overload
  562. def delay_cancellation(awaitable: Awaitable[T]) -> Awaitable[T]:
  563. ...
  564. def delay_cancellation(awaitable: Awaitable[T]) -> Awaitable[T]:
  565. """Delay cancellation of a coroutine or `Deferred` awaitable until it resolves.
  566. Has the same effect as `stop_cancellation`, but the returned `Deferred` will not
  567. resolve with a `CancelledError` until the original awaitable resolves.
  568. Args:
  569. deferred: The coroutine or `Deferred` to protect against cancellation. May
  570. optionally follow the Synapse logcontext rules.
  571. Returns:
  572. A new `Deferred`, which will contain the result of the original coroutine or
  573. `Deferred`. The new `Deferred` will not propagate cancellation through to the
  574. original coroutine or `Deferred`.
  575. When cancelled, the new `Deferred` will wait until the original coroutine or
  576. `Deferred` resolves before failing with a `CancelledError`.
  577. The new `Deferred` will follow the Synapse logcontext rules if `awaitable`
  578. follows the Synapse logcontext rules. Otherwise the new `Deferred` should be
  579. wrapped with `make_deferred_yieldable`.
  580. """
  581. # First, convert the awaitable into a `Deferred`.
  582. if isinstance(awaitable, defer.Deferred):
  583. deferred = awaitable
  584. elif asyncio.iscoroutine(awaitable):
  585. # Ideally we'd use `Deferred.fromCoroutine()` here, to save on redundant
  586. # type-checking, but we'd need Twisted >= 21.2.
  587. deferred = defer.ensureDeferred(awaitable)
  588. else:
  589. # We have no idea what to do with this awaitable.
  590. # We assume it's already resolved, such as `DoneAwaitable`s or `Future`s from
  591. # `make_awaitable`, and let the caller `await` it normally.
  592. return awaitable
  593. def handle_cancel(new_deferred: "defer.Deferred[T]") -> None:
  594. # before the new deferred is cancelled, we `pause` it to stop the cancellation
  595. # propagating. we then `unpause` it once the wrapped deferred completes, to
  596. # propagate the exception.
  597. new_deferred.pause()
  598. new_deferred.errback(Failure(CancelledError()))
  599. deferred.addBoth(lambda _: new_deferred.unpause())
  600. new_deferred: "defer.Deferred[T]" = defer.Deferred(handle_cancel)
  601. deferred.chainDeferred(new_deferred)
  602. return new_deferred