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.
 
 
 
 
 
 

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