async_helpers.py 29 KB

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