defer.py 98 KB

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