Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

defer.py 85KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372
  1. # -*- test-case-name: twisted.test.test_defer -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Support for results that aren't immediately available.
  6. Maintainer: Glyph Lefkowitz
  7. """
  8. import traceback
  9. import warnings
  10. from abc import ABC, abstractmethod
  11. from asyncio import AbstractEventLoop, Future, iscoroutine
  12. from enum import Enum
  13. from functools import wraps
  14. from sys import exc_info
  15. from types import CoroutineType, GeneratorType, MappingProxyType
  16. from typing import (
  17. TYPE_CHECKING,
  18. Any,
  19. Awaitable,
  20. Callable,
  21. Coroutine,
  22. Generator,
  23. Generic,
  24. Iterable,
  25. List,
  26. Mapping,
  27. NoReturn,
  28. Optional,
  29. Tuple,
  30. Type,
  31. TypeVar,
  32. Union,
  33. cast,
  34. overload,
  35. )
  36. import attr
  37. from incremental import Version
  38. from typing_extensions import Literal, ParamSpec, Protocol
  39. from twisted.internet.interfaces import IDelayedCall, IReactorTime
  40. from twisted.logger import Logger
  41. from twisted.python import lockfile
  42. from twisted.python.compat import _PYPY, cmp, comparable
  43. from twisted.python.deprecate import deprecated, warnAboutFunction
  44. from twisted.python.failure import Failure, _extraneous
  45. class _Context(Protocol):
  46. def run(self, f: Callable[..., object], *args: object, **kwargs: object) -> object:
  47. ...
  48. try:
  49. from contextvars import copy_context as __copy_context
  50. _contextvarsSupport = True
  51. except ImportError:
  52. _contextvarsSupport = False
  53. class _NoContext:
  54. @staticmethod
  55. def run(f: Callable[..., object], *args: object, **kwargs: object) -> object:
  56. return f(*args, **kwargs)
  57. def _copy_context() -> Type[_NoContext]:
  58. return _NoContext
  59. else:
  60. _copy_context = __copy_context # type: ignore[assignment]
  61. log = Logger()
  62. _T = TypeVar("_T")
  63. _P = ParamSpec("_P")
  64. class AlreadyCalledError(Exception):
  65. """
  66. This error is raised when one of L{Deferred.callback} or L{Deferred.errback}
  67. is called after one of the two had already been called.
  68. """
  69. class CancelledError(Exception):
  70. """
  71. This error is raised by default when a L{Deferred} is cancelled.
  72. """
  73. class TimeoutError(Exception):
  74. """
  75. This error is raised by default when a L{Deferred} times out.
  76. """
  77. class NotACoroutineError(TypeError):
  78. """
  79. This error is raised when a coroutine is expected and something else is
  80. encountered.
  81. """
  82. def logError(err: Failure) -> Failure:
  83. """
  84. Log and return failure.
  85. This method can be used as an errback that passes the failure on to the
  86. next errback unmodified. Note that if this is the last errback, and the
  87. deferred gets garbage collected after being this errback has been called,
  88. the clean up code logs it again.
  89. """
  90. log.failure("", err)
  91. return err
  92. def succeed(result: _T) -> "Deferred[_T]":
  93. """
  94. Return a L{Deferred} that has already had C{.callback(result)} called.
  95. This is useful when you're writing synchronous code to an
  96. asynchronous interface: i.e., some code is calling you expecting a
  97. L{Deferred} result, but you don't actually need to do anything
  98. asynchronous. Just return C{defer.succeed(theResult)}.
  99. See L{fail} for a version of this function that uses a failing
  100. L{Deferred} rather than a successful one.
  101. @param result: The result to give to the Deferred's 'callback'
  102. method.
  103. """
  104. d: Deferred[_T] = Deferred()
  105. d.callback(result)
  106. return d
  107. def fail(result: Optional[Union[Failure, BaseException]] = None) -> "Deferred[Any]":
  108. """
  109. Return a L{Deferred} that has already had C{.errback(result)} called.
  110. See L{succeed}'s docstring for rationale.
  111. @param result: The same argument that L{Deferred.errback} takes.
  112. @raise NoCurrentExceptionError: If C{result} is L{None} but there is no
  113. current exception state.
  114. """
  115. d: Deferred[Any] = Deferred()
  116. d.errback(result)
  117. return d
  118. def execute(
  119. callable: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs
  120. ) -> "Deferred[_T]":
  121. """
  122. Create a L{Deferred} from a callable and arguments.
  123. Call the given function with the given arguments. Return a L{Deferred}
  124. which has been fired with its callback as the result of that invocation
  125. or its C{errback} with a L{Failure} for the exception thrown.
  126. """
  127. try:
  128. result = callable(*args, **kwargs)
  129. except BaseException:
  130. return fail()
  131. else:
  132. return succeed(result)
  133. def maybeDeferred(
  134. f: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs
  135. ) -> "Deferred[_T]":
  136. """
  137. Invoke a function that may or may not return a L{Deferred} or coroutine.
  138. Call the given function with the given arguments. Then:
  139. - If the returned object is a L{Deferred}, return it.
  140. - If the returned object is a L{Failure}, wrap it with L{fail} and
  141. return it.
  142. - If the returned object is a L{types.CoroutineType}, wrap it with
  143. L{Deferred.fromCoroutine} and return it.
  144. - Otherwise, wrap it in L{succeed} and return it.
  145. - If an exception is raised, convert it to a L{Failure}, wrap it in
  146. L{fail}, and then return it.
  147. @param f: The callable to invoke
  148. @param args: The arguments to pass to C{f}
  149. @param kwargs: The keyword arguments to pass to C{f}
  150. @return: The result of the function call, wrapped in a L{Deferred} if
  151. necessary.
  152. """
  153. try:
  154. result = f(*args, **kwargs)
  155. except BaseException:
  156. return fail(Failure(captureVars=Deferred.debug))
  157. if isinstance(result, Deferred):
  158. return result
  159. elif isinstance(result, Failure):
  160. return fail(result)
  161. elif type(result) is CoroutineType:
  162. # A note on how we identify this case ...
  163. #
  164. # inspect.iscoroutinefunction(f) should be the simplest and easiest
  165. # way to determine if we want to apply coroutine handling. However,
  166. # the value may be returned by a regular function that calls a
  167. # coroutine function and returns its result. It would be confusing if
  168. # cases like this led to different handling of the coroutine (even
  169. # though it is a mistake to have a regular function call a coroutine
  170. # function to return its result - doing so immediately destroys a
  171. # large part of the value of coroutine functions: that they can only
  172. # have a coroutine result).
  173. #
  174. # There are many ways we could inspect ``result`` to determine if it
  175. # is a "coroutine" but most of these are mistakes. The goal is only
  176. # to determine whether the value came from ``async def`` or not
  177. # because these are the only values we're trying to handle with this
  178. # case. Such values always have exactly one type: CoroutineType.
  179. return Deferred.fromCoroutine(result)
  180. else:
  181. return succeed(result)
  182. @deprecated(
  183. Version("Twisted", 17, 1, 0),
  184. replacement="twisted.internet.defer.Deferred.addTimeout",
  185. )
  186. def timeout(deferred: "Deferred[object]") -> None:
  187. deferred.errback(Failure(TimeoutError("Callback timed out")))
  188. def passthru(arg: _T) -> _T:
  189. return arg
  190. def _failthru(arg: Failure) -> Failure:
  191. return arg
  192. def setDebugging(on: bool) -> None:
  193. """
  194. Enable or disable L{Deferred} debugging.
  195. When debugging is on, the call stacks from creation and invocation are
  196. recorded, and added to any L{AlreadyCalledError}s we raise.
  197. """
  198. Deferred.debug = bool(on)
  199. def getDebugging() -> bool:
  200. """
  201. Determine whether L{Deferred} debugging is enabled.
  202. """
  203. return Deferred.debug
  204. def _cancelledToTimedOutError(value: _T, timeout: float) -> _T:
  205. """
  206. A default translation function that translates L{Failure}s that are
  207. L{CancelledError}s to L{TimeoutError}s.
  208. @param value: Anything
  209. @param timeout: The timeout
  210. @raise TimeoutError: If C{value} is a L{Failure} that is a L{CancelledError}.
  211. @raise Exception: If C{value} is a L{Failure} that is not a L{CancelledError},
  212. it is re-raised.
  213. @since: 16.5
  214. """
  215. if isinstance(value, Failure):
  216. value.trap(CancelledError)
  217. raise TimeoutError(timeout, "Deferred")
  218. return value
  219. class _Sentinel(Enum):
  220. """
  221. @cvar _NO_RESULT:
  222. The result used to represent the fact that there is no result.
  223. B{Never ever ever use this as an actual result for a Deferred}.
  224. You have been warned.
  225. @cvar _CONTINUE:
  226. A marker left in L{Deferred.callback}s to indicate a Deferred chain.
  227. Always accompanied by a Deferred instance in the args tuple pointing at
  228. the Deferred which is chained to the Deferred which has this marker.
  229. """
  230. _NO_RESULT = object()
  231. _CONTINUE = object()
  232. # Cache these values for use without the extra lookup in deferred hot code paths
  233. _NO_RESULT = _Sentinel._NO_RESULT
  234. _CONTINUE = _Sentinel._CONTINUE
  235. # type note: this should be Callable[[object, ...], object] but mypy doesn't allow.
  236. # Callable[[object], object] is next best, but disallows valid callback signatures
  237. DeferredCallback = Callable[..., object]
  238. # type note: this should be Callable[[Failure, ...], object] but mypy doesn't allow.
  239. # Callable[[Failure], object] is next best, but disallows valid callback signatures
  240. DeferredErrback = Callable[..., object]
  241. _CallbackOrderedArguments = Tuple[object, ...]
  242. _CallbackKeywordArguments = Mapping[str, object]
  243. _CallbackChain = Tuple[
  244. Tuple[
  245. Union[DeferredCallback, Literal[_Sentinel._CONTINUE]],
  246. _CallbackOrderedArguments,
  247. _CallbackKeywordArguments,
  248. ],
  249. Tuple[
  250. Union[DeferredErrback, DeferredCallback, Literal[_Sentinel._CONTINUE]],
  251. _CallbackOrderedArguments,
  252. _CallbackKeywordArguments,
  253. ],
  254. ]
  255. _NONE_KWARGS: _CallbackKeywordArguments = MappingProxyType({})
  256. _DeferredResultT = TypeVar("_DeferredResultT", contravariant=True)
  257. _NextDeferredResultT = TypeVar("_NextDeferredResultT", covariant=True)
  258. class DebugInfo:
  259. """
  260. Deferred debug helper.
  261. """
  262. failResult: Optional[Failure] = None
  263. creator: Optional[List[str]] = None
  264. invoker: Optional[List[str]] = None
  265. def _getDebugTracebacks(self) -> str:
  266. info = ""
  267. if self.creator is not None:
  268. info += " C: Deferred was created:\n C:"
  269. info += "".join(self.creator).rstrip().replace("\n", "\n C:")
  270. info += "\n"
  271. if self.invoker is not None:
  272. info += " I: First Invoker was:\n I:"
  273. info += "".join(self.invoker).rstrip().replace("\n", "\n I:")
  274. info += "\n"
  275. return info
  276. def __del__(self) -> None:
  277. """
  278. Print tracebacks and die.
  279. If the *last* (and I do mean *last*) callback leaves me in an error
  280. state, print a traceback (if said errback is a L{Failure}).
  281. """
  282. if self.failResult is not None:
  283. # Note: this is two separate messages for compatibility with
  284. # earlier tests; arguably it should be a single error message.
  285. log.critical("Unhandled error in Deferred:", isError=True)
  286. debugInfo = self._getDebugTracebacks()
  287. if debugInfo:
  288. format = "(debug: {debugInfo})"
  289. else:
  290. format = ""
  291. log.failure(format, self.failResult, debugInfo=debugInfo)
  292. class Deferred(Awaitable[_DeferredResultT]):
  293. """
  294. This is a callback which will be put off until later.
  295. Why do we want this? Well, in cases where a function in a threaded
  296. program would block until it gets a result, for Twisted it should
  297. not block. Instead, it should return a L{Deferred}.
  298. This can be implemented for protocols that run over the network by
  299. writing an asynchronous protocol for L{twisted.internet}. For methods
  300. that come from outside packages that are not under our control, we use
  301. threads (see for example L{twisted.enterprise.adbapi}).
  302. For more information about Deferreds, see doc/core/howto/defer.html or
  303. U{http://twistedmatrix.com/documents/current/core/howto/defer.html}
  304. When creating a Deferred, you may provide a canceller function, which
  305. will be called by d.cancel() to let you do any clean-up necessary if the
  306. user decides not to wait for the deferred to complete.
  307. @ivar called: A flag which is C{False} until either C{callback} or
  308. C{errback} is called and afterwards always C{True}.
  309. @ivar paused: A counter of how many unmatched C{pause} calls have been made
  310. on this instance.
  311. @ivar _suppressAlreadyCalled: A flag used by the cancellation mechanism
  312. which is C{True} if the Deferred has no canceller and has been
  313. cancelled, C{False} otherwise. If C{True}, it can be expected that
  314. C{callback} or C{errback} will eventually be called and the result
  315. should be silently discarded.
  316. @ivar _runningCallbacks: A flag which is C{True} while this instance is
  317. executing its callback chain, used to stop recursive execution of
  318. L{_runCallbacks}
  319. @ivar _chainedTo: If this L{Deferred} is waiting for the result of another
  320. L{Deferred}, this is a reference to the other Deferred. Otherwise,
  321. L{None}.
  322. """
  323. called = False
  324. paused = 0
  325. _debugInfo: Optional[DebugInfo] = None
  326. _suppressAlreadyCalled = False
  327. # Are we currently running a user-installed callback? Meant to prevent
  328. # recursive running of callbacks when a reentrant call to add a callback is
  329. # used.
  330. _runningCallbacks = False
  331. # Keep this class attribute for now, for compatibility with code that
  332. # sets it directly.
  333. debug = False
  334. _chainedTo: "Optional[Deferred[Any]]" = None
  335. def __init__(
  336. self, canceller: Optional[Callable[["Deferred[Any]"], None]] = None
  337. ) -> None:
  338. """
  339. Initialize a L{Deferred}.
  340. @param canceller: a callable used to stop the pending operation
  341. scheduled by this L{Deferred} when L{Deferred.cancel} is invoked.
  342. The canceller will be passed the deferred whose cancellation is
  343. requested (i.e., C{self}).
  344. If a canceller is not given, or does not invoke its argument's
  345. C{callback} or C{errback} method, L{Deferred.cancel} will
  346. invoke L{Deferred.errback} with a L{CancelledError}.
  347. Note that if a canceller is not given, C{callback} or
  348. C{errback} may still be invoked exactly once, even though
  349. defer.py will have already invoked C{errback}, as described
  350. above. This allows clients of code which returns a L{Deferred}
  351. to cancel it without requiring the L{Deferred} instantiator to
  352. provide any specific implementation support for cancellation.
  353. New in 10.1.
  354. @type canceller: a 1-argument callable which takes a L{Deferred}. The
  355. return result is ignored.
  356. """
  357. self.callbacks: List[_CallbackChain] = []
  358. self._canceller = canceller
  359. if self.debug:
  360. self._debugInfo = DebugInfo()
  361. self._debugInfo.creator = traceback.format_stack()[:-1]
  362. def addCallbacks(
  363. self,
  364. callback: Callable[
  365. ...,
  366. "Union[_NextDeferredResultT, Deferred[_NextDeferredResultT]]",
  367. ],
  368. errback: Callable[
  369. ...,
  370. "Union[Failure, _NextDeferredResultT, Deferred[_NextDeferredResultT]]",
  371. ] = _failthru,
  372. callbackArgs: _CallbackOrderedArguments = (),
  373. callbackKeywords: _CallbackKeywordArguments = _NONE_KWARGS,
  374. errbackArgs: _CallbackOrderedArguments = (),
  375. errbackKeywords: _CallbackKeywordArguments = _NONE_KWARGS,
  376. ) -> "Deferred[_NextDeferredResultT]":
  377. """
  378. Add a pair of callbacks (success and error) to this L{Deferred}.
  379. These will be executed when the 'master' callback is run.
  380. @return: C{self}.
  381. """
  382. # Default value used to be None and callers may be using None
  383. if errback is None:
  384. errback = _failthru # type: ignore[unreachable]
  385. if callbackArgs is None:
  386. callbackArgs = () # type: ignore[unreachable]
  387. if callbackKeywords is None:
  388. callbackKeywords = {} # type: ignore[unreachable]
  389. if errbackArgs is None:
  390. errbackArgs = () # type: ignore[unreachable]
  391. if errbackKeywords is None:
  392. errbackKeywords = {} # type: ignore[unreachable]
  393. assert callable(callback)
  394. assert callable(errback)
  395. self.callbacks.append(
  396. (
  397. (callback, callbackArgs, callbackKeywords),
  398. (errback, errbackArgs, errbackKeywords),
  399. )
  400. )
  401. if self.called:
  402. self._runCallbacks()
  403. # type note: The Deferred's type has changed here, but *idiomatically*
  404. # the caller should treat the result as the new type, consistently.
  405. return cast(Deferred[_NextDeferredResultT], self)
  406. def addCallback(
  407. self,
  408. callback: Callable[
  409. ...,
  410. "Union[_NextDeferredResultT, Deferred[_NextDeferredResultT]]",
  411. ],
  412. *args: object,
  413. **kwargs: object,
  414. ) -> "Deferred[_NextDeferredResultT]":
  415. """
  416. Convenience method for adding just a callback.
  417. See L{addCallbacks}.
  418. """
  419. return self.addCallbacks(callback, callbackArgs=args, callbackKeywords=kwargs)
  420. def addErrback(
  421. self,
  422. errback: Callable[
  423. ...,
  424. "Union[Failure, _NextDeferredResultT, Deferred[_NextDeferredResultT]]",
  425. ],
  426. *args: object,
  427. **kwargs: object,
  428. ) -> "Deferred[Union[_DeferredResultT, _NextDeferredResultT]]":
  429. """
  430. Convenience method for adding just an errback.
  431. See L{addCallbacks}.
  432. """
  433. # type note: passthru constrains the type of errback in a way which mypy
  434. # can't propagate through to _NextDeferredResultT, so we have to
  435. # ignore a type error.
  436. return self.addCallbacks(
  437. passthru,
  438. errback, # type: ignore[arg-type]
  439. errbackArgs=args,
  440. errbackKeywords=kwargs,
  441. )
  442. def addBoth(
  443. self,
  444. callback: Callable[
  445. ...,
  446. "Union[_NextDeferredResultT, Deferred[_NextDeferredResultT]]",
  447. ],
  448. *args: object,
  449. **kwargs: object,
  450. ) -> "Deferred[_NextDeferredResultT]":
  451. """
  452. Convenience method for adding a single callable as both a callback
  453. and an errback.
  454. See L{addCallbacks}.
  455. """
  456. return self.addCallbacks(
  457. callback,
  458. callback,
  459. callbackArgs=args,
  460. errbackArgs=args,
  461. callbackKeywords=kwargs,
  462. errbackKeywords=kwargs,
  463. )
  464. def addTimeout(
  465. self,
  466. timeout: float,
  467. clock: IReactorTime,
  468. onTimeoutCancel: Optional[Callable[[object, float], object]] = None,
  469. ) -> "Deferred[_DeferredResultT]":
  470. """
  471. Time out this L{Deferred} by scheduling it to be cancelled after
  472. C{timeout} seconds.
  473. The timeout encompasses all the callbacks and errbacks added to this
  474. L{defer.Deferred} before the call to L{addTimeout}, and none added
  475. after the call.
  476. If this L{Deferred} gets timed out, it errbacks with a L{TimeoutError},
  477. unless a cancelable function was passed to its initialization or unless
  478. a different C{onTimeoutCancel} callable is provided.
  479. @param timeout: number of seconds to wait before timing out this
  480. L{Deferred}
  481. @param clock: The object which will be used to schedule the timeout.
  482. @param onTimeoutCancel: A callable which is called immediately after
  483. this L{Deferred} times out, and not if this L{Deferred} is
  484. otherwise cancelled before the timeout. It takes an arbitrary
  485. value, which is the value of this L{Deferred} at that exact point
  486. in time (probably a L{CancelledError} L{Failure}), and the
  487. C{timeout}. The default callable (if C{None} is provided) will
  488. translate a L{CancelledError} L{Failure} into a L{TimeoutError}.
  489. @return: C{self}.
  490. @since: 16.5
  491. """
  492. timedOut = [False]
  493. def timeItOut() -> None:
  494. timedOut[0] = True
  495. self.cancel()
  496. delayedCall = clock.callLater(timeout, timeItOut)
  497. def convertCancelled(value: object) -> object:
  498. # if C{deferred} was timed out, call the translation function,
  499. # if provided, otherwise just use L{cancelledToTimedOutError}
  500. if timedOut[0]:
  501. toCall = onTimeoutCancel or _cancelledToTimedOutError
  502. return toCall(value, timeout)
  503. return value
  504. self.addBoth(convertCancelled)
  505. def cancelTimeout(
  506. result: Union[_DeferredResultT, Failure]
  507. ) -> Union[_DeferredResultT, Failure]:
  508. # stop the pending call to cancel the deferred if it's been fired
  509. if delayedCall.active():
  510. delayedCall.cancel()
  511. return result
  512. self.addBoth(cancelTimeout)
  513. return self
  514. def chainDeferred(self, d: "Deferred[_DeferredResultT]") -> "Deferred[None]":
  515. """
  516. Chain another L{Deferred} to this L{Deferred}.
  517. This method adds callbacks to this L{Deferred} to call C{d}'s callback
  518. or errback, as appropriate. It is merely a shorthand way of performing
  519. the following::
  520. d1.addCallbacks(d2.callback, d2.errback)
  521. When you chain a deferred C{d2} to another deferred C{d1} with
  522. C{d1.chainDeferred(d2)}, you are making C{d2} participate in the
  523. callback chain of C{d1}.
  524. Thus any event that fires C{d1} will also fire C{d2}.
  525. However, the converse is B{not} true; if C{d2} is fired, C{d1} will not
  526. be affected.
  527. Note that unlike the case where chaining is caused by a L{Deferred}
  528. being returned from a callback, it is possible to cause the call
  529. stack size limit to be exceeded by chaining many L{Deferred}s
  530. together with C{chainDeferred}.
  531. @return: C{self}.
  532. """
  533. d._chainedTo = self
  534. return self.addCallbacks(d.callback, d.errback)
  535. def callback(self, result: Union[_DeferredResultT, Failure]) -> None:
  536. """
  537. Run all success callbacks that have been added to this L{Deferred}.
  538. Each callback will have its result passed as the first argument to
  539. the next; this way, the callbacks act as a 'processing chain'. If
  540. the success-callback returns a L{Failure} or raises an L{Exception},
  541. processing will continue on the *error* callback chain. If a
  542. callback (or errback) returns another L{Deferred}, this L{Deferred}
  543. will be chained to it (and further callbacks will not run until that
  544. L{Deferred} has a result).
  545. An instance of L{Deferred} may only have either L{callback} or
  546. L{errback} called on it, and only once.
  547. @param result: The object which will be passed to the first callback
  548. added to this L{Deferred} (via L{addCallback}), unless C{result} is
  549. a L{Failure}, in which case the behavior is the same as calling
  550. C{errback(result)}.
  551. @raise AlreadyCalledError: If L{callback} or L{errback} has already been
  552. called on this L{Deferred}.
  553. """
  554. assert not isinstance(result, Deferred)
  555. self._startRunCallbacks(result)
  556. def errback(self, fail: Optional[Union[Failure, BaseException]] = None) -> None:
  557. """
  558. Run all error callbacks that have been added to this L{Deferred}.
  559. Each callback will have its result passed as the first
  560. argument to the next; this way, the callbacks act as a
  561. 'processing chain'. Also, if the error-callback returns a non-Failure
  562. or doesn't raise an L{Exception}, processing will continue on the
  563. *success*-callback chain.
  564. If the argument that's passed to me is not a L{Failure} instance,
  565. it will be embedded in one. If no argument is passed, a
  566. L{Failure} instance will be created based on the current
  567. traceback stack.
  568. Passing a string as `fail' is deprecated, and will be punished with
  569. a warning message.
  570. An instance of L{Deferred} may only have either L{callback} or
  571. L{errback} called on it, and only once.
  572. @param fail: The L{Failure} object which will be passed to the first
  573. errback added to this L{Deferred} (via L{addErrback}).
  574. Alternatively, a L{Exception} instance from which a L{Failure} will
  575. be constructed (with no traceback) or L{None} to create a L{Failure}
  576. instance from the current exception state (with a traceback).
  577. @raise AlreadyCalledError: If L{callback} or L{errback} has already been
  578. called on this L{Deferred}.
  579. @raise NoCurrentExceptionError: If C{fail} is L{None} but there is
  580. no current exception state.
  581. """
  582. if fail is None:
  583. fail = Failure(captureVars=self.debug)
  584. elif not isinstance(fail, Failure):
  585. fail = Failure(fail)
  586. self._startRunCallbacks(fail)
  587. def pause(self) -> None:
  588. """
  589. Stop processing on a L{Deferred} until L{unpause}() is called.
  590. """
  591. self.paused = self.paused + 1
  592. def unpause(self) -> None:
  593. """
  594. Process all callbacks made since L{pause}() was called.
  595. """
  596. self.paused = self.paused - 1
  597. if self.paused:
  598. return
  599. if self.called:
  600. self._runCallbacks()
  601. def cancel(self) -> None:
  602. """
  603. Cancel this L{Deferred}.
  604. If the L{Deferred} has not yet had its C{errback} or C{callback} method
  605. invoked, call the canceller function provided to the constructor. If
  606. that function does not invoke C{callback} or C{errback}, or if no
  607. canceller function was provided, errback with L{CancelledError}.
  608. If this L{Deferred} is waiting on another L{Deferred}, forward the
  609. cancellation to the other L{Deferred}.
  610. """
  611. if not self.called:
  612. canceller = self._canceller
  613. if canceller:
  614. canceller(self)
  615. else:
  616. # Arrange to eat the callback that will eventually be fired
  617. # since there was no real canceller.
  618. self._suppressAlreadyCalled = True
  619. if not self.called:
  620. # There was no canceller, or the canceller didn't call
  621. # callback or errback.
  622. self.errback(Failure(CancelledError()))
  623. elif isinstance(self.result, Deferred):
  624. # Waiting for another deferred -- cancel it instead.
  625. self.result.cancel()
  626. def _startRunCallbacks(self, result: object) -> None:
  627. if self.called:
  628. if self._suppressAlreadyCalled:
  629. self._suppressAlreadyCalled = False
  630. return
  631. if self.debug:
  632. if self._debugInfo is None:
  633. self._debugInfo = DebugInfo()
  634. extra = "\n" + self._debugInfo._getDebugTracebacks()
  635. raise AlreadyCalledError(extra)
  636. raise AlreadyCalledError
  637. if self.debug:
  638. if self._debugInfo is None:
  639. self._debugInfo = DebugInfo()
  640. self._debugInfo.invoker = traceback.format_stack()[:-2]
  641. self.called = True
  642. self.result = result
  643. self._runCallbacks()
  644. def _continuation(self) -> _CallbackChain:
  645. """
  646. Build a tuple of callback and errback with L{_Sentinel._CONTINUE}.
  647. """
  648. return (
  649. (_Sentinel._CONTINUE, (self,), _NONE_KWARGS),
  650. (_Sentinel._CONTINUE, (self,), _NONE_KWARGS),
  651. )
  652. def _runCallbacks(self) -> None:
  653. """
  654. Run the chain of callbacks once a result is available.
  655. This consists of a simple loop over all of the callbacks, calling each
  656. with the current result and making the current result equal to the
  657. return value (or raised exception) of that call.
  658. If L{_runningCallbacks} is true, this loop won't run at all, since
  659. it is already running above us on the call stack. If C{self.paused} is
  660. true, the loop also won't run, because that's what it means to be
  661. paused.
  662. The loop will terminate before processing all of the callbacks if a
  663. L{Deferred} without a result is encountered.
  664. If a L{Deferred} I{with} a result is encountered, that result is taken
  665. and the loop proceeds.
  666. @note: The implementation is complicated slightly by the fact that
  667. chaining (associating two L{Deferred}s with each other such that one
  668. will wait for the result of the other, as happens when a Deferred is
  669. returned from a callback on another L{Deferred}) is supported
  670. iteratively rather than recursively, to avoid running out of stack
  671. frames when processing long chains.
  672. """
  673. if self._runningCallbacks:
  674. # Don't recursively run callbacks
  675. return
  676. # Keep track of all the Deferreds encountered while propagating results
  677. # up a chain. The way a Deferred gets onto this stack is by having
  678. # added its _continuation() to the callbacks list of a second Deferred
  679. # and then that second Deferred being fired. ie, if ever had _chainedTo
  680. # set to something other than None, you might end up on this stack.
  681. chain: List[Deferred[Any]] = [self]
  682. while chain:
  683. current = chain[-1]
  684. if current.paused:
  685. # This Deferred isn't going to produce a result at all. All the
  686. # Deferreds up the chain waiting on it will just have to...
  687. # wait.
  688. return
  689. finished = True
  690. current._chainedTo = None
  691. while current.callbacks:
  692. item = current.callbacks.pop(0)
  693. if not isinstance(current.result, Failure):
  694. callback, args, kwargs = item[0]
  695. else:
  696. # type note: Callback signature also works for Errbacks in
  697. # this context.
  698. callback, args, kwargs = item[1]
  699. # Avoid recursion if we can.
  700. if callback is _CONTINUE:
  701. # Give the waiting Deferred our current result and then
  702. # forget about that result ourselves.
  703. chainee = cast(Deferred[object], args[0])
  704. chainee.result = current.result
  705. current.result = None
  706. # Making sure to update _debugInfo
  707. if current._debugInfo is not None:
  708. current._debugInfo.failResult = None
  709. chainee.paused -= 1
  710. chain.append(chainee)
  711. # Delay cleaning this Deferred and popping it from the chain
  712. # until after we've dealt with chainee.
  713. finished = False
  714. break
  715. try:
  716. current._runningCallbacks = True
  717. try:
  718. # type note: mypy sees `callback is _CONTINUE` above and
  719. # then decides that `callback` is not callable.
  720. # This goes away when we use `_Sentinel._CONTINUE`
  721. # instead, but we don't want to do that attribute
  722. # lookup in this hot code path, so we ignore the mypy
  723. # complaint here.
  724. current.result = callback( # type: ignore[misc]
  725. current.result, *args, **kwargs
  726. )
  727. if current.result is current:
  728. warnAboutFunction(
  729. callback,
  730. "Callback returned the Deferred "
  731. "it was attached to; this breaks the "
  732. "callback chain and will raise an "
  733. "exception in the future.",
  734. )
  735. finally:
  736. current._runningCallbacks = False
  737. except BaseException:
  738. # Including full frame information in the Failure is quite
  739. # expensive, so we avoid it unless self.debug is set.
  740. current.result = Failure(captureVars=self.debug)
  741. else:
  742. if isinstance(current.result, Deferred):
  743. # The result is another Deferred. If it has a result,
  744. # we can take it and keep going.
  745. resultResult = getattr(current.result, "result", _NO_RESULT)
  746. if (
  747. resultResult is _NO_RESULT
  748. or isinstance(resultResult, Deferred)
  749. or current.result.paused
  750. ):
  751. # Nope, it didn't. Pause and chain.
  752. current.pause()
  753. current._chainedTo = current.result
  754. # Note: current.result has no result, so it's not
  755. # running its callbacks right now. Therefore we can
  756. # append to the callbacks list directly instead of
  757. # using addCallbacks.
  758. current.result.callbacks.append(current._continuation())
  759. break
  760. else:
  761. # Yep, it did. Steal it.
  762. current.result.result = None
  763. # Make sure _debugInfo's failure state is updated.
  764. if current.result._debugInfo is not None:
  765. current.result._debugInfo.failResult = None
  766. current.result = resultResult
  767. if finished:
  768. # As much of the callback chain - perhaps all of it - as can be
  769. # processed right now has been. The current Deferred is waiting on
  770. # another Deferred or for more callbacks. Before finishing with it,
  771. # make sure its _debugInfo is in the proper state.
  772. if isinstance(current.result, Failure):
  773. # Stash the Failure in the _debugInfo for unhandled error
  774. # reporting.
  775. current.result.cleanFailure()
  776. if current._debugInfo is None:
  777. current._debugInfo = DebugInfo()
  778. current._debugInfo.failResult = current.result
  779. else:
  780. # Clear out any Failure in the _debugInfo, since the result
  781. # is no longer a Failure.
  782. if current._debugInfo is not None:
  783. current._debugInfo.failResult = None
  784. # This Deferred is done, pop it from the chain and move back up
  785. # to the Deferred which supplied us with our result.
  786. chain.pop()
  787. def __str__(self) -> str:
  788. """
  789. Return a string representation of this L{Deferred}.
  790. """
  791. cname = self.__class__.__name__
  792. result = getattr(self, "result", _NO_RESULT)
  793. myID = id(self)
  794. if self._chainedTo is not None:
  795. result = f" waiting on Deferred at 0x{id(self._chainedTo):x}"
  796. elif result is _NO_RESULT:
  797. result = ""
  798. else:
  799. result = f" current result: {result!r}"
  800. return f"<{cname} at 0x{myID:x}{result}>"
  801. __repr__ = __str__
  802. def __iter__(self) -> "Deferred[_DeferredResultT]":
  803. return self
  804. @_extraneous
  805. def send(self, value: object = None) -> "Deferred[_DeferredResultT]":
  806. if self.paused:
  807. # If we're paused, we have no result to give
  808. return self
  809. result = getattr(self, "result", _NO_RESULT)
  810. if result is _NO_RESULT:
  811. return self
  812. if isinstance(result, Failure):
  813. # Clear the failure on debugInfo so it doesn't raise "unhandled
  814. # exception"
  815. assert self._debugInfo is not None
  816. self._debugInfo.failResult = None
  817. result.value.__failure__ = result
  818. raise result.value
  819. else:
  820. raise StopIteration(result)
  821. # For PEP-492 support (async/await)
  822. # type note: base class "Awaitable" defined the type as:
  823. # Callable[[], Generator[Any, None, _DeferredResultT]]
  824. # See: https://github.com/python/typeshed/issues/5125
  825. # When the typeshed patch is included in a mypy release,
  826. # this method can be replaced by `__await__ = __iter__`.
  827. def __await__(self) -> Generator[Any, None, _DeferredResultT]:
  828. return self.__iter__() # type: ignore[return-value]
  829. __next__ = send
  830. def asFuture(self, loop: AbstractEventLoop) -> "Future[_DeferredResultT]":
  831. """
  832. Adapt this L{Deferred} into a L{Future} which is bound to C{loop}.
  833. @note: converting a L{Deferred} to an L{Future} consumes both
  834. its result and its errors, so this method implicitly converts
  835. C{self} into a L{Deferred} firing with L{None}, regardless of what
  836. its result previously would have been.
  837. @since: Twisted 17.5.0
  838. @param loop: The L{asyncio} event loop to bind the L{Future} to.
  839. @return: A L{Future} which will fire when the L{Deferred} fires.
  840. """
  841. future = loop.create_future()
  842. def checkCancel(futureAgain: "Future[_DeferredResultT]") -> None:
  843. if futureAgain.cancelled():
  844. self.cancel()
  845. def maybeFail(failure: Failure) -> None:
  846. if not future.cancelled():
  847. future.set_exception(failure.value)
  848. def maybeSucceed(result: object) -> None:
  849. if not future.cancelled():
  850. future.set_result(result)
  851. self.addCallbacks(maybeSucceed, maybeFail)
  852. future.add_done_callback(checkCancel)
  853. return future
  854. @classmethod
  855. def fromFuture(cls, future: Future) -> "Deferred[Any]":
  856. """
  857. Adapt a L{Future} to a L{Deferred}.
  858. @note: This creates a L{Deferred} from a L{Future}, I{not} from
  859. a C{coroutine}; in other words, you will need to call
  860. L{asyncio.ensure_future}, L{asyncio.loop.create_task} or create an
  861. L{asyncio.Task} yourself to get from a C{coroutine} to a
  862. L{Future} if what you have is an awaitable coroutine and
  863. not a L{Future}. (The length of this list of techniques is
  864. exactly why we have left it to the caller!)
  865. @since: Twisted 17.5.0
  866. @param future: The L{Future} to adapt.
  867. @return: A L{Deferred} which will fire when the L{Future} fires.
  868. """
  869. def adapt(result: Future) -> None:
  870. try:
  871. extracted = result.result()
  872. except BaseException:
  873. extracted = Failure()
  874. actual.callback(extracted)
  875. futureCancel = object()
  876. def cancel(reself: Deferred[object]) -> None:
  877. future.cancel()
  878. reself.callback(futureCancel)
  879. self = cls(cancel)
  880. actual = self
  881. def uncancel(
  882. result: _DeferredResultT,
  883. ) -> Union[_DeferredResultT, Deferred[_DeferredResultT]]:
  884. if result is futureCancel:
  885. nonlocal actual
  886. actual = Deferred()
  887. return actual
  888. return result
  889. self.addCallback(uncancel)
  890. future.add_done_callback(adapt)
  891. return self
  892. @classmethod
  893. def fromCoroutine(
  894. cls,
  895. coro: Union[
  896. Coroutine["Deferred[_T]", Any, _T],
  897. Generator["Deferred[_T]", Any, _T],
  898. ],
  899. ) -> "Deferred[_T]":
  900. """
  901. Schedule the execution of a coroutine that awaits on L{Deferred}s,
  902. wrapping it in a L{Deferred} that will fire on success/failure of the
  903. coroutine.
  904. Coroutine functions return a coroutine object, similar to how
  905. generators work. This function turns that coroutine into a Deferred,
  906. meaning that it can be used in regular Twisted code. For example::
  907. import treq
  908. from twisted.internet.defer import Deferred
  909. from twisted.internet.task import react
  910. async def crawl(pages):
  911. results = {}
  912. for page in pages:
  913. results[page] = await treq.content(await treq.get(page))
  914. return results
  915. def main(reactor):
  916. pages = [
  917. "http://localhost:8080"
  918. ]
  919. d = Deferred.fromCoroutine(crawl(pages))
  920. d.addCallback(print)
  921. return d
  922. react(main)
  923. @since: Twisted 21.2.0
  924. @param coro: The coroutine object to schedule.
  925. @raise ValueError: If C{coro} is not a coroutine or generator.
  926. """
  927. # asyncio.iscoroutine identifies generators as coroutines, too.
  928. if iscoroutine(coro):
  929. return _cancellableInlineCallbacks(coro)
  930. raise NotACoroutineError(f"{coro!r} is not a coroutine")
  931. def ensureDeferred(
  932. coro: Union[
  933. Coroutine[Deferred[_T], Any, _T],
  934. Generator[Deferred[_T], Any, _T],
  935. Deferred[_T],
  936. ]
  937. ) -> Deferred[_T]:
  938. """
  939. Schedule the execution of a coroutine that awaits/yields from L{Deferred}s,
  940. wrapping it in a L{Deferred} that will fire on success/failure of the
  941. coroutine. If a Deferred is passed to this function, it will be returned
  942. directly (mimicking the L{asyncio.ensure_future} function).
  943. See L{Deferred.fromCoroutine} for examples of coroutines.
  944. @param coro: The coroutine object to schedule, or a L{Deferred}.
  945. """
  946. if isinstance(coro, Deferred):
  947. return coro
  948. else:
  949. try:
  950. return Deferred.fromCoroutine(coro)
  951. except NotACoroutineError:
  952. # It's not a coroutine. Raise an exception, but say that it's also
  953. # not a Deferred so the error makes sense.
  954. raise NotACoroutineError(f"{coro!r} is not a coroutine or a Deferred")
  955. @comparable
  956. class FirstError(Exception):
  957. """
  958. First error to occur in a L{DeferredList} if C{fireOnOneErrback} is set.
  959. @ivar subFailure: The L{Failure} that occurred.
  960. @ivar index: The index of the L{Deferred} in the L{DeferredList} where
  961. it happened.
  962. """
  963. def __init__(self, failure: Failure, index: int) -> None:
  964. Exception.__init__(self, failure, index)
  965. self.subFailure = failure
  966. self.index = index
  967. def __repr__(self) -> str:
  968. """
  969. The I{repr} of L{FirstError} instances includes the repr of the
  970. wrapped failure's exception and the index of the L{FirstError}.
  971. """
  972. return "FirstError[#%d, %r]" % (self.index, self.subFailure.value)
  973. def __str__(self) -> str:
  974. """
  975. The I{str} of L{FirstError} instances includes the I{str} of the
  976. entire wrapped failure (including its traceback and exception) and
  977. the index of the L{FirstError}.
  978. """
  979. return "FirstError[#%d, %s]" % (self.index, self.subFailure)
  980. def __cmp__(self, other: object) -> int:
  981. """
  982. Comparison between L{FirstError} and other L{FirstError} instances
  983. is defined as the comparison of the index and sub-failure of each
  984. instance. L{FirstError} instances don't compare equal to anything
  985. that isn't a L{FirstError} instance.
  986. @since: 8.2
  987. """
  988. if isinstance(other, FirstError):
  989. return cmp((self.index, self.subFailure), (other.index, other.subFailure))
  990. return -1
  991. _DeferredListSingleResultT = Tuple[_DeferredResultT, int]
  992. _DeferredListResultItemT = Tuple[bool, _DeferredResultT]
  993. _DeferredListResultListT = List[_DeferredListResultItemT]
  994. if TYPE_CHECKING:
  995. # The result type is different depending on whether fireOnOneCallback
  996. # is True or False. The type system is not flexible enough to handle
  997. # that in a class definition, so instead we pretend that DeferredList
  998. # is a function that returns a Deferred.
  999. @overload
  1000. def _DeferredList(
  1001. deferredList: Iterable[Deferred[_DeferredResultT]],
  1002. fireOnOneCallback: Literal[True],
  1003. fireOnOneErrback: bool = False,
  1004. consumeErrors: bool = False,
  1005. ) -> Deferred[_DeferredListSingleResultT]:
  1006. ...
  1007. @overload
  1008. def _DeferredList(
  1009. deferredList: Iterable[Deferred[_DeferredResultT]],
  1010. fireOnOneCallback: Literal[False] = False,
  1011. fireOnOneErrback: bool = False,
  1012. consumeErrors: bool = False,
  1013. ) -> Deferred[_DeferredListResultListT]:
  1014. ...
  1015. def _DeferredList(
  1016. deferredList: Iterable[Deferred[_DeferredResultT]],
  1017. fireOnOneCallback: bool = False,
  1018. fireOnOneErrback: bool = False,
  1019. consumeErrors: bool = False,
  1020. ) -> Union[
  1021. Deferred[_DeferredListSingleResultT], Deferred[_DeferredListResultListT]
  1022. ]:
  1023. ...
  1024. DeferredList = _DeferredList
  1025. class DeferredList(Deferred[_DeferredListResultListT]): # type: ignore[no-redef]
  1026. """
  1027. L{DeferredList} is a tool for collecting the results of several Deferreds.
  1028. This tracks a list of L{Deferred}s for their results, and makes a single
  1029. callback when they have all completed. By default, the ultimate result is a
  1030. list of (success, result) tuples, 'success' being a boolean.
  1031. L{DeferredList} exposes the same API that L{Deferred} does, so callbacks and
  1032. errbacks can be added to it in the same way.
  1033. L{DeferredList} is implemented by adding callbacks and errbacks to each
  1034. L{Deferred} in the list passed to it. This means callbacks and errbacks
  1035. added to the Deferreds before they are passed to L{DeferredList} will change
  1036. the result that L{DeferredList} sees (i.e., L{DeferredList} is not special).
  1037. Callbacks and errbacks can also be added to the Deferreds after they are
  1038. passed to L{DeferredList} and L{DeferredList} may change the result that
  1039. they see.
  1040. See the documentation for the C{__init__} arguments for more information.
  1041. @ivar _deferredList: The L{list} of L{Deferred}s to track.
  1042. """
  1043. fireOnOneCallback = False
  1044. fireOnOneErrback = False
  1045. def __init__(
  1046. self,
  1047. deferredList: Iterable[Deferred[_DeferredResultT]],
  1048. fireOnOneCallback: bool = False,
  1049. fireOnOneErrback: bool = False,
  1050. consumeErrors: bool = False,
  1051. ):
  1052. """
  1053. Initialize a DeferredList.
  1054. @param deferredList: The deferreds to track.
  1055. @param fireOnOneCallback: (keyword param) a flag indicating that this
  1056. L{DeferredList} will fire when the first L{Deferred} in
  1057. C{deferredList} fires with a non-failure result without waiting for
  1058. any of the other Deferreds. When this flag is set, the DeferredList
  1059. will fire with a two-tuple: the first element is the result of the
  1060. Deferred which fired; the second element is the index in
  1061. C{deferredList} of that Deferred.
  1062. @param fireOnOneErrback: (keyword param) a flag indicating that this
  1063. L{DeferredList} will fire when the first L{Deferred} in
  1064. C{deferredList} fires with a failure result without waiting for any
  1065. of the other Deferreds. When this flag is set, if a Deferred in the
  1066. list errbacks, the DeferredList will errback with a L{FirstError}
  1067. failure wrapping the failure of that Deferred.
  1068. @param consumeErrors: (keyword param) a flag indicating that failures in
  1069. any of the included L{Deferred}s should not be propagated to
  1070. errbacks added to the individual L{Deferred}s after this
  1071. L{DeferredList} is constructed. After constructing the
  1072. L{DeferredList}, any errors in the individual L{Deferred}s will be
  1073. converted to a callback result of L{None}. This is useful to
  1074. prevent spurious 'Unhandled error in Deferred' messages from being
  1075. logged. This does not prevent C{fireOnOneErrback} from working.
  1076. """
  1077. self._deferredList = list(deferredList)
  1078. # Note this contains optional result values as the DeferredList is
  1079. # processing its results, even though the callback result will not,
  1080. # which is why we aren't using _DeferredListResultListT here.
  1081. self.resultList: List[Optional[_DeferredListResultItemT]] = [None] * len(
  1082. self._deferredList
  1083. )
  1084. """
  1085. The final result, in progress.
  1086. Each item in the list corresponds to the L{Deferred} at the same
  1087. position in L{_deferredList}. It will be L{None} if the L{Deferred}
  1088. did not complete yet, or a C{(success, result)} pair if it did.
  1089. """
  1090. Deferred.__init__(self)
  1091. if len(self._deferredList) == 0 and not fireOnOneCallback:
  1092. self.callback([])
  1093. # These flags need to be set *before* attaching callbacks to the
  1094. # deferreds, because the callbacks use these flags, and will run
  1095. # synchronously if any of the deferreds are already fired.
  1096. self.fireOnOneCallback = fireOnOneCallback
  1097. self.fireOnOneErrback = fireOnOneErrback
  1098. self.consumeErrors = consumeErrors
  1099. self.finishedCount = 0
  1100. index = 0
  1101. for deferred in self._deferredList:
  1102. deferred.addCallbacks(
  1103. self._cbDeferred,
  1104. self._cbDeferred,
  1105. callbackArgs=(index, SUCCESS),
  1106. errbackArgs=(index, FAILURE),
  1107. )
  1108. index = index + 1
  1109. def _cbDeferred(
  1110. self, result: _DeferredResultT, index: int, succeeded: bool
  1111. ) -> Optional[_DeferredResultT]:
  1112. """
  1113. (internal) Callback for when one of my deferreds fires.
  1114. """
  1115. self.resultList[index] = (succeeded, result)
  1116. self.finishedCount += 1
  1117. if not self.called:
  1118. if succeeded == SUCCESS and self.fireOnOneCallback:
  1119. self.callback((result, index)) # type: ignore[arg-type]
  1120. elif succeeded == FAILURE and self.fireOnOneErrback:
  1121. assert isinstance(result, Failure)
  1122. self.errback(Failure(FirstError(result, index)))
  1123. elif self.finishedCount == len(self.resultList):
  1124. # At this point, None values in self.resultList have been
  1125. # replaced by result values, so we cast it to
  1126. # _DeferredListResultListT to match the callback result type.
  1127. self.callback(cast(_DeferredListResultListT, self.resultList))
  1128. if succeeded == FAILURE and self.consumeErrors:
  1129. return None
  1130. return result
  1131. def cancel(self) -> None:
  1132. """
  1133. Cancel this L{DeferredList}.
  1134. If the L{DeferredList} hasn't fired yet, cancel every L{Deferred} in
  1135. the list.
  1136. If the L{DeferredList} has fired, including the case where the
  1137. C{fireOnOneCallback}/C{fireOnOneErrback} flag is set and the
  1138. L{DeferredList} fires because one L{Deferred} in the list fires with a
  1139. non-failure/failure result, do nothing in the C{cancel} method.
  1140. """
  1141. if not self.called:
  1142. for deferred in self._deferredList:
  1143. try:
  1144. deferred.cancel()
  1145. except BaseException:
  1146. log.failure("Exception raised from user supplied canceller")
  1147. def _parseDeferredListResult(
  1148. resultList: List[_DeferredListResultItemT], fireOnOneErrback: bool = False
  1149. ) -> List[_T]:
  1150. if __debug__:
  1151. for result in resultList:
  1152. assert result is not None
  1153. success, value = result
  1154. assert success
  1155. return [x[1] for x in resultList]
  1156. def gatherResults(
  1157. deferredList: Iterable[Deferred[_T]], consumeErrors: bool = False
  1158. ) -> Deferred[List[_T]]:
  1159. """
  1160. Returns, via a L{Deferred}, a list with the results of the given
  1161. L{Deferred}s - in effect, a "join" of multiple deferred operations.
  1162. The returned L{Deferred} will fire when I{all} of the provided L{Deferred}s
  1163. have fired, or when any one of them has failed.
  1164. This method can be cancelled by calling the C{cancel} method of the
  1165. L{Deferred}, all the L{Deferred}s in the list will be cancelled.
  1166. This differs from L{DeferredList} in that you don't need to parse
  1167. the result for success/failure.
  1168. @param consumeErrors: (keyword param) a flag, defaulting to False,
  1169. indicating that failures in any of the given L{Deferred}s should not be
  1170. propagated to errbacks added to the individual L{Deferred}s after this
  1171. L{gatherResults} invocation. Any such errors in the individual
  1172. L{Deferred}s will be converted to a callback result of L{None}. This
  1173. is useful to prevent spurious 'Unhandled error in Deferred' messages
  1174. from being logged. This parameter is available since 11.1.0.
  1175. """
  1176. d = DeferredList(deferredList, fireOnOneErrback=True, consumeErrors=consumeErrors)
  1177. d.addCallback(_parseDeferredListResult)
  1178. return cast(Deferred[List[_T]], d)
  1179. # Constants for use with DeferredList
  1180. SUCCESS = True
  1181. FAILURE = False
  1182. ## deferredGenerator
  1183. class waitForDeferred:
  1184. """
  1185. See L{deferredGenerator}.
  1186. """
  1187. result: Any = _NO_RESULT
  1188. def __init__(self, d: Deferred[object]) -> None:
  1189. warnings.warn(
  1190. "twisted.internet.defer.waitForDeferred was deprecated in "
  1191. "Twisted 15.0.0; please use twisted.internet.defer.inlineCallbacks "
  1192. "instead",
  1193. DeprecationWarning,
  1194. stacklevel=2,
  1195. )
  1196. if not isinstance(d, Deferred):
  1197. raise TypeError(
  1198. f"You must give waitForDeferred a Deferred. You gave it {d!r}."
  1199. )
  1200. self.d = d
  1201. def getResult(self) -> Any:
  1202. if isinstance(self.result, Failure):
  1203. self.result.raiseException()
  1204. self.result is not _NO_RESULT
  1205. return self.result
  1206. _DeferableGenerator = Generator[object, None, None]
  1207. def _deferGenerator(
  1208. g: _DeferableGenerator, deferred: Deferred[object]
  1209. ) -> Deferred[Any]:
  1210. """
  1211. See L{deferredGenerator}.
  1212. """
  1213. result = None
  1214. # This function is complicated by the need to prevent unbounded recursion
  1215. # arising from repeatedly yielding immediately ready deferreds. This while
  1216. # loop and the waiting variable solve that by manually unfolding the
  1217. # recursion.
  1218. # defgen is waiting for result? # result
  1219. # type note: List[Any] because you can't annotate List items by index.
  1220. # …better fix would be to create a class, but we need to jettison
  1221. # deferredGenerator anyway.
  1222. waiting: List[Any] = [True, None]
  1223. while 1:
  1224. try:
  1225. result = next(g)
  1226. except StopIteration:
  1227. deferred.callback(result)
  1228. return deferred
  1229. except BaseException:
  1230. deferred.errback()
  1231. return deferred
  1232. # Deferred.callback(Deferred) raises an error; we catch this case
  1233. # early here and give a nicer error message to the user in case
  1234. # they yield a Deferred.
  1235. if isinstance(result, Deferred):
  1236. return fail(TypeError("Yield waitForDeferred(d), not d!"))
  1237. if isinstance(result, waitForDeferred):
  1238. # a waitForDeferred was yielded, get the result.
  1239. # Pass result in so it don't get changed going around the loop
  1240. # This isn't a problem for waiting, as it's only reused if
  1241. # gotResult has already been executed.
  1242. def gotResult(
  1243. r: object, result: waitForDeferred = cast(waitForDeferred, result)
  1244. ) -> None:
  1245. result.result = r
  1246. if waiting[0]:
  1247. waiting[0] = False
  1248. waiting[1] = r
  1249. else:
  1250. _deferGenerator(g, deferred)
  1251. result.d.addBoth(gotResult)
  1252. if waiting[0]:
  1253. # Haven't called back yet, set flag so that we get reinvoked
  1254. # and return from the loop
  1255. waiting[0] = False
  1256. return deferred
  1257. # Reset waiting to initial values for next loop
  1258. waiting[0] = True
  1259. waiting[1] = None
  1260. result = None
  1261. @deprecated(Version("Twisted", 15, 0, 0), "twisted.internet.defer.inlineCallbacks")
  1262. def deferredGenerator(
  1263. f: Callable[..., _DeferableGenerator]
  1264. ) -> Callable[..., Deferred[object]]:
  1265. """
  1266. L{deferredGenerator} and L{waitForDeferred} help you write
  1267. L{Deferred}-using code that looks like a regular sequential function.
  1268. Consider the use of L{inlineCallbacks} instead, which can accomplish
  1269. the same thing in a more concise manner.
  1270. There are two important functions involved: L{waitForDeferred}, and
  1271. L{deferredGenerator}. They are used together, like this::
  1272. @deferredGenerator
  1273. def thingummy():
  1274. thing = waitForDeferred(makeSomeRequestResultingInDeferred())
  1275. yield thing
  1276. thing = thing.getResult()
  1277. print(thing) #the result! hoorj!
  1278. L{waitForDeferred} returns something that you should immediately yield; when
  1279. your generator is resumed, calling C{thing.getResult()} will either give you
  1280. the result of the L{Deferred} if it was a success, or raise an exception if it
  1281. was a failure. Calling C{getResult} is B{absolutely mandatory}. If you do
  1282. not call it, I{your program will not work}.
  1283. L{deferredGenerator} takes one of these waitForDeferred-using generator
  1284. functions and converts it into a function that returns a L{Deferred}. The
  1285. result of the L{Deferred} will be the last value that your generator yielded
  1286. unless the last value is a L{waitForDeferred} instance, in which case the
  1287. result will be L{None}. If the function raises an unhandled exception, the
  1288. L{Deferred} will errback instead. Remember that C{return result} won't work;
  1289. use C{yield result; return} in place of that.
  1290. Note that not yielding anything from your generator will make the L{Deferred}
  1291. result in L{None}. Yielding a L{Deferred} from your generator is also an error
  1292. condition; always yield C{waitForDeferred(d)} instead.
  1293. The L{Deferred} returned from your deferred generator may also errback if your
  1294. generator raised an exception. For example::
  1295. @deferredGenerator
  1296. def thingummy():
  1297. thing = waitForDeferred(makeSomeRequestResultingInDeferred())
  1298. yield thing
  1299. thing = thing.getResult()
  1300. if thing == 'I love Twisted':
  1301. # will become the result of the Deferred
  1302. yield 'TWISTED IS GREAT!'
  1303. return
  1304. else:
  1305. # will trigger an errback
  1306. raise Exception('DESTROY ALL LIFE')
  1307. Put succinctly, these functions connect deferred-using code with this 'fake
  1308. blocking' style in both directions: L{waitForDeferred} converts from a
  1309. L{Deferred} to the 'blocking' style, and L{deferredGenerator} converts from the
  1310. 'blocking' style to a L{Deferred}.
  1311. """
  1312. @wraps(f)
  1313. def unwindGenerator(*args: object, **kwargs: object) -> Deferred[object]:
  1314. return _deferGenerator(f(*args, **kwargs), Deferred())
  1315. return unwindGenerator
  1316. ## inlineCallbacks
  1317. class _DefGen_Return(BaseException):
  1318. def __init__(self, value: object) -> None:
  1319. self.value = value
  1320. def returnValue(val: object) -> NoReturn:
  1321. """
  1322. Return val from a L{inlineCallbacks} generator.
  1323. Note: this is currently implemented by raising an exception
  1324. derived from L{BaseException}. You might want to change any
  1325. 'except:' clauses to an 'except Exception:' clause so as not to
  1326. catch this exception.
  1327. Also: while this function currently will work when called from
  1328. within arbitrary functions called from within the generator, do
  1329. not rely upon this behavior.
  1330. """
  1331. raise _DefGen_Return(val)
  1332. @attr.s(auto_attribs=True)
  1333. class _CancellationStatus:
  1334. """
  1335. Cancellation status of an L{inlineCallbacks} invocation.
  1336. @ivar deferred: the L{Deferred} to callback or errback when the generator
  1337. invocation has finished.
  1338. @ivar waitingOn: the L{Deferred} being waited upon (which
  1339. L{_inlineCallbacks} must fill out before returning)
  1340. """
  1341. deferred: Deferred[object]
  1342. waitingOn: Optional[Deferred[object]] = None
  1343. @_extraneous
  1344. def _inlineCallbacks(
  1345. result: object,
  1346. gen: Union[
  1347. Generator[Deferred[_T], object, None],
  1348. Coroutine[Deferred[_T], object, None],
  1349. ],
  1350. status: _CancellationStatus,
  1351. context: _Context,
  1352. ) -> None:
  1353. """
  1354. Carry out the work of L{inlineCallbacks}.
  1355. Iterate the generator produced by an C{@}L{inlineCallbacks}-decorated
  1356. function, C{gen}, C{send()}ing it the results of each value C{yield}ed by
  1357. that generator, until a L{Deferred} is yielded, at which point a callback
  1358. is added to that L{Deferred} to call this function again.
  1359. @param result: The last result seen by this generator. Note that this is
  1360. never a L{Deferred} - by the time this function is invoked, the
  1361. L{Deferred} has been called back and this will be a particular result
  1362. at a point in its callback chain.
  1363. @param gen: a generator object returned by calling a function or method
  1364. decorated with C{@}L{inlineCallbacks}
  1365. @param status: a L{_CancellationStatus} tracking the current status of C{gen}
  1366. @param context: the contextvars context to run `gen` in
  1367. """
  1368. # This function is complicated by the need to prevent unbounded recursion
  1369. # arising from repeatedly yielding immediately ready deferreds. This while
  1370. # loop and the waiting variable solve that by manually unfolding the
  1371. # recursion.
  1372. # waiting for result? # result
  1373. waiting: List[Any] = [True, None]
  1374. stopIteration: bool = False
  1375. callbackValue: Any = None
  1376. while 1:
  1377. try:
  1378. # Send the last result back as the result of the yield expression.
  1379. isFailure = isinstance(result, Failure)
  1380. if isFailure:
  1381. result = context.run(
  1382. cast(Failure, result).throwExceptionIntoGenerator, gen
  1383. )
  1384. else:
  1385. result = context.run(gen.send, result)
  1386. except StopIteration as e:
  1387. # fell off the end, or "return" statement
  1388. stopIteration = True
  1389. callbackValue = getattr(e, "value", None)
  1390. except _DefGen_Return as e:
  1391. # returnValue() was called; time to give a result to the original
  1392. # Deferred. First though, let's try to identify the potentially
  1393. # confusing situation which results when returnValue() is
  1394. # accidentally invoked from a different function, one that wasn't
  1395. # decorated with @inlineCallbacks.
  1396. # The traceback starts in this frame (the one for
  1397. # _inlineCallbacks); the next one down should be the application
  1398. # code.
  1399. excInfo = exc_info()
  1400. assert excInfo is not None
  1401. traceback = excInfo[2]
  1402. assert traceback is not None
  1403. appCodeTrace = traceback.tb_next
  1404. assert appCodeTrace is not None
  1405. if _PYPY:
  1406. # PyPy as of 3.7 adds an extra frame.
  1407. appCodeTrace = appCodeTrace.tb_next
  1408. assert appCodeTrace is not None
  1409. if isFailure:
  1410. # If we invoked this generator frame by throwing an exception
  1411. # into it, then throwExceptionIntoGenerator will consume an
  1412. # additional stack frame itself, so we need to skip that too.
  1413. appCodeTrace = appCodeTrace.tb_next
  1414. assert appCodeTrace is not None
  1415. # Now that we've identified the frame being exited by the
  1416. # exception, let's figure out if returnValue was called from it
  1417. # directly. returnValue itself consumes a stack frame, so the
  1418. # application code will have a tb_next, but it will *not* have a
  1419. # second tb_next.
  1420. assert appCodeTrace.tb_next is not None
  1421. if appCodeTrace.tb_next.tb_next:
  1422. # If returnValue was invoked non-local to the frame which it is
  1423. # exiting, identify the frame that ultimately invoked
  1424. # returnValue so that we can warn the user, as this behavior is
  1425. # confusing.
  1426. ultimateTrace = appCodeTrace
  1427. assert ultimateTrace is not None
  1428. assert ultimateTrace.tb_next is not None
  1429. while ultimateTrace.tb_next.tb_next:
  1430. ultimateTrace = ultimateTrace.tb_next
  1431. assert ultimateTrace is not None
  1432. filename = ultimateTrace.tb_frame.f_code.co_filename
  1433. lineno = ultimateTrace.tb_lineno
  1434. assert ultimateTrace.tb_frame is not None
  1435. assert appCodeTrace.tb_frame is not None
  1436. warnings.warn_explicit(
  1437. "returnValue() in %r causing %r to exit: "
  1438. "returnValue should only be invoked by functions decorated "
  1439. "with inlineCallbacks"
  1440. % (
  1441. ultimateTrace.tb_frame.f_code.co_name,
  1442. appCodeTrace.tb_frame.f_code.co_name,
  1443. ),
  1444. DeprecationWarning,
  1445. filename,
  1446. lineno,
  1447. )
  1448. stopIteration = True
  1449. callbackValue = e.value
  1450. except BaseException:
  1451. status.deferred.errback()
  1452. return
  1453. if stopIteration:
  1454. # Call the callback outside of the exception handler to avoid inappropriate/confusing
  1455. # "During handling of the above exception, another exception occurred:" if the callback
  1456. # itself throws an exception.
  1457. status.deferred.callback(callbackValue)
  1458. return
  1459. if isinstance(result, Deferred):
  1460. # a deferred was yielded, get the result.
  1461. def gotResult(r: object) -> None:
  1462. if waiting[0]:
  1463. waiting[0] = False
  1464. waiting[1] = r
  1465. else:
  1466. _inlineCallbacks(r, gen, status, context)
  1467. result.addBoth(gotResult)
  1468. if waiting[0]:
  1469. # Haven't called back yet, set flag so that we get reinvoked
  1470. # and return from the loop
  1471. waiting[0] = False
  1472. status.waitingOn = result
  1473. return
  1474. result = waiting[1]
  1475. # Reset waiting to initial values for next loop. gotResult uses
  1476. # waiting, but this isn't a problem because gotResult is only
  1477. # executed once, and if it hasn't been executed yet, the return
  1478. # branch above would have been taken.
  1479. waiting[0] = True
  1480. waiting[1] = None
  1481. def _cancellableInlineCallbacks(
  1482. gen: Union[
  1483. Generator["Deferred[_T]", object, _T],
  1484. Coroutine["Deferred[_T]", object, _T],
  1485. ]
  1486. ) -> Deferred[_T]:
  1487. """
  1488. Make an C{@}L{inlineCallbacks} cancellable.
  1489. @param gen: a generator object returned by calling a function or method
  1490. decorated with C{@}L{inlineCallbacks}
  1491. @return: L{Deferred} for the C{@}L{inlineCallbacks} that is cancellable.
  1492. """
  1493. def cancel(it: Deferred[object]) -> None:
  1494. it.callbacks, tmp = [], it.callbacks
  1495. it.addErrback(handleCancel)
  1496. it.callbacks.extend(tmp)
  1497. it.errback(_InternalInlineCallbacksCancelledError())
  1498. deferred: Deferred[object] = Deferred(cancel)
  1499. status = _CancellationStatus(deferred)
  1500. def handleCancel(result: Failure) -> Deferred[object]:
  1501. """
  1502. Propagate the cancellation of an C{@}L{inlineCallbacks} to the
  1503. L{Deferred} it is waiting on.
  1504. @param result: An L{_InternalInlineCallbacksCancelledError} from
  1505. C{cancel()}.
  1506. @return: A new L{Deferred} that the C{@}L{inlineCallbacks} generator
  1507. can callback or errback through.
  1508. """
  1509. result.trap(_InternalInlineCallbacksCancelledError)
  1510. status.deferred = Deferred(cancel)
  1511. # We would only end up here if the inlineCallback is waiting on
  1512. # another Deferred. It needs to be cancelled.
  1513. awaited = status.waitingOn
  1514. assert awaited is not None
  1515. awaited.cancel()
  1516. return status.deferred
  1517. _inlineCallbacks(None, gen, status, _copy_context())
  1518. return deferred
  1519. class _InternalInlineCallbacksCancelledError(Exception):
  1520. """
  1521. A unique exception used only in L{_cancellableInlineCallbacks} to verify
  1522. that an L{inlineCallbacks} is being cancelled as expected.
  1523. """
  1524. # type note: "..." is used here because we don't have a better way to express
  1525. # that the same arguments are accepted by the returned callable.
  1526. def inlineCallbacks(
  1527. f: Callable[..., Generator[Deferred[object], object, _T]]
  1528. ) -> Callable[..., Deferred[_T]]:
  1529. """
  1530. L{inlineCallbacks} helps you write L{Deferred}-using code that looks like a
  1531. regular sequential function. For example::
  1532. @inlineCallbacks
  1533. def thingummy():
  1534. thing = yield makeSomeRequestResultingInDeferred()
  1535. print(thing) # the result! hoorj!
  1536. When you call anything that results in a L{Deferred}, you can simply yield it;
  1537. your generator will automatically be resumed when the Deferred's result is
  1538. available. The generator will be sent the result of the L{Deferred} with the
  1539. 'send' method on generators, or if the result was a failure, 'throw'.
  1540. Things that are not L{Deferred}s may also be yielded, and your generator
  1541. will be resumed with the same object sent back. This means C{yield}
  1542. performs an operation roughly equivalent to L{maybeDeferred}.
  1543. Your inlineCallbacks-enabled generator will return a L{Deferred} object, which
  1544. will result in the return value of the generator (or will fail with a
  1545. failure object if your generator raises an unhandled exception). Note that
  1546. you can't use C{return result} to return a value; use C{returnValue(result)}
  1547. instead. Falling off the end of the generator, or simply using C{return}
  1548. will cause the L{Deferred} to have a result of L{None}.
  1549. Be aware that L{returnValue} will not accept a L{Deferred} as a parameter.
  1550. If you believe the thing you'd like to return could be a L{Deferred}, do
  1551. this::
  1552. result = yield result
  1553. returnValue(result)
  1554. The L{Deferred} returned from your deferred generator may errback if your
  1555. generator raised an exception::
  1556. @inlineCallbacks
  1557. def thingummy():
  1558. thing = yield makeSomeRequestResultingInDeferred()
  1559. if thing == 'I love Twisted':
  1560. # will become the result of the Deferred
  1561. returnValue('TWISTED IS GREAT!')
  1562. else:
  1563. # will trigger an errback
  1564. raise Exception('DESTROY ALL LIFE')
  1565. It is possible to use the C{return} statement instead of L{returnValue}::
  1566. @inlineCallbacks
  1567. def loadData(url):
  1568. response = yield makeRequest(url)
  1569. return json.loads(response)
  1570. You can cancel the L{Deferred} returned from your L{inlineCallbacks}
  1571. generator before it is fired by your generator completing (either by
  1572. reaching its end, a C{return} statement, or by calling L{returnValue}).
  1573. A C{CancelledError} will be raised from the C{yield}ed L{Deferred} that
  1574. has been cancelled if that C{Deferred} does not otherwise suppress it.
  1575. """
  1576. @wraps(f)
  1577. def unwindGenerator(*args: object, **kwargs: object) -> Deferred[object]:
  1578. try:
  1579. gen = f(*args, **kwargs)
  1580. except _DefGen_Return:
  1581. raise TypeError(
  1582. "inlineCallbacks requires %r to produce a generator; instead"
  1583. "caught returnValue being used in a non-generator" % (f,)
  1584. )
  1585. if not isinstance(gen, GeneratorType):
  1586. raise TypeError(
  1587. "inlineCallbacks requires %r to produce a generator; "
  1588. "instead got %r" % (f, gen)
  1589. )
  1590. return _cancellableInlineCallbacks(gen)
  1591. return unwindGenerator
  1592. ## DeferredLock/DeferredQueue
  1593. _ConcurrencyPrimitiveT = TypeVar(
  1594. "_ConcurrencyPrimitiveT", bound="_ConcurrencyPrimitive"
  1595. )
  1596. class _ConcurrencyPrimitive(ABC, Generic[_DeferredResultT]):
  1597. def __init__(self: _ConcurrencyPrimitiveT) -> None:
  1598. self.waiting: List[Deferred[_ConcurrencyPrimitiveT]] = []
  1599. def _releaseAndReturn(self, r: _T) -> _T:
  1600. self.release()
  1601. return r
  1602. # You might wonder: "WTF is self_319AA2A8B18F4B8EA296D75F279EB07F?"
  1603. # It's self_ + a GUID, which is to say: "it's not a string that will ever
  1604. # be used as a name in kwargs".
  1605. # Positional-only arguments, starting in Python 3.8, would be a better
  1606. # alternative.
  1607. def run(
  1608. self_319AA2A8B18F4B8EA296D75F279EB07F: _ConcurrencyPrimitiveT,
  1609. f: Callable[..., _DeferredResultT],
  1610. *args: object,
  1611. **kwargs: object,
  1612. ) -> Deferred[_DeferredResultT]:
  1613. """
  1614. Acquire, run, release.
  1615. This method takes a callable as its first argument and any
  1616. number of other positional and keyword arguments. When the
  1617. lock or semaphore is acquired, the callable will be invoked
  1618. with those arguments.
  1619. The callable may return a L{Deferred}; if it does, the lock or
  1620. semaphore won't be released until that L{Deferred} fires.
  1621. @return: L{Deferred} of function result.
  1622. """
  1623. def execute(ignoredResult: object) -> Deferred[_DeferredResultT]:
  1624. return maybeDeferred(f, *args, **kwargs).addBoth(
  1625. self_319AA2A8B18F4B8EA296D75F279EB07F._releaseAndReturn
  1626. )
  1627. return self_319AA2A8B18F4B8EA296D75F279EB07F.acquire().addCallback(execute)
  1628. def __aenter__(self: _ConcurrencyPrimitiveT) -> Deferred[_ConcurrencyPrimitiveT]:
  1629. """
  1630. We can be used as an asynchronous context manager.
  1631. """
  1632. return self.acquire()
  1633. def __aexit__(self, exc_type: bool, exc_val: bool, exc_tb: bool) -> Deferred[bool]:
  1634. self.release()
  1635. # We return False to indicate that we have not consumed the
  1636. # exception, if any.
  1637. return succeed(False)
  1638. @abstractmethod
  1639. def acquire(self: _ConcurrencyPrimitiveT) -> Deferred[_ConcurrencyPrimitiveT]:
  1640. pass
  1641. @abstractmethod
  1642. def release(self) -> None:
  1643. pass
  1644. _DeferredLockT = TypeVar("_DeferredLockT", bound="DeferredLock")
  1645. class DeferredLock(_ConcurrencyPrimitive):
  1646. """
  1647. A lock for event driven systems.
  1648. @ivar locked: C{True} when this Lock has been acquired, false at all other
  1649. times. Do not change this value, but it is useful to examine for the
  1650. equivalent of a "non-blocking" acquisition.
  1651. """
  1652. locked = False
  1653. def _cancelAcquire(self: _DeferredLockT, d: Deferred[_DeferredLockT]) -> None:
  1654. """
  1655. Remove a deferred d from our waiting list, as the deferred has been
  1656. canceled.
  1657. Note: We do not need to wrap this in a try/except to catch d not
  1658. being in self.waiting because this canceller will not be called if
  1659. d has fired. release() pops a deferred out of self.waiting and
  1660. calls it, so the canceller will no longer be called.
  1661. @param d: The deferred that has been canceled.
  1662. """
  1663. self.waiting.remove(d)
  1664. def acquire(self: _DeferredLockT) -> Deferred[_DeferredLockT]:
  1665. """
  1666. Attempt to acquire the lock. Returns a L{Deferred} that fires on
  1667. lock acquisition with the L{DeferredLock} as the value. If the lock
  1668. is locked, then the Deferred is placed at the end of a waiting list.
  1669. @return: a L{Deferred} which fires on lock acquisition.
  1670. @rtype: a L{Deferred}
  1671. """
  1672. d: Deferred[_DeferredLockT] = Deferred(canceller=self._cancelAcquire)
  1673. if self.locked:
  1674. self.waiting.append(d)
  1675. else:
  1676. self.locked = True
  1677. d.callback(self)
  1678. return d
  1679. def release(self: _DeferredLockT) -> None:
  1680. """
  1681. Release the lock. If there is a waiting list, then the first
  1682. L{Deferred} in that waiting list will be called back.
  1683. Should be called by whomever did the L{acquire}() when the shared
  1684. resource is free.
  1685. """
  1686. assert self.locked, "Tried to release an unlocked lock"
  1687. self.locked = False
  1688. if self.waiting:
  1689. # someone is waiting to acquire lock
  1690. self.locked = True
  1691. d = self.waiting.pop(0)
  1692. d.callback(self)
  1693. _DeferredSemaphoreT = TypeVar("_DeferredSemaphoreT", bound="DeferredSemaphore")
  1694. class DeferredSemaphore(_ConcurrencyPrimitive):
  1695. """
  1696. A semaphore for event driven systems.
  1697. If you are looking into this as a means of limiting parallelism, you might
  1698. find L{twisted.internet.task.Cooperator} more useful.
  1699. @ivar limit: At most this many users may acquire this semaphore at
  1700. once.
  1701. @ivar tokens: The difference between C{limit} and the number of users
  1702. which have currently acquired this semaphore.
  1703. """
  1704. def __init__(self, tokens: int) -> None:
  1705. """
  1706. @param tokens: initial value of L{tokens} and L{limit}
  1707. @type tokens: L{int}
  1708. """
  1709. _ConcurrencyPrimitive.__init__(self)
  1710. if tokens < 1:
  1711. raise ValueError("DeferredSemaphore requires tokens >= 1")
  1712. self.tokens = tokens
  1713. self.limit = tokens
  1714. def _cancelAcquire(
  1715. self: _DeferredSemaphoreT, d: Deferred[_DeferredSemaphoreT]
  1716. ) -> None:
  1717. """
  1718. Remove a deferred d from our waiting list, as the deferred has been
  1719. canceled.
  1720. Note: We do not need to wrap this in a try/except to catch d not
  1721. being in self.waiting because this canceller will not be called if
  1722. d has fired. release() pops a deferred out of self.waiting and
  1723. calls it, so the canceller will no longer be called.
  1724. @param d: The deferred that has been canceled.
  1725. """
  1726. self.waiting.remove(d)
  1727. def acquire(self: _DeferredSemaphoreT) -> Deferred[_DeferredSemaphoreT]:
  1728. """
  1729. Attempt to acquire the token.
  1730. @return: a L{Deferred} which fires on token acquisition.
  1731. """
  1732. assert (
  1733. self.tokens >= 0
  1734. ), "Internal inconsistency?? tokens should never be negative"
  1735. d: Deferred[_DeferredSemaphoreT] = Deferred(canceller=self._cancelAcquire)
  1736. if not self.tokens:
  1737. self.waiting.append(d)
  1738. else:
  1739. self.tokens = self.tokens - 1
  1740. d.callback(self)
  1741. return d
  1742. def release(self: _DeferredSemaphoreT) -> None:
  1743. """
  1744. Release the token.
  1745. Should be called by whoever did the L{acquire}() when the shared
  1746. resource is free.
  1747. """
  1748. assert (
  1749. self.tokens < self.limit
  1750. ), "Someone released me too many times: too many tokens!"
  1751. self.tokens = self.tokens + 1
  1752. if self.waiting:
  1753. # someone is waiting to acquire token
  1754. self.tokens = self.tokens - 1
  1755. d = self.waiting.pop(0)
  1756. d.callback(self)
  1757. class QueueOverflow(Exception):
  1758. pass
  1759. class QueueUnderflow(Exception):
  1760. pass
  1761. class DeferredQueue(Generic[_T]):
  1762. """
  1763. An event driven queue.
  1764. Objects may be added as usual to this queue. When an attempt is
  1765. made to retrieve an object when the queue is empty, a L{Deferred} is
  1766. returned which will fire when an object becomes available.
  1767. @ivar size: The maximum number of objects to allow into the queue
  1768. at a time. When an attempt to add a new object would exceed this
  1769. limit, L{QueueOverflow} is raised synchronously. L{None} for no limit.
  1770. @ivar backlog: The maximum number of L{Deferred} gets to allow at
  1771. one time. When an attempt is made to get an object which would
  1772. exceed this limit, L{QueueUnderflow} is raised synchronously. L{None}
  1773. for no limit.
  1774. """
  1775. def __init__(
  1776. self, size: Optional[int] = None, backlog: Optional[int] = None
  1777. ) -> None:
  1778. self.waiting: List[Deferred[_T]] = []
  1779. self.pending: List[_T] = []
  1780. self.size = size
  1781. self.backlog = backlog
  1782. def _cancelGet(self, d: Deferred[object]) -> None:
  1783. """
  1784. Remove a deferred d from our waiting list, as the deferred has been
  1785. canceled.
  1786. Note: We do not need to wrap this in a try/except to catch d not
  1787. being in self.waiting because this canceller will not be called if
  1788. d has fired. put() pops a deferred out of self.waiting and calls
  1789. it, so the canceller will no longer be called.
  1790. @param d: The deferred that has been canceled.
  1791. """
  1792. self.waiting.remove(d)
  1793. def put(self, obj: _T) -> None:
  1794. """
  1795. Add an object to this queue.
  1796. @raise QueueOverflow: Too many objects are in this queue.
  1797. """
  1798. if self.waiting:
  1799. self.waiting.pop(0).callback(obj)
  1800. elif self.size is None or len(self.pending) < self.size:
  1801. self.pending.append(obj)
  1802. else:
  1803. raise QueueOverflow()
  1804. def get(self) -> Deferred[_T]:
  1805. """
  1806. Attempt to retrieve and remove an object from the queue.
  1807. @return: a L{Deferred} which fires with the next object available in
  1808. the queue.
  1809. @raise QueueUnderflow: Too many (more than C{backlog})
  1810. L{Deferred}s are already waiting for an object from this queue.
  1811. """
  1812. if self.pending:
  1813. return succeed(self.pending.pop(0))
  1814. elif self.backlog is None or len(self.waiting) < self.backlog:
  1815. d: Deferred[_T] = Deferred(canceller=self._cancelGet)
  1816. self.waiting.append(d)
  1817. return d
  1818. else:
  1819. raise QueueUnderflow()
  1820. class AlreadyTryingToLockError(Exception):
  1821. """
  1822. Raised when L{DeferredFilesystemLock.deferUntilLocked} is called twice on a
  1823. single L{DeferredFilesystemLock}.
  1824. """
  1825. class DeferredFilesystemLock(lockfile.FilesystemLock):
  1826. """
  1827. A L{FilesystemLock} that allows for a L{Deferred} to be fired when the lock is
  1828. acquired.
  1829. @ivar _scheduler: The object in charge of scheduling retries. In this
  1830. implementation this is parameterized for testing.
  1831. @ivar _interval: The retry interval for an L{IReactorTime} based scheduler.
  1832. @ivar _tryLockCall: An L{IDelayedCall} based on C{_interval} that will manage
  1833. the next retry for acquiring the lock.
  1834. @ivar _timeoutCall: An L{IDelayedCall} based on C{deferUntilLocked}'s timeout
  1835. argument. This is in charge of timing out our attempt to acquire the
  1836. lock.
  1837. """
  1838. _interval = 1
  1839. _tryLockCall: Optional[IDelayedCall] = None
  1840. _timeoutCall: Optional[IDelayedCall] = None
  1841. def __init__(self, name: str, scheduler: Optional[IReactorTime] = None) -> None:
  1842. """
  1843. @param name: The name of the lock to acquire
  1844. @param scheduler: An object which provides L{IReactorTime}
  1845. """
  1846. lockfile.FilesystemLock.__init__(self, name)
  1847. if scheduler is None:
  1848. from twisted.internet import reactor
  1849. scheduler = cast(IReactorTime, reactor)
  1850. self._scheduler = scheduler
  1851. def deferUntilLocked(self, timeout: Optional[float] = None) -> Deferred[None]:
  1852. """
  1853. Wait until we acquire this lock. This method is not safe for
  1854. concurrent use.
  1855. @param timeout: the number of seconds after which to time out if the
  1856. lock has not been acquired.
  1857. @return: a L{Deferred} which will callback when the lock is acquired, or
  1858. errback with a L{TimeoutError} after timing out or an
  1859. L{AlreadyTryingToLockError} if the L{deferUntilLocked} has already
  1860. been called and not successfully locked the file.
  1861. """
  1862. if self._tryLockCall is not None:
  1863. return fail(
  1864. AlreadyTryingToLockError(
  1865. "deferUntilLocked isn't safe for concurrent use."
  1866. )
  1867. )
  1868. def _cancelLock(reason: Union[Failure, Exception]) -> None:
  1869. """
  1870. Cancel a L{DeferredFilesystemLock.deferUntilLocked} call.
  1871. @type reason: L{Failure}
  1872. @param reason: The reason why the call is cancelled.
  1873. """
  1874. assert self._tryLockCall is not None
  1875. self._tryLockCall.cancel()
  1876. self._tryLockCall = None
  1877. if self._timeoutCall is not None and self._timeoutCall.active():
  1878. self._timeoutCall.cancel()
  1879. self._timeoutCall = None
  1880. if self.lock():
  1881. d.callback(None)
  1882. else:
  1883. d.errback(reason)
  1884. d: Deferred[None] = Deferred(lambda deferred: _cancelLock(CancelledError()))
  1885. def _tryLock() -> None:
  1886. if self.lock():
  1887. if self._timeoutCall is not None:
  1888. self._timeoutCall.cancel()
  1889. self._timeoutCall = None
  1890. self._tryLockCall = None
  1891. d.callback(None)
  1892. else:
  1893. if timeout is not None and self._timeoutCall is None:
  1894. reason = Failure(
  1895. TimeoutError(
  1896. "Timed out acquiring lock: %s after %fs"
  1897. % (self.name, timeout)
  1898. )
  1899. )
  1900. self._timeoutCall = self._scheduler.callLater(
  1901. timeout, _cancelLock, reason
  1902. )
  1903. self._tryLockCall = self._scheduler.callLater(self._interval, _tryLock)
  1904. _tryLock()
  1905. return d
  1906. __all__ = [
  1907. "Deferred",
  1908. "DeferredList",
  1909. "succeed",
  1910. "fail",
  1911. "FAILURE",
  1912. "SUCCESS",
  1913. "AlreadyCalledError",
  1914. "TimeoutError",
  1915. "gatherResults",
  1916. "maybeDeferred",
  1917. "ensureDeferred",
  1918. "waitForDeferred",
  1919. "deferredGenerator",
  1920. "inlineCallbacks",
  1921. "returnValue",
  1922. "DeferredLock",
  1923. "DeferredSemaphore",
  1924. "DeferredQueue",
  1925. "DeferredFilesystemLock",
  1926. "AlreadyTryingToLockError",
  1927. "CancelledError",
  1928. ]