defer.py 97 KB

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