You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

887 lines
30 KiB

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