async_helpers.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  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, Concatenate, Literal, ParamSpec
  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],
  168. args: Iterable[T],
  169. limit: int,
  170. delay_cancellation: bool = False,
  171. ) -> None:
  172. """Executes the function with each argument concurrently while limiting
  173. the number of concurrent executions.
  174. Args:
  175. func: Function to execute, should return a deferred or coroutine.
  176. args: List of arguments to pass to func, each invocation of func
  177. gets a single argument.
  178. limit: Maximum number of conccurent executions.
  179. delay_cancellation: Whether to delay cancellation until after the invocations
  180. have finished.
  181. Returns:
  182. None, when all function invocations have finished. The return values
  183. from those functions are discarded.
  184. """
  185. it = iter(args)
  186. async def _concurrently_execute_inner(value: T) -> None:
  187. try:
  188. while True:
  189. await maybe_awaitable(func(value))
  190. value = next(it)
  191. except StopIteration:
  192. pass
  193. # We use `itertools.islice` to handle the case where the number of args is
  194. # less than the limit, avoiding needlessly spawning unnecessary background
  195. # tasks.
  196. if delay_cancellation:
  197. await yieldable_gather_results_delaying_cancellation(
  198. _concurrently_execute_inner,
  199. (value for value in itertools.islice(it, limit)),
  200. )
  201. else:
  202. await yieldable_gather_results(
  203. _concurrently_execute_inner,
  204. (value for value in itertools.islice(it, limit)),
  205. )
  206. P = ParamSpec("P")
  207. R = TypeVar("R")
  208. async def yieldable_gather_results(
  209. func: Callable[Concatenate[T, P], Awaitable[R]],
  210. iter: Iterable[T],
  211. *args: P.args,
  212. **kwargs: P.kwargs,
  213. ) -> List[R]:
  214. """Executes the function with each argument concurrently.
  215. Args:
  216. func: Function to execute that returns a Deferred
  217. iter: An iterable that yields items that get passed as the first
  218. argument to the function
  219. *args: Arguments to be passed to each call to func
  220. **kwargs: Keyword arguments to be passed to each call to func
  221. Returns
  222. A list containing the results of the function
  223. """
  224. try:
  225. return await make_deferred_yieldable(
  226. defer.gatherResults(
  227. # type-ignore: mypy reports two errors:
  228. # error: Argument 1 to "run_in_background" has incompatible type
  229. # "Callable[[T, **P], Awaitable[R]]"; expected
  230. # "Callable[[T, **P], Awaitable[R]]" [arg-type]
  231. # error: Argument 2 to "run_in_background" has incompatible type
  232. # "T"; expected "[T, **P.args]" [arg-type]
  233. # The former looks like a mypy bug, and the latter looks like a
  234. # false positive.
  235. [run_in_background(func, item, *args, **kwargs) for item in iter], # type: ignore[arg-type]
  236. consumeErrors=True,
  237. )
  238. )
  239. except defer.FirstError as dfe:
  240. # unwrap the error from defer.gatherResults.
  241. # The raised exception's traceback only includes func() etc if
  242. # the 'await' happens before the exception is thrown - ie if the failure
  243. # happens *asynchronously* - otherwise Twisted throws away the traceback as it
  244. # could be large.
  245. #
  246. # We could maybe reconstruct a fake traceback from Failure.frames. Or maybe
  247. # we could throw Twisted into the fires of Mordor.
  248. # suppress exception chaining, because the FirstError doesn't tell us anything
  249. # very interesting.
  250. assert isinstance(dfe.subFailure.value, BaseException)
  251. raise dfe.subFailure.value from None
  252. async def yieldable_gather_results_delaying_cancellation(
  253. func: Callable[Concatenate[T, P], Awaitable[R]],
  254. iter: Iterable[T],
  255. *args: P.args,
  256. **kwargs: P.kwargs,
  257. ) -> List[R]:
  258. """Executes the function with each argument concurrently.
  259. Cancellation is delayed until after all the results have been gathered.
  260. See `yieldable_gather_results`.
  261. Args:
  262. func: Function to execute that returns a Deferred
  263. iter: An iterable that yields items that get passed as the first
  264. argument to the function
  265. *args: Arguments to be passed to each call to func
  266. **kwargs: Keyword arguments to be passed to each call to func
  267. Returns
  268. A list containing the results of the function
  269. """
  270. try:
  271. return await make_deferred_yieldable(
  272. delay_cancellation(
  273. defer.gatherResults(
  274. [run_in_background(func, item, *args, **kwargs) for item in iter], # type: ignore[arg-type]
  275. consumeErrors=True,
  276. )
  277. )
  278. )
  279. except defer.FirstError as dfe:
  280. assert isinstance(dfe.subFailure.value, BaseException)
  281. raise dfe.subFailure.value from None
  282. T1 = TypeVar("T1")
  283. T2 = TypeVar("T2")
  284. T3 = TypeVar("T3")
  285. @overload
  286. def gather_results(
  287. deferredList: Tuple[()], consumeErrors: bool = ...
  288. ) -> "defer.Deferred[Tuple[()]]":
  289. ...
  290. @overload
  291. def gather_results(
  292. deferredList: Tuple["defer.Deferred[T1]"],
  293. consumeErrors: bool = ...,
  294. ) -> "defer.Deferred[Tuple[T1]]":
  295. ...
  296. @overload
  297. def gather_results(
  298. deferredList: Tuple["defer.Deferred[T1]", "defer.Deferred[T2]"],
  299. consumeErrors: bool = ...,
  300. ) -> "defer.Deferred[Tuple[T1, T2]]":
  301. ...
  302. @overload
  303. def gather_results(
  304. deferredList: Tuple[
  305. "defer.Deferred[T1]", "defer.Deferred[T2]", "defer.Deferred[T3]"
  306. ],
  307. consumeErrors: bool = ...,
  308. ) -> "defer.Deferred[Tuple[T1, T2, T3]]":
  309. ...
  310. def gather_results( # type: ignore[misc]
  311. deferredList: Tuple["defer.Deferred[T1]", ...],
  312. consumeErrors: bool = False,
  313. ) -> "defer.Deferred[Tuple[T1, ...]]":
  314. """Combines a tuple of `Deferred`s into a single `Deferred`.
  315. Wraps `defer.gatherResults` to provide type annotations that support heterogenous
  316. lists of `Deferred`s.
  317. """
  318. # The `type: ignore[misc]` above suppresses
  319. # "Overloaded function implementation cannot produce return type of signature 1/2/3"
  320. deferred = defer.gatherResults(deferredList, consumeErrors=consumeErrors)
  321. return deferred.addCallback(tuple)
  322. @attr.s(slots=True, auto_attribs=True)
  323. class _LinearizerEntry:
  324. # The number of things executing.
  325. count: int
  326. # Deferreds for the things blocked from executing.
  327. deferreds: collections.OrderedDict
  328. class Linearizer:
  329. """Limits concurrent access to resources based on a key. Useful to ensure
  330. only a few things happen at a time on a given resource.
  331. Example:
  332. async with limiter.queue("test_key"):
  333. # do some work.
  334. """
  335. def __init__(
  336. self,
  337. name: Optional[str] = None,
  338. max_count: int = 1,
  339. clock: Optional[Clock] = None,
  340. ):
  341. """
  342. Args:
  343. max_count: The maximum number of concurrent accesses
  344. """
  345. if name is None:
  346. self.name: Union[str, int] = id(self)
  347. else:
  348. self.name = name
  349. if not clock:
  350. from twisted.internet import reactor
  351. clock = Clock(cast(IReactorTime, reactor))
  352. self._clock = clock
  353. self.max_count = max_count
  354. # key_to_defer is a map from the key to a _LinearizerEntry.
  355. self.key_to_defer: Dict[Hashable, _LinearizerEntry] = {}
  356. def is_queued(self, key: Hashable) -> bool:
  357. """Checks whether there is a process queued up waiting"""
  358. entry = self.key_to_defer.get(key)
  359. if not entry:
  360. # No entry so nothing is waiting.
  361. return False
  362. # There are waiting deferreds only in the OrderedDict of deferreds is
  363. # non-empty.
  364. return bool(entry.deferreds)
  365. def queue(self, key: Hashable) -> AsyncContextManager[None]:
  366. @asynccontextmanager
  367. async def _ctx_manager() -> AsyncIterator[None]:
  368. entry = await self._acquire_lock(key)
  369. try:
  370. yield
  371. finally:
  372. self._release_lock(key, entry)
  373. return _ctx_manager()
  374. async def _acquire_lock(self, key: Hashable) -> _LinearizerEntry:
  375. """Acquires a linearizer lock, waiting if necessary.
  376. Returns once we have secured the lock.
  377. """
  378. entry = self.key_to_defer.setdefault(
  379. key, _LinearizerEntry(0, collections.OrderedDict())
  380. )
  381. if entry.count < self.max_count:
  382. # The number of things executing is less than the maximum.
  383. logger.debug(
  384. "Acquired uncontended linearizer lock %r for key %r", self.name, key
  385. )
  386. entry.count += 1
  387. return entry
  388. # Otherwise, the number of things executing is at the maximum and we have to
  389. # add a deferred to the list of blocked items.
  390. # When one of the things currently executing finishes it will callback
  391. # this item so that it can continue executing.
  392. logger.debug("Waiting to acquire linearizer lock %r for key %r", self.name, key)
  393. new_defer: "defer.Deferred[None]" = make_deferred_yieldable(defer.Deferred())
  394. entry.deferreds[new_defer] = 1
  395. try:
  396. await new_defer
  397. except Exception as e:
  398. logger.info("defer %r got err %r", new_defer, e)
  399. if isinstance(e, CancelledError):
  400. logger.debug(
  401. "Cancelling wait for linearizer lock %r for key %r",
  402. self.name,
  403. key,
  404. )
  405. else:
  406. logger.warning(
  407. "Unexpected exception waiting for linearizer lock %r for key %r",
  408. self.name,
  409. key,
  410. )
  411. # we just have to take ourselves back out of the queue.
  412. del entry.deferreds[new_defer]
  413. raise
  414. logger.debug("Acquired linearizer lock %r for key %r", self.name, key)
  415. entry.count += 1
  416. # if the code holding the lock completes synchronously, then it
  417. # will recursively run the next claimant on the list. That can
  418. # relatively rapidly lead to stack exhaustion. This is essentially
  419. # the same problem as http://twistedmatrix.com/trac/ticket/9304.
  420. #
  421. # In order to break the cycle, we add a cheeky sleep(0) here to
  422. # ensure that we fall back to the reactor between each iteration.
  423. #
  424. # This needs to happen while we hold the lock. We could put it on the
  425. # exit path, but that would slow down the uncontended case.
  426. try:
  427. await self._clock.sleep(0)
  428. except CancelledError:
  429. self._release_lock(key, entry)
  430. raise
  431. return entry
  432. def _release_lock(self, key: Hashable, entry: _LinearizerEntry) -> None:
  433. """Releases a held linearizer lock."""
  434. logger.debug("Releasing linearizer lock %r for key %r", self.name, key)
  435. # We've finished executing so check if there are any things
  436. # blocked waiting to execute and start one of them
  437. entry.count -= 1
  438. if entry.deferreds:
  439. (next_def, _) = entry.deferreds.popitem(last=False)
  440. # we need to run the next thing in the sentinel context.
  441. with PreserveLoggingContext():
  442. next_def.callback(None)
  443. elif entry.count == 0:
  444. # We were the last thing for this key: remove it from the
  445. # map.
  446. del self.key_to_defer[key]
  447. class ReadWriteLock:
  448. """An async read write lock.
  449. Example:
  450. async with read_write_lock.read("test_key"):
  451. # do some work
  452. """
  453. # IMPLEMENTATION NOTES
  454. #
  455. # We track the most recent queued reader and writer deferreds (which get
  456. # resolved when they release the lock).
  457. #
  458. # Read: We know its safe to acquire a read lock when the latest writer has
  459. # been resolved. The new reader is appended to the list of latest readers.
  460. #
  461. # Write: We know its safe to acquire the write lock when both the latest
  462. # writers and readers have been resolved. The new writer replaces the latest
  463. # writer.
  464. def __init__(self) -> None:
  465. # Latest readers queued
  466. self.key_to_current_readers: Dict[str, Set[defer.Deferred]] = {}
  467. # Latest writer queued
  468. self.key_to_current_writer: Dict[str, defer.Deferred] = {}
  469. def read(self, key: str) -> AsyncContextManager:
  470. @asynccontextmanager
  471. async def _ctx_manager() -> AsyncIterator[None]:
  472. new_defer: "defer.Deferred[None]" = defer.Deferred()
  473. curr_readers = self.key_to_current_readers.setdefault(key, set())
  474. curr_writer = self.key_to_current_writer.get(key, None)
  475. curr_readers.add(new_defer)
  476. try:
  477. # We wait for the latest writer to finish writing. We can safely ignore
  478. # any existing readers... as they're readers.
  479. # May raise a `CancelledError` if the `Deferred` wrapping us is
  480. # cancelled. The `Deferred` we are waiting on must not be cancelled,
  481. # since we do not own it.
  482. if curr_writer:
  483. await make_deferred_yieldable(stop_cancellation(curr_writer))
  484. yield
  485. finally:
  486. with PreserveLoggingContext():
  487. new_defer.callback(None)
  488. self.key_to_current_readers.get(key, set()).discard(new_defer)
  489. return _ctx_manager()
  490. def write(self, key: str) -> AsyncContextManager:
  491. @asynccontextmanager
  492. async def _ctx_manager() -> AsyncIterator[None]:
  493. new_defer: "defer.Deferred[None]" = defer.Deferred()
  494. curr_readers = self.key_to_current_readers.get(key, set())
  495. curr_writer = self.key_to_current_writer.get(key, None)
  496. # We wait on all latest readers and writer.
  497. to_wait_on = list(curr_readers)
  498. if curr_writer:
  499. to_wait_on.append(curr_writer)
  500. # We can clear the list of current readers since `new_defer` waits
  501. # for them to finish.
  502. curr_readers.clear()
  503. self.key_to_current_writer[key] = new_defer
  504. to_wait_on_defer = defer.gatherResults(to_wait_on)
  505. try:
  506. # Wait for all current readers and the latest writer to finish.
  507. # May raise a `CancelledError` immediately after the wait if the
  508. # `Deferred` wrapping us is cancelled. We must only release the lock
  509. # once we have acquired it, hence the use of `delay_cancellation`
  510. # rather than `stop_cancellation`.
  511. await make_deferred_yieldable(delay_cancellation(to_wait_on_defer))
  512. yield
  513. finally:
  514. # Release the lock.
  515. with PreserveLoggingContext():
  516. new_defer.callback(None)
  517. # `self.key_to_current_writer[key]` may be missing if there was another
  518. # writer waiting for us and it completed entirely within the
  519. # `new_defer.callback()` call above.
  520. if self.key_to_current_writer.get(key) == new_defer:
  521. self.key_to_current_writer.pop(key)
  522. return _ctx_manager()
  523. def timeout_deferred(
  524. deferred: "defer.Deferred[_T]", timeout: float, reactor: IReactorTime
  525. ) -> "defer.Deferred[_T]":
  526. """The in built twisted `Deferred.addTimeout` fails to time out deferreds
  527. that have a canceller that throws exceptions. This method creates a new
  528. deferred that wraps and times out the given deferred, correctly handling
  529. the case where the given deferred's canceller throws.
  530. (See https://twistedmatrix.com/trac/ticket/9534)
  531. NOTE: Unlike `Deferred.addTimeout`, this function returns a new deferred.
  532. NOTE: the TimeoutError raised by the resultant deferred is
  533. twisted.internet.defer.TimeoutError, which is *different* to the built-in
  534. TimeoutError, as well as various other TimeoutErrors you might have imported.
  535. Args:
  536. deferred: The Deferred to potentially timeout.
  537. timeout: Timeout in seconds
  538. reactor: The twisted reactor to use
  539. Returns:
  540. A new Deferred, which will errback with defer.TimeoutError on timeout.
  541. """
  542. new_d: "defer.Deferred[_T]" = defer.Deferred()
  543. timed_out = [False]
  544. def time_it_out() -> None:
  545. timed_out[0] = True
  546. try:
  547. deferred.cancel()
  548. except Exception: # if we throw any exception it'll break time outs
  549. logger.exception("Canceller failed during timeout")
  550. # the cancel() call should have set off a chain of errbacks which
  551. # will have errbacked new_d, but in case it hasn't, errback it now.
  552. if not new_d.called:
  553. new_d.errback(defer.TimeoutError("Timed out after %gs" % (timeout,)))
  554. delayed_call = reactor.callLater(timeout, time_it_out)
  555. def convert_cancelled(value: Failure) -> Failure:
  556. # if the original deferred was cancelled, and our timeout has fired, then
  557. # the reason it was cancelled was due to our timeout. Turn the CancelledError
  558. # into a TimeoutError.
  559. if timed_out[0] and value.check(CancelledError):
  560. raise defer.TimeoutError("Timed out after %gs" % (timeout,))
  561. return value
  562. deferred.addErrback(convert_cancelled)
  563. def cancel_timeout(result: _T) -> _T:
  564. # stop the pending call to cancel the deferred if it's been fired
  565. if delayed_call.active():
  566. delayed_call.cancel()
  567. return result
  568. deferred.addBoth(cancel_timeout)
  569. def success_cb(val: _T) -> None:
  570. if not new_d.called:
  571. new_d.callback(val)
  572. def failure_cb(val: Failure) -> None:
  573. if not new_d.called:
  574. new_d.errback(val)
  575. deferred.addCallbacks(success_cb, failure_cb)
  576. return new_d
  577. # This class can't be generic because it uses slots with attrs.
  578. # See: https://github.com/python-attrs/attrs/issues/313
  579. @attr.s(slots=True, frozen=True, auto_attribs=True)
  580. class DoneAwaitable: # should be: Generic[R]
  581. """Simple awaitable that returns the provided value."""
  582. value: Any # should be: R
  583. def __await__(self) -> Any:
  584. return self
  585. def __iter__(self) -> "DoneAwaitable":
  586. return self
  587. def __next__(self) -> None:
  588. raise StopIteration(self.value)
  589. def maybe_awaitable(value: Union[Awaitable[R], R]) -> Awaitable[R]:
  590. """Convert a value to an awaitable if not already an awaitable."""
  591. if inspect.isawaitable(value):
  592. assert isinstance(value, Awaitable)
  593. return value
  594. return DoneAwaitable(value)
  595. def stop_cancellation(deferred: "defer.Deferred[T]") -> "defer.Deferred[T]":
  596. """Prevent a `Deferred` from being cancelled by wrapping it in another `Deferred`.
  597. Args:
  598. deferred: The `Deferred` to protect against cancellation. Must not follow the
  599. Synapse logcontext rules.
  600. Returns:
  601. A new `Deferred`, which will contain the result of the original `Deferred`.
  602. The new `Deferred` will not propagate cancellation through to the original.
  603. When cancelled, the new `Deferred` will fail with a `CancelledError`.
  604. The new `Deferred` will not follow the Synapse logcontext rules and should be
  605. wrapped with `make_deferred_yieldable`.
  606. """
  607. new_deferred: "defer.Deferred[T]" = defer.Deferred()
  608. deferred.chainDeferred(new_deferred)
  609. return new_deferred
  610. @overload
  611. def delay_cancellation(awaitable: "defer.Deferred[T]") -> "defer.Deferred[T]":
  612. ...
  613. @overload
  614. def delay_cancellation(awaitable: Coroutine[Any, Any, T]) -> "defer.Deferred[T]":
  615. ...
  616. @overload
  617. def delay_cancellation(awaitable: Awaitable[T]) -> Awaitable[T]:
  618. ...
  619. def delay_cancellation(awaitable: Awaitable[T]) -> Awaitable[T]:
  620. """Delay cancellation of a coroutine or `Deferred` awaitable until it resolves.
  621. Has the same effect as `stop_cancellation`, but the returned `Deferred` will not
  622. resolve with a `CancelledError` until the original awaitable resolves.
  623. Args:
  624. deferred: The coroutine or `Deferred` to protect against cancellation. May
  625. optionally follow the Synapse logcontext rules.
  626. Returns:
  627. A new `Deferred`, which will contain the result of the original coroutine or
  628. `Deferred`. The new `Deferred` will not propagate cancellation through to the
  629. original coroutine or `Deferred`.
  630. When cancelled, the new `Deferred` will wait until the original coroutine or
  631. `Deferred` resolves before failing with a `CancelledError`.
  632. The new `Deferred` will follow the Synapse logcontext rules if `awaitable`
  633. follows the Synapse logcontext rules. Otherwise the new `Deferred` should be
  634. wrapped with `make_deferred_yieldable`.
  635. """
  636. # First, convert the awaitable into a `Deferred`.
  637. if isinstance(awaitable, defer.Deferred):
  638. deferred = awaitable
  639. elif asyncio.iscoroutine(awaitable):
  640. # Ideally we'd use `Deferred.fromCoroutine()` here, to save on redundant
  641. # type-checking, but we'd need Twisted >= 21.2.
  642. deferred = defer.ensureDeferred(awaitable)
  643. else:
  644. # We have no idea what to do with this awaitable.
  645. # We assume it's already resolved, such as `DoneAwaitable`s or `Future`s from
  646. # `make_awaitable`, and let the caller `await` it normally.
  647. return awaitable
  648. def handle_cancel(new_deferred: "defer.Deferred[T]") -> None:
  649. # before the new deferred is cancelled, we `pause` it to stop the cancellation
  650. # propagating. we then `unpause` it once the wrapped deferred completes, to
  651. # propagate the exception.
  652. new_deferred.pause()
  653. new_deferred.errback(Failure(CancelledError()))
  654. deferred.addBoth(lambda _: new_deferred.unpause())
  655. new_deferred: "defer.Deferred[T]" = defer.Deferred(handle_cancel)
  656. deferred.chainDeferred(new_deferred)
  657. return new_deferred
  658. class AwakenableSleeper:
  659. """Allows explicitly waking up deferreds related to an entity that are
  660. currently sleeping.
  661. """
  662. def __init__(self, reactor: IReactorTime) -> None:
  663. self._streams: Dict[str, Set[defer.Deferred[None]]] = {}
  664. self._reactor = reactor
  665. def wake(self, name: str) -> None:
  666. """Wake everything related to `name` that is currently sleeping."""
  667. stream_set = self._streams.pop(name, set())
  668. for deferred in stream_set:
  669. try:
  670. with PreserveLoggingContext():
  671. deferred.callback(None)
  672. except Exception:
  673. pass
  674. async def sleep(self, name: str, delay_ms: int) -> None:
  675. """Sleep for the given number of milliseconds, or return if the given
  676. `name` is explicitly woken up.
  677. """
  678. # Create a deferred that gets called in N seconds
  679. sleep_deferred: "defer.Deferred[None]" = defer.Deferred()
  680. call = self._reactor.callLater(delay_ms / 1000, sleep_deferred.callback, None)
  681. # Create a deferred that will get called if `wake` is called with
  682. # the same `name`.
  683. stream_set = self._streams.setdefault(name, set())
  684. notify_deferred: "defer.Deferred[None]" = defer.Deferred()
  685. stream_set.add(notify_deferred)
  686. try:
  687. # Wait for either the delay or for `wake` to be called.
  688. await make_deferred_yieldable(
  689. defer.DeferredList(
  690. [sleep_deferred, notify_deferred],
  691. fireOnOneCallback=True,
  692. fireOnOneErrback=True,
  693. consumeErrors=True,
  694. )
  695. )
  696. finally:
  697. # Clean up the state
  698. curr_stream_set = self._streams.get(name)
  699. if curr_stream_set is not None:
  700. curr_stream_set.discard(notify_deferred)
  701. if len(curr_stream_set) == 0:
  702. self._streams.pop(name)
  703. # Cancel the sleep if we were woken up
  704. if call.active():
  705. call.cancel()