defer.py 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701
  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. assert callable(callback)
  419. assert callable(errback)
  420. self.callbacks.append(
  421. (
  422. (callback, callbackArgs, callbackKeywords),
  423. (errback, errbackArgs, errbackKeywords),
  424. )
  425. )
  426. if self.called:
  427. self._runCallbacks()
  428. # type note: The Deferred's type has changed here, but *idiomatically*
  429. # the caller should treat the result as the new type, consistently.
  430. return self # type:ignore[return-value]
  431. # BEGIN way too many @overload-s for addCallback, addErrback, and addBoth:
  432. # these must be accomplished with @overloads, rather than a big Union on
  433. # the result type as you might expect, because the fact that
  434. # _NextResultT has no bound makes mypy get confused and require the
  435. # return types of functions to be combinations of Deferred and Failure
  436. # rather than the actual return type. I'm not entirely sure what about the
  437. # semantics of <nothing> create this overzealousness on the part of trying
  438. # to assign a type; there *might* be a mypy bug in there somewhere.
  439. # Possibly https://github.com/python/typing/issues/548 is implicated here
  440. # because TypeVar for the *callable* with a variadic bound might express to
  441. # Mypy the actual constraint that we want on its type.
  442. @overload
  443. def addCallback(
  444. self,
  445. callback: Callable[Concatenate[_SelfResultT, _P], Failure],
  446. *args: _P.args,
  447. **kwargs: _P.kwargs,
  448. ) -> Deferred[_NextResultT]:
  449. ...
  450. @overload
  451. def addCallback(
  452. self,
  453. callback: Callable[
  454. Concatenate[_SelfResultT, _P],
  455. Union[Failure, Deferred[_NextResultT]],
  456. ],
  457. *args: _P.args,
  458. **kwargs: _P.kwargs,
  459. ) -> Deferred[_NextResultT]:
  460. ...
  461. @overload
  462. def addCallback(
  463. self,
  464. callback: Callable[Concatenate[_SelfResultT, _P], Union[Failure, _NextResultT]],
  465. *args: _P.args,
  466. **kwargs: _P.kwargs,
  467. ) -> Deferred[_NextResultT]:
  468. ...
  469. @overload
  470. def addCallback(
  471. self,
  472. callback: Callable[Concatenate[_SelfResultT, _P], Deferred[_NextResultT]],
  473. *args: _P.args,
  474. **kwargs: _P.kwargs,
  475. ) -> Deferred[_NextResultT]:
  476. ...
  477. @overload
  478. def addCallback(
  479. self,
  480. callback: Callable[
  481. Concatenate[_SelfResultT, _P],
  482. Union[Deferred[_NextResultT], _NextResultT],
  483. ],
  484. *args: _P.args,
  485. **kwargs: _P.kwargs,
  486. ) -> Deferred[_NextResultT]:
  487. ...
  488. @overload
  489. def addCallback(
  490. self,
  491. callback: Callable[Concatenate[_SelfResultT, _P], _NextResultT],
  492. *args: _P.args,
  493. **kwargs: _P.kwargs,
  494. ) -> Deferred[_NextResultT]:
  495. ...
  496. def addCallback(self, callback: Any, *args: Any, **kwargs: Any) -> "Deferred[Any]":
  497. """
  498. Convenience method for adding just a callback.
  499. See L{addCallbacks}.
  500. """
  501. # Implementation Note: Any annotations for brevity; the overloads above
  502. # handle specifying the actual signature, and there's nothing worth
  503. # type-checking in this implementation.
  504. return self.addCallbacks(callback, callbackArgs=args, callbackKeywords=kwargs)
  505. @overload
  506. def addErrback(
  507. self,
  508. errback: Callable[Concatenate[Failure, _P], Deferred[_NextResultT]],
  509. *args: _P.args,
  510. **kwargs: _P.kwargs,
  511. ) -> "Deferred[Union[_SelfResultT, _NextResultT]]":
  512. ...
  513. @overload
  514. def addErrback(
  515. self,
  516. errback: Callable[Concatenate[Failure, _P], Failure],
  517. *args: _P.args,
  518. **kwargs: _P.kwargs,
  519. ) -> "Deferred[Union[_SelfResultT]]":
  520. ...
  521. @overload
  522. def addErrback(
  523. self,
  524. errback: Callable[Concatenate[Failure, _P], _NextResultT],
  525. *args: _P.args,
  526. **kwargs: _P.kwargs,
  527. ) -> "Deferred[Union[_SelfResultT, _NextResultT]]":
  528. ...
  529. def addErrback(self, errback: Any, *args: Any, **kwargs: Any) -> "Deferred[Any]":
  530. """
  531. Convenience method for adding just an errback.
  532. See L{addCallbacks}.
  533. """
  534. # See implementation note in addCallbacks about Any arguments
  535. return self.addCallbacks(
  536. passthru, errback, errbackArgs=args, errbackKeywords=kwargs
  537. )
  538. @overload
  539. def addBoth(
  540. self,
  541. callback: Callable[Concatenate[Union[_SelfResultT, Failure], _P], Failure],
  542. *args: _P.args,
  543. **kwargs: _P.kwargs,
  544. ) -> Deferred[_NextResultT]:
  545. ...
  546. @overload
  547. def addBoth(
  548. self,
  549. callback: Callable[
  550. Concatenate[Union[_SelfResultT, Failure], _P],
  551. Union[Failure, Deferred[_NextResultT]],
  552. ],
  553. *args: _P.args,
  554. **kwargs: _P.kwargs,
  555. ) -> Deferred[_NextResultT]:
  556. ...
  557. @overload
  558. def addBoth(
  559. self,
  560. callback: Callable[
  561. Concatenate[Union[_SelfResultT, Failure], _P], Union[Failure, _NextResultT]
  562. ],
  563. *args: _P.args,
  564. **kwargs: _P.kwargs,
  565. ) -> Deferred[_NextResultT]:
  566. ...
  567. @overload
  568. def addBoth(
  569. self,
  570. callback: Callable[
  571. Concatenate[Union[_SelfResultT, Failure], _P], Deferred[_NextResultT]
  572. ],
  573. *args: _P.args,
  574. **kwargs: _P.kwargs,
  575. ) -> Deferred[_NextResultT]:
  576. ...
  577. @overload
  578. def addBoth(
  579. self,
  580. callback: Callable[
  581. Concatenate[Union[_SelfResultT, Failure], _P],
  582. Union[Deferred[_NextResultT], _NextResultT],
  583. ],
  584. *args: _P.args,
  585. **kwargs: _P.kwargs,
  586. ) -> Deferred[_NextResultT]:
  587. ...
  588. @overload
  589. def addBoth(
  590. self,
  591. callback: Callable[Concatenate[Union[_SelfResultT, Failure], _P], _NextResultT],
  592. *args: _P.args,
  593. **kwargs: _P.kwargs,
  594. ) -> Deferred[_NextResultT]:
  595. ...
  596. @overload
  597. def addBoth(
  598. self,
  599. callback: Callable[Concatenate[_T, _P], _T],
  600. *args: _P.args,
  601. **kwargs: _P.kwargs,
  602. ) -> Deferred[_SelfResultT]:
  603. ...
  604. def addBoth(self, callback: Any, *args: Any, **kwargs: Any) -> "Deferred[Any]":
  605. """
  606. Convenience method for adding a single callable as both a callback
  607. and an errback.
  608. See L{addCallbacks}.
  609. """
  610. # See implementation note in addCallbacks about Any arguments
  611. return self.addCallbacks(
  612. callback,
  613. callback,
  614. callbackArgs=args,
  615. errbackArgs=args,
  616. callbackKeywords=kwargs,
  617. errbackKeywords=kwargs,
  618. )
  619. # END way too many overloads
  620. def addTimeout(
  621. self,
  622. timeout: float,
  623. clock: IReactorTime,
  624. onTimeoutCancel: Optional[
  625. Callable[
  626. [Union[_SelfResultT, Failure], float],
  627. Union[_NextResultT, Failure],
  628. ]
  629. ] = None,
  630. ) -> "Deferred[Union[_SelfResultT, _NextResultT]]":
  631. """
  632. Time out this L{Deferred} by scheduling it to be cancelled after
  633. C{timeout} seconds.
  634. The timeout encompasses all the callbacks and errbacks added to this
  635. L{defer.Deferred} before the call to L{addTimeout}, and none added
  636. after the call.
  637. If this L{Deferred} gets timed out, it errbacks with a L{TimeoutError},
  638. unless a cancelable function was passed to its initialization or unless
  639. a different C{onTimeoutCancel} callable is provided.
  640. @param timeout: number of seconds to wait before timing out this
  641. L{Deferred}
  642. @param clock: The object which will be used to schedule the timeout.
  643. @param onTimeoutCancel: A callable which is called immediately after
  644. this L{Deferred} times out, and not if this L{Deferred} is
  645. otherwise cancelled before the timeout. It takes an arbitrary
  646. value, which is the value of this L{Deferred} at that exact point
  647. in time (probably a L{CancelledError} L{Failure}), and the
  648. C{timeout}. The default callable (if C{None} is provided) will
  649. translate a L{CancelledError} L{Failure} into a L{TimeoutError}.
  650. @return: C{self}.
  651. @since: 16.5
  652. """
  653. timedOut = [False]
  654. def timeItOut() -> None:
  655. timedOut[0] = True
  656. self.cancel()
  657. delayedCall = clock.callLater(timeout, timeItOut)
  658. def convertCancelled(
  659. result: Union[_SelfResultT, Failure],
  660. ) -> Union[_SelfResultT, _NextResultT, Failure]:
  661. # if C{deferred} was timed out, call the translation function,
  662. # if provided, otherwise just use L{cancelledToTimedOutError}
  663. if timedOut[0]:
  664. toCall = onTimeoutCancel or _cancelledToTimedOutError
  665. return toCall(result, timeout)
  666. return result
  667. def cancelTimeout(result: _T) -> _T:
  668. # stop the pending call to cancel the deferred if it's been fired
  669. if delayedCall.active():
  670. delayedCall.cancel()
  671. return result
  672. # Note: Mypy cannot infer this type, apparently thanks to the ambiguity
  673. # of _SelfResultT / _NextResultT both being unbound. Explicitly
  674. # annotating it seems to do the trick though.
  675. converted: Deferred[Union[_SelfResultT, _NextResultT]] = self.addBoth(
  676. convertCancelled
  677. )
  678. return converted.addBoth(cancelTimeout)
  679. def chainDeferred(self, d: "Deferred[_SelfResultT]") -> "Deferred[None]":
  680. """
  681. Chain another L{Deferred} to this L{Deferred}.
  682. This method adds callbacks to this L{Deferred} to call C{d}'s callback
  683. or errback, as appropriate. It is merely a shorthand way of performing
  684. the following::
  685. d1.addCallbacks(d2.callback, d2.errback)
  686. When you chain a deferred C{d2} to another deferred C{d1} with
  687. C{d1.chainDeferred(d2)}, you are making C{d2} participate in the
  688. callback chain of C{d1}.
  689. Thus any event that fires C{d1} will also fire C{d2}.
  690. However, the converse is B{not} true; if C{d2} is fired, C{d1} will not
  691. be affected.
  692. Note that unlike the case where chaining is caused by a L{Deferred}
  693. being returned from a callback, it is possible to cause the call
  694. stack size limit to be exceeded by chaining many L{Deferred}s
  695. together with C{chainDeferred}.
  696. @return: C{self}.
  697. """
  698. d._chainedTo = self
  699. return self.addCallbacks(d.callback, d.errback)
  700. def callback(self, result: Union[_SelfResultT, Failure]) -> None:
  701. """
  702. Run all success callbacks that have been added to this L{Deferred}.
  703. Each callback will have its result passed as the first argument to
  704. the next; this way, the callbacks act as a 'processing chain'. If
  705. the success-callback returns a L{Failure} or raises an L{Exception},
  706. processing will continue on the *error* callback chain. If a
  707. callback (or errback) returns another L{Deferred}, this L{Deferred}
  708. will be chained to it (and further callbacks will not run until that
  709. L{Deferred} has a result).
  710. An instance of L{Deferred} may only have either L{callback} or
  711. L{errback} called on it, and only once.
  712. @param result: The object which will be passed to the first callback
  713. added to this L{Deferred} (via L{addCallback}), unless C{result} is
  714. a L{Failure}, in which case the behavior is the same as calling
  715. C{errback(result)}.
  716. @raise AlreadyCalledError: If L{callback} or L{errback} has already been
  717. called on this L{Deferred}.
  718. """
  719. assert not isinstance(result, Deferred)
  720. self._startRunCallbacks(result)
  721. def errback(self, fail: Optional[Union[Failure, BaseException]] = None) -> None:
  722. """
  723. Run all error callbacks that have been added to this L{Deferred}.
  724. Each callback will have its result passed as the first
  725. argument to the next; this way, the callbacks act as a
  726. 'processing chain'. Also, if the error-callback returns a non-Failure
  727. or doesn't raise an L{Exception}, processing will continue on the
  728. *success*-callback chain.
  729. If the argument that's passed to me is not a L{Failure} instance,
  730. it will be embedded in one. If no argument is passed, a
  731. L{Failure} instance will be created based on the current
  732. traceback stack.
  733. Passing a string as `fail' is deprecated, and will be punished with
  734. a warning message.
  735. An instance of L{Deferred} may only have either L{callback} or
  736. L{errback} called on it, and only once.
  737. @param fail: The L{Failure} object which will be passed to the first
  738. errback added to this L{Deferred} (via L{addErrback}).
  739. Alternatively, a L{Exception} instance from which a L{Failure} will
  740. be constructed (with no traceback) or L{None} to create a L{Failure}
  741. instance from the current exception state (with a traceback).
  742. @raise AlreadyCalledError: If L{callback} or L{errback} has already been
  743. called on this L{Deferred}.
  744. @raise NoCurrentExceptionError: If C{fail} is L{None} but there is
  745. no current exception state.
  746. """
  747. if fail is None:
  748. fail = Failure(captureVars=self.debug)
  749. elif not isinstance(fail, Failure):
  750. fail = Failure(fail)
  751. self._startRunCallbacks(fail)
  752. def pause(self) -> None:
  753. """
  754. Stop processing on a L{Deferred} until L{unpause}() is called.
  755. """
  756. self.paused = self.paused + 1
  757. def unpause(self) -> None:
  758. """
  759. Process all callbacks made since L{pause}() was called.
  760. """
  761. self.paused = self.paused - 1
  762. if self.paused:
  763. return
  764. if self.called:
  765. self._runCallbacks()
  766. def cancel(self) -> None:
  767. """
  768. Cancel this L{Deferred}.
  769. If the L{Deferred} has not yet had its C{errback} or C{callback} method
  770. invoked, call the canceller function provided to the constructor. If
  771. that function does not invoke C{callback} or C{errback}, or if no
  772. canceller function was provided, errback with L{CancelledError}.
  773. If this L{Deferred} is waiting on another L{Deferred}, forward the
  774. cancellation to the other L{Deferred}.
  775. """
  776. if not self.called:
  777. canceller = self._canceller
  778. if canceller:
  779. canceller(self)
  780. else:
  781. # Arrange to eat the callback that will eventually be fired
  782. # since there was no real canceller.
  783. self._suppressAlreadyCalled = True
  784. if not self.called:
  785. # There was no canceller, or the canceller didn't call
  786. # callback or errback.
  787. self.errback(Failure(CancelledError()))
  788. elif isinstance(self.result, Deferred):
  789. # Waiting for another deferred -- cancel it instead.
  790. self.result.cancel()
  791. def _startRunCallbacks(self, result: object) -> None:
  792. if self.called:
  793. if self._suppressAlreadyCalled:
  794. self._suppressAlreadyCalled = False
  795. return
  796. if self.debug:
  797. if self._debugInfo is None:
  798. self._debugInfo = DebugInfo()
  799. extra = "\n" + self._debugInfo._getDebugTracebacks()
  800. raise AlreadyCalledError(extra)
  801. raise AlreadyCalledError
  802. if self.debug:
  803. if self._debugInfo is None:
  804. self._debugInfo = DebugInfo()
  805. self._debugInfo.invoker = traceback.format_stack()[:-2]
  806. self.called = True
  807. # Clear the canceller to avoid any circular references. This is safe to
  808. # do as the canceller does not get called after the deferred has fired
  809. self._canceller = None
  810. self.result = result
  811. self._runCallbacks()
  812. def _continuation(self) -> _CallbackChain:
  813. """
  814. Build a tuple of callback and errback with L{_Sentinel._CONTINUE}.
  815. """
  816. return (
  817. (_Sentinel._CONTINUE, (self,), _NONE_KWARGS),
  818. (_Sentinel._CONTINUE, (self,), _NONE_KWARGS),
  819. )
  820. def _runCallbacks(self) -> None:
  821. """
  822. Run the chain of callbacks once a result is available.
  823. This consists of a simple loop over all of the callbacks, calling each
  824. with the current result and making the current result equal to the
  825. return value (or raised exception) of that call.
  826. If L{_runningCallbacks} is true, this loop won't run at all, since
  827. it is already running above us on the call stack. If C{self.paused} is
  828. true, the loop also won't run, because that's what it means to be
  829. paused.
  830. The loop will terminate before processing all of the callbacks if a
  831. L{Deferred} without a result is encountered.
  832. If a L{Deferred} I{with} a result is encountered, that result is taken
  833. and the loop proceeds.
  834. @note: The implementation is complicated slightly by the fact that
  835. chaining (associating two L{Deferred}s with each other such that one
  836. will wait for the result of the other, as happens when a Deferred is
  837. returned from a callback on another L{Deferred}) is supported
  838. iteratively rather than recursively, to avoid running out of stack
  839. frames when processing long chains.
  840. """
  841. if self._runningCallbacks:
  842. # Don't recursively run callbacks
  843. return
  844. # Keep track of all the Deferreds encountered while propagating results
  845. # up a chain. The way a Deferred gets onto this stack is by having
  846. # added its _continuation() to the callbacks list of a second Deferred
  847. # and then that second Deferred being fired. ie, if ever had _chainedTo
  848. # set to something other than None, you might end up on this stack.
  849. chain: List[Deferred[Any]] = [self]
  850. while chain:
  851. current = chain[-1]
  852. if current.paused:
  853. # This Deferred isn't going to produce a result at all. All the
  854. # Deferreds up the chain waiting on it will just have to...
  855. # wait.
  856. return
  857. finished = True
  858. current._chainedTo = None
  859. while current.callbacks:
  860. item = current.callbacks.pop(0)
  861. if not isinstance(current.result, Failure):
  862. callback, args, kwargs = item[0]
  863. else:
  864. # type note: Callback signature also works for Errbacks in
  865. # this context.
  866. callback, args, kwargs = item[1]
  867. # Avoid recursion if we can.
  868. if callback is _CONTINUE:
  869. # Give the waiting Deferred our current result and then
  870. # forget about that result ourselves.
  871. chainee = cast(Deferred[object], args[0])
  872. chainee.result = current.result
  873. current.result = None
  874. # Making sure to update _debugInfo
  875. if current._debugInfo is not None:
  876. current._debugInfo.failResult = None
  877. chainee.paused -= 1
  878. chain.append(chainee)
  879. # Delay cleaning this Deferred and popping it from the chain
  880. # until after we've dealt with chainee.
  881. finished = False
  882. break
  883. try:
  884. current._runningCallbacks = True
  885. try:
  886. # type note: mypy sees `callback is _CONTINUE` above and
  887. # then decides that `callback` is not callable.
  888. # This goes away when we use `_Sentinel._CONTINUE`
  889. # instead, but we don't want to do that attribute
  890. # lookup in this hot code path, so we ignore the mypy
  891. # complaint here.
  892. current.result = callback( # type: ignore[misc]
  893. current.result, *args, **kwargs
  894. )
  895. if current.result is current:
  896. warnAboutFunction(
  897. callback,
  898. "Callback returned the Deferred "
  899. "it was attached to; this breaks the "
  900. "callback chain and will raise an "
  901. "exception in the future.",
  902. )
  903. finally:
  904. current._runningCallbacks = False
  905. except BaseException:
  906. # Including full frame information in the Failure is quite
  907. # expensive, so we avoid it unless self.debug is set.
  908. current.result = Failure(captureVars=self.debug)
  909. else:
  910. if isinstance(current.result, Deferred):
  911. # The result is another Deferred. If it has a result,
  912. # we can take it and keep going.
  913. resultResult = getattr(current.result, "result", _NO_RESULT)
  914. if (
  915. resultResult is _NO_RESULT
  916. or isinstance(resultResult, Deferred)
  917. or current.result.paused
  918. ):
  919. # Nope, it didn't. Pause and chain.
  920. current.pause()
  921. current._chainedTo = current.result
  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. current.result.callbacks.append(current._continuation())
  927. break
  928. else:
  929. # Yep, it did. Steal it.
  930. current.result.result = None
  931. # Make sure _debugInfo's failure state is updated.
  932. if current.result._debugInfo is not None:
  933. current.result._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 ensureDeferred(
  1102. coro: Union[
  1103. Coroutine[Deferred[Any], Any, _T],
  1104. Generator[Deferred[Any], Any, _T],
  1105. Deferred[_T],
  1106. ]
  1107. ) -> Deferred[_T]:
  1108. """
  1109. Schedule the execution of a coroutine that awaits/yields from L{Deferred}s,
  1110. wrapping it in a L{Deferred} that will fire on success/failure of the
  1111. coroutine. If a Deferred is passed to this function, it will be returned
  1112. directly (mimicking the L{asyncio.ensure_future} function).
  1113. See L{Deferred.fromCoroutine} for examples of coroutines.
  1114. @param coro: The coroutine object to schedule, or a L{Deferred}.
  1115. """
  1116. if isinstance(coro, Deferred):
  1117. return coro
  1118. else:
  1119. try:
  1120. return Deferred.fromCoroutine(coro)
  1121. except NotACoroutineError:
  1122. # It's not a coroutine. Raise an exception, but say that it's also
  1123. # not a Deferred so the error makes sense.
  1124. raise NotACoroutineError(f"{coro!r} is not a coroutine or a Deferred")
  1125. @comparable
  1126. class FirstError(Exception):
  1127. """
  1128. First error to occur in a L{DeferredList} if C{fireOnOneErrback} is set.
  1129. @ivar subFailure: The L{Failure} that occurred.
  1130. @ivar index: The index of the L{Deferred} in the L{DeferredList} where
  1131. it happened.
  1132. """
  1133. def __init__(self, failure: Failure, index: int) -> None:
  1134. Exception.__init__(self, failure, index)
  1135. self.subFailure = failure
  1136. self.index = index
  1137. def __repr__(self) -> str:
  1138. """
  1139. The I{repr} of L{FirstError} instances includes the repr of the
  1140. wrapped failure's exception and the index of the L{FirstError}.
  1141. """
  1142. return "FirstError[#%d, %r]" % (self.index, self.subFailure.value)
  1143. def __str__(self) -> str:
  1144. """
  1145. The I{str} of L{FirstError} instances includes the I{str} of the
  1146. entire wrapped failure (including its traceback and exception) and
  1147. the index of the L{FirstError}.
  1148. """
  1149. return "FirstError[#%d, %s]" % (self.index, self.subFailure)
  1150. def __cmp__(self, other: object) -> int:
  1151. """
  1152. Comparison between L{FirstError} and other L{FirstError} instances
  1153. is defined as the comparison of the index and sub-failure of each
  1154. instance. L{FirstError} instances don't compare equal to anything
  1155. that isn't a L{FirstError} instance.
  1156. @since: 8.2
  1157. """
  1158. if isinstance(other, FirstError):
  1159. return cmp((self.index, self.subFailure), (other.index, other.subFailure))
  1160. return -1
  1161. _DeferredListSingleResultT = Tuple[_SelfResultT, int]
  1162. _DeferredListResultItemT = Tuple[bool, _SelfResultT]
  1163. _DeferredListResultListT = List[_DeferredListResultItemT[_SelfResultT]]
  1164. if TYPE_CHECKING:
  1165. # The result type is different depending on whether fireOnOneCallback
  1166. # is True or False. The type system is not flexible enough to handle
  1167. # that in a class definition, so instead we pretend that DeferredList
  1168. # is a function that returns a Deferred.
  1169. @overload
  1170. def _DeferredList(
  1171. deferredList: Iterable[Deferred[_SelfResultT]],
  1172. fireOnOneCallback: Literal[True],
  1173. fireOnOneErrback: bool = False,
  1174. consumeErrors: bool = False,
  1175. ) -> Deferred[_DeferredListSingleResultT[_SelfResultT]]:
  1176. ...
  1177. @overload
  1178. def _DeferredList(
  1179. deferredList: Iterable[Deferred[_SelfResultT]],
  1180. fireOnOneCallback: Literal[False] = False,
  1181. fireOnOneErrback: bool = False,
  1182. consumeErrors: bool = False,
  1183. ) -> Deferred[_DeferredListResultListT[_SelfResultT]]:
  1184. ...
  1185. def _DeferredList(
  1186. deferredList: Iterable[Deferred[_SelfResultT]],
  1187. fireOnOneCallback: bool = False,
  1188. fireOnOneErrback: bool = False,
  1189. consumeErrors: bool = False,
  1190. ) -> Union[
  1191. Deferred[_DeferredListSingleResultT[_SelfResultT]],
  1192. Deferred[_DeferredListResultListT[_SelfResultT]],
  1193. ]:
  1194. ...
  1195. DeferredList = _DeferredList
  1196. class DeferredList( # type: ignore[no-redef] # noqa:F811
  1197. Deferred[_DeferredListResultListT[Any]]
  1198. ):
  1199. """
  1200. L{DeferredList} is a tool for collecting the results of several Deferreds.
  1201. This tracks a list of L{Deferred}s for their results, and makes a single
  1202. callback when they have all completed. By default, the ultimate result is a
  1203. list of (success, result) tuples, 'success' being a boolean.
  1204. L{DeferredList} exposes the same API that L{Deferred} does, so callbacks and
  1205. errbacks can be added to it in the same way.
  1206. L{DeferredList} is implemented by adding callbacks and errbacks to each
  1207. L{Deferred} in the list passed to it. This means callbacks and errbacks
  1208. added to the Deferreds before they are passed to L{DeferredList} will change
  1209. the result that L{DeferredList} sees (i.e., L{DeferredList} is not special).
  1210. Callbacks and errbacks can also be added to the Deferreds after they are
  1211. passed to L{DeferredList} and L{DeferredList} may change the result that
  1212. they see.
  1213. See the documentation for the C{__init__} arguments for more information.
  1214. @ivar _deferredList: The L{list} of L{Deferred}s to track.
  1215. """
  1216. fireOnOneCallback = False
  1217. fireOnOneErrback = False
  1218. def __init__(
  1219. self,
  1220. deferredList: Iterable[Deferred[_SelfResultT]],
  1221. fireOnOneCallback: bool = False,
  1222. fireOnOneErrback: bool = False,
  1223. consumeErrors: bool = False,
  1224. ):
  1225. """
  1226. Initialize a DeferredList.
  1227. @param deferredList: The deferreds to track.
  1228. @param fireOnOneCallback: (keyword param) a flag indicating that this
  1229. L{DeferredList} will fire when the first L{Deferred} in
  1230. C{deferredList} fires with a non-failure result without waiting for
  1231. any of the other Deferreds. When this flag is set, the DeferredList
  1232. will fire with a two-tuple: the first element is the result of the
  1233. Deferred which fired; the second element is the index in
  1234. C{deferredList} of that Deferred.
  1235. @param fireOnOneErrback: (keyword param) a flag indicating that this
  1236. L{DeferredList} will fire when the first L{Deferred} in
  1237. C{deferredList} fires with a failure result without waiting for any
  1238. of the other Deferreds. When this flag is set, if a Deferred in the
  1239. list errbacks, the DeferredList will errback with a L{FirstError}
  1240. failure wrapping the failure of that Deferred.
  1241. @param consumeErrors: (keyword param) a flag indicating that failures in
  1242. any of the included L{Deferred}s should not be propagated to
  1243. errbacks added to the individual L{Deferred}s after this
  1244. L{DeferredList} is constructed. After constructing the
  1245. L{DeferredList}, any errors in the individual L{Deferred}s will be
  1246. converted to a callback result of L{None}. This is useful to
  1247. prevent spurious 'Unhandled error in Deferred' messages from being
  1248. logged. This does not prevent C{fireOnOneErrback} from working.
  1249. """
  1250. self._deferredList = list(deferredList)
  1251. # Note this contains optional result values as the DeferredList is
  1252. # processing its results, even though the callback result will not,
  1253. # which is why we aren't using _DeferredListResultListT here.
  1254. self.resultList: List[Optional[_DeferredListResultItemT[Any]]] = [None] * len(
  1255. self._deferredList
  1256. )
  1257. """
  1258. The final result, in progress.
  1259. Each item in the list corresponds to the L{Deferred} at the same
  1260. position in L{_deferredList}. It will be L{None} if the L{Deferred}
  1261. did not complete yet, or a C{(success, result)} pair if it did.
  1262. """
  1263. Deferred.__init__(self)
  1264. if len(self._deferredList) == 0 and not fireOnOneCallback:
  1265. self.callback([])
  1266. # These flags need to be set *before* attaching callbacks to the
  1267. # deferreds, because the callbacks use these flags, and will run
  1268. # synchronously if any of the deferreds are already fired.
  1269. self.fireOnOneCallback = fireOnOneCallback
  1270. self.fireOnOneErrback = fireOnOneErrback
  1271. self.consumeErrors = consumeErrors
  1272. self.finishedCount = 0
  1273. index = 0
  1274. for deferred in self._deferredList:
  1275. deferred.addCallbacks(
  1276. self._cbDeferred,
  1277. self._cbDeferred,
  1278. callbackArgs=(index, SUCCESS),
  1279. errbackArgs=(index, FAILURE),
  1280. )
  1281. index = index + 1
  1282. def _cbDeferred(
  1283. self, result: _SelfResultT, index: int, succeeded: bool
  1284. ) -> Optional[_SelfResultT]:
  1285. """
  1286. (internal) Callback for when one of my deferreds fires.
  1287. """
  1288. self.resultList[index] = (succeeded, result)
  1289. self.finishedCount += 1
  1290. if not self.called:
  1291. if succeeded == SUCCESS and self.fireOnOneCallback:
  1292. self.callback((result, index)) # type: ignore[arg-type]
  1293. elif succeeded == FAILURE and self.fireOnOneErrback:
  1294. assert isinstance(result, Failure)
  1295. self.errback(Failure(FirstError(result, index)))
  1296. elif self.finishedCount == len(self.resultList):
  1297. # At this point, None values in self.resultList have been
  1298. # replaced by result values, so we cast it to
  1299. # _DeferredListResultListT to match the callback result type.
  1300. self.callback(cast(_DeferredListResultListT[Any], self.resultList))
  1301. if succeeded == FAILURE and self.consumeErrors:
  1302. return None
  1303. return result
  1304. def cancel(self) -> None:
  1305. """
  1306. Cancel this L{DeferredList}.
  1307. If the L{DeferredList} hasn't fired yet, cancel every L{Deferred} in
  1308. the list.
  1309. If the L{DeferredList} has fired, including the case where the
  1310. C{fireOnOneCallback}/C{fireOnOneErrback} flag is set and the
  1311. L{DeferredList} fires because one L{Deferred} in the list fires with a
  1312. non-failure/failure result, do nothing in the C{cancel} method.
  1313. """
  1314. if not self.called:
  1315. for deferred in self._deferredList:
  1316. try:
  1317. deferred.cancel()
  1318. except BaseException:
  1319. log.failure("Exception raised from user supplied canceller")
  1320. def _parseDeferredListResult(
  1321. resultList: List[_DeferredListResultItemT[_T]], fireOnOneErrback: bool = False, /
  1322. ) -> List[_T]:
  1323. if __debug__:
  1324. for result in resultList:
  1325. assert result is not None
  1326. success, value = result
  1327. assert success
  1328. return [x[1] for x in resultList]
  1329. def gatherResults(
  1330. deferredList: Iterable[Deferred[_T]], consumeErrors: bool = False
  1331. ) -> Deferred[List[_T]]:
  1332. """
  1333. Returns, via a L{Deferred}, a list with the results of the given
  1334. L{Deferred}s - in effect, a "join" of multiple deferred operations.
  1335. The returned L{Deferred} will fire when I{all} of the provided L{Deferred}s
  1336. have fired, or when any one of them has failed.
  1337. This method can be cancelled by calling the C{cancel} method of the
  1338. L{Deferred}, all the L{Deferred}s in the list will be cancelled.
  1339. This differs from L{DeferredList} in that you don't need to parse
  1340. the result for success/failure.
  1341. @param consumeErrors: (keyword param) a flag, defaulting to False,
  1342. indicating that failures in any of the given L{Deferred}s should not be
  1343. propagated to errbacks added to the individual L{Deferred}s after this
  1344. L{gatherResults} invocation. Any such errors in the individual
  1345. L{Deferred}s will be converted to a callback result of L{None}. This
  1346. is useful to prevent spurious 'Unhandled error in Deferred' messages
  1347. from being logged. This parameter is available since 11.1.0.
  1348. """
  1349. return DeferredList(
  1350. deferredList, fireOnOneErrback=True, consumeErrors=consumeErrors
  1351. ).addCallback(_parseDeferredListResult)
  1352. class FailureGroup(Exception):
  1353. """
  1354. More than one failure occurred.
  1355. """
  1356. def __init__(self, failures: Sequence[Failure]) -> None:
  1357. super(FailureGroup, self).__init__()
  1358. self.failures = failures
  1359. def race(ds: Sequence[Deferred[_T]]) -> Deferred[tuple[int, _T]]:
  1360. """
  1361. Select the first available result from the sequence of Deferreds and
  1362. cancel the rest.
  1363. @return: A cancellable L{Deferred} that fires with the index and output of
  1364. the element of C{ds} to have a success result first, or that fires
  1365. with L{FailureGroup} holding a list of their failures if they all
  1366. fail.
  1367. """
  1368. # Keep track of the Deferred for the action which completed first. When
  1369. # it completes, all of the other Deferreds will get cancelled but this one
  1370. # shouldn't be. Even though it "completed" it isn't really done - the
  1371. # caller will still be using it for something. If we cancelled it,
  1372. # cancellation could propagate down to them.
  1373. winner: Optional[Deferred[_T]] = None
  1374. # The cancellation function for the Deferred this function returns.
  1375. def cancel(result: Deferred[_T]) -> None:
  1376. # If it is cancelled then we cancel all of the Deferreds for the
  1377. # individual actions because there is no longer the possibility of
  1378. # delivering any of their results anywhere. We don't have to fire
  1379. # `result` because the Deferred will do that for us.
  1380. for d in to_cancel:
  1381. d.cancel()
  1382. # The Deferred that this function will return. It will fire with the
  1383. # index and output of the action that completes first, or errback if all
  1384. # of the actions fail. If it is cancelled, all of the actions will be
  1385. # cancelled.
  1386. final_result: Deferred[tuple[int, _T]] = Deferred(canceller=cancel)
  1387. # A callback for an individual action.
  1388. def succeeded(this_output: _T, this_index: int) -> None:
  1389. # If it is the first action to succeed then it becomes the "winner",
  1390. # its index/output become the externally visible result, and the rest
  1391. # of the action Deferreds get cancelled. If it is not the first
  1392. # action to succeed (because some action did not support
  1393. # cancellation), just ignore the result. It is uncommon for this
  1394. # callback to be entered twice. The only way it can happen is if one
  1395. # of the input Deferreds has a cancellation function that fires the
  1396. # Deferred with a success result.
  1397. nonlocal winner
  1398. if winner is None:
  1399. # This is the first success. Act on it.
  1400. winner = to_cancel[this_index]
  1401. # Cancel the rest.
  1402. for d in to_cancel:
  1403. if d is not winner:
  1404. d.cancel()
  1405. # Fire our Deferred
  1406. final_result.callback((this_index, this_output))
  1407. # Keep track of how many actions have failed. If they all fail we need to
  1408. # deliver failure notification on our externally visible result.
  1409. failure_state = []
  1410. def failed(failure: Failure, this_index: int) -> None:
  1411. failure_state.append((this_index, failure))
  1412. if len(failure_state) == len(to_cancel):
  1413. # Every operation failed.
  1414. failure_state.sort()
  1415. failures = [f for (ignored, f) in failure_state]
  1416. final_result.errback(FailureGroup(failures))
  1417. # Copy the sequence of Deferreds so we know it doesn't get mutated out
  1418. # from under us.
  1419. to_cancel = list(ds)
  1420. for index, d in enumerate(ds):
  1421. # Propagate the position of this action as well as the argument to f
  1422. # to the success callback so we can cancel the right Deferreds and
  1423. # propagate the result outwards.
  1424. d.addCallbacks(succeeded, failed, callbackArgs=(index,), errbackArgs=(index,))
  1425. return final_result
  1426. # Constants for use with DeferredList
  1427. SUCCESS = True
  1428. FAILURE = False
  1429. ## deferredGenerator
  1430. class waitForDeferred:
  1431. """
  1432. See L{deferredGenerator}.
  1433. """
  1434. result: Any = _NO_RESULT
  1435. def __init__(self, d: Deferred[object]) -> None:
  1436. warnings.warn(
  1437. "twisted.internet.defer.waitForDeferred was deprecated in "
  1438. "Twisted 15.0.0; please use twisted.internet.defer.inlineCallbacks "
  1439. "instead",
  1440. DeprecationWarning,
  1441. stacklevel=2,
  1442. )
  1443. if not isinstance(d, Deferred):
  1444. raise TypeError(
  1445. f"You must give waitForDeferred a Deferred. You gave it {d!r}."
  1446. )
  1447. self.d = d
  1448. def getResult(self) -> Any:
  1449. if isinstance(self.result, Failure):
  1450. self.result.raiseException()
  1451. self.result is not _NO_RESULT
  1452. return self.result
  1453. _DeferableGenerator = Generator[object, None, None]
  1454. def _deferGenerator(
  1455. g: _DeferableGenerator, deferred: Deferred[object]
  1456. ) -> Deferred[Any]:
  1457. """
  1458. See L{deferredGenerator}.
  1459. """
  1460. result = None
  1461. # This function is complicated by the need to prevent unbounded recursion
  1462. # arising from repeatedly yielding immediately ready deferreds. This while
  1463. # loop and the waiting variable solve that by manually unfolding the
  1464. # recursion.
  1465. # defgen is waiting for result? # result
  1466. # type note: List[Any] because you can't annotate List items by index.
  1467. # …better fix would be to create a class, but we need to jettison
  1468. # deferredGenerator anyway.
  1469. waiting: List[Any] = [True, None]
  1470. while 1:
  1471. try:
  1472. result = next(g)
  1473. except StopIteration:
  1474. deferred.callback(result)
  1475. return deferred
  1476. except BaseException:
  1477. deferred.errback()
  1478. return deferred
  1479. # Deferred.callback(Deferred) raises an error; we catch this case
  1480. # early here and give a nicer error message to the user in case
  1481. # they yield a Deferred.
  1482. if isinstance(result, Deferred):
  1483. return fail(TypeError("Yield waitForDeferred(d), not d!"))
  1484. if isinstance(result, waitForDeferred):
  1485. # a waitForDeferred was yielded, get the result.
  1486. # Pass result in so it don't get changed going around the loop
  1487. # This isn't a problem for waiting, as it's only reused if
  1488. # gotResult has already been executed.
  1489. def gotResult(
  1490. r: object, result: waitForDeferred = cast(waitForDeferred, result)
  1491. ) -> None:
  1492. result.result = r
  1493. if waiting[0]:
  1494. waiting[0] = False
  1495. waiting[1] = r
  1496. else:
  1497. _deferGenerator(g, deferred)
  1498. result.d.addBoth(gotResult)
  1499. if waiting[0]:
  1500. # Haven't called back yet, set flag so that we get reinvoked
  1501. # and return from the loop
  1502. waiting[0] = False
  1503. return deferred
  1504. # Reset waiting to initial values for next loop
  1505. waiting[0] = True
  1506. waiting[1] = None
  1507. result = None
  1508. @deprecated(Version("Twisted", 15, 0, 0), "twisted.internet.defer.inlineCallbacks")
  1509. def deferredGenerator(
  1510. f: Callable[..., _DeferableGenerator]
  1511. ) -> Callable[..., Deferred[object]]:
  1512. """
  1513. L{deferredGenerator} and L{waitForDeferred} help you write
  1514. L{Deferred}-using code that looks like a regular sequential function.
  1515. Consider the use of L{inlineCallbacks} instead, which can accomplish
  1516. the same thing in a more concise manner.
  1517. There are two important functions involved: L{waitForDeferred}, and
  1518. L{deferredGenerator}. They are used together, like this::
  1519. @deferredGenerator
  1520. def thingummy():
  1521. thing = waitForDeferred(makeSomeRequestResultingInDeferred())
  1522. yield thing
  1523. thing = thing.getResult()
  1524. print(thing) #the result! hoorj!
  1525. L{waitForDeferred} returns something that you should immediately yield; when
  1526. your generator is resumed, calling C{thing.getResult()} will either give you
  1527. the result of the L{Deferred} if it was a success, or raise an exception if it
  1528. was a failure. Calling C{getResult} is B{absolutely mandatory}. If you do
  1529. not call it, I{your program will not work}.
  1530. L{deferredGenerator} takes one of these waitForDeferred-using generator
  1531. functions and converts it into a function that returns a L{Deferred}. The
  1532. result of the L{Deferred} will be the last value that your generator yielded
  1533. unless the last value is a L{waitForDeferred} instance, in which case the
  1534. result will be L{None}. If the function raises an unhandled exception, the
  1535. L{Deferred} will errback instead. Remember that C{return result} won't work;
  1536. use C{yield result; return} in place of that.
  1537. Note that not yielding anything from your generator will make the L{Deferred}
  1538. result in L{None}. Yielding a L{Deferred} from your generator is also an error
  1539. condition; always yield C{waitForDeferred(d)} instead.
  1540. The L{Deferred} returned from your deferred generator may also errback if your
  1541. generator raised an exception. For example::
  1542. @deferredGenerator
  1543. def thingummy():
  1544. thing = waitForDeferred(makeSomeRequestResultingInDeferred())
  1545. yield thing
  1546. thing = thing.getResult()
  1547. if thing == 'I love Twisted':
  1548. # will become the result of the Deferred
  1549. yield 'TWISTED IS GREAT!'
  1550. return
  1551. else:
  1552. # will trigger an errback
  1553. raise Exception('DESTROY ALL LIFE')
  1554. Put succinctly, these functions connect deferred-using code with this 'fake
  1555. blocking' style in both directions: L{waitForDeferred} converts from a
  1556. L{Deferred} to the 'blocking' style, and L{deferredGenerator} converts from the
  1557. 'blocking' style to a L{Deferred}.
  1558. """
  1559. @wraps(f)
  1560. def unwindGenerator(*args: object, **kwargs: object) -> Deferred[object]:
  1561. return _deferGenerator(f(*args, **kwargs), Deferred())
  1562. return unwindGenerator
  1563. ## inlineCallbacks
  1564. class _DefGen_Return(BaseException):
  1565. def __init__(self, value: object) -> None:
  1566. self.value = value
  1567. def returnValue(val: object) -> NoReturn:
  1568. """
  1569. Return val from a L{inlineCallbacks} generator.
  1570. Note: this is currently implemented by raising an exception
  1571. derived from L{BaseException}. You might want to change any
  1572. 'except:' clauses to an 'except Exception:' clause so as not to
  1573. catch this exception.
  1574. Also: while this function currently will work when called from
  1575. within arbitrary functions called from within the generator, do
  1576. not rely upon this behavior.
  1577. """
  1578. raise _DefGen_Return(val)
  1579. @attr.s(auto_attribs=True)
  1580. class _CancellationStatus(Generic[_SelfResultT]):
  1581. """
  1582. Cancellation status of an L{inlineCallbacks} invocation.
  1583. @ivar deferred: the L{Deferred} to callback or errback when the generator
  1584. invocation has finished.
  1585. @ivar waitingOn: the L{Deferred} being waited upon (which
  1586. L{_inlineCallbacks} must fill out before returning)
  1587. """
  1588. deferred: Deferred[_SelfResultT]
  1589. waitingOn: Optional[Deferred[_SelfResultT]] = None
  1590. def _gotResultInlineCallbacks(
  1591. r: object,
  1592. waiting: List[Any],
  1593. gen: Union[
  1594. Generator[Deferred[Any], Any, _T],
  1595. Coroutine[Deferred[Any], Any, _T],
  1596. ],
  1597. status: _CancellationStatus[_T],
  1598. context: _Context,
  1599. ) -> None:
  1600. """
  1601. Helper for L{_inlineCallbacks} to handle a nested L{Deferred} firing.
  1602. @param r: The result of the L{Deferred}
  1603. @param waiting: Whether the L{_inlineCallbacks} was waiting, and the result.
  1604. @param gen: a generator object returned by calling a function or method
  1605. decorated with C{@}L{inlineCallbacks}
  1606. @param status: a L{_CancellationStatus} tracking the current status of C{gen}
  1607. @param context: the contextvars context to run `gen` in
  1608. """
  1609. if waiting[0]:
  1610. waiting[0] = False
  1611. waiting[1] = r
  1612. else:
  1613. _inlineCallbacks(r, gen, status, context)
  1614. @_extraneous
  1615. def _inlineCallbacks(
  1616. result: object,
  1617. gen: Union[
  1618. Generator[Deferred[Any], Any, _T],
  1619. Coroutine[Deferred[Any], Any, _T],
  1620. ],
  1621. status: _CancellationStatus[_T],
  1622. context: _Context,
  1623. ) -> None:
  1624. """
  1625. Carry out the work of L{inlineCallbacks}.
  1626. Iterate the generator produced by an C{@}L{inlineCallbacks}-decorated
  1627. function, C{gen}, C{send()}ing it the results of each value C{yield}ed by
  1628. that generator, until a L{Deferred} is yielded, at which point a callback
  1629. is added to that L{Deferred} to call this function again.
  1630. @param result: The last result seen by this generator. Note that this is
  1631. never a L{Deferred} - by the time this function is invoked, the
  1632. L{Deferred} has been called back and this will be a particular result
  1633. at a point in its callback chain.
  1634. @param gen: a generator object returned by calling a function or method
  1635. decorated with C{@}L{inlineCallbacks}
  1636. @param status: a L{_CancellationStatus} tracking the current status of C{gen}
  1637. @param context: the contextvars context to run `gen` in
  1638. """
  1639. # This function is complicated by the need to prevent unbounded recursion
  1640. # arising from repeatedly yielding immediately ready deferreds. This while
  1641. # loop and the waiting variable solve that by manually unfolding the
  1642. # recursion.
  1643. # waiting for result? # result
  1644. waiting: List[Any] = [True, None]
  1645. stopIteration: bool = False
  1646. callbackValue: Any = None
  1647. while 1:
  1648. try:
  1649. # Send the last result back as the result of the yield expression.
  1650. isFailure = isinstance(result, Failure)
  1651. if isFailure:
  1652. result = context.run(
  1653. cast(Failure, result).throwExceptionIntoGenerator, gen
  1654. )
  1655. else:
  1656. result = context.run(gen.send, result)
  1657. except StopIteration as e:
  1658. # fell off the end, or "return" statement
  1659. stopIteration = True
  1660. callbackValue = getattr(e, "value", None)
  1661. except _DefGen_Return as e:
  1662. # returnValue() was called; time to give a result to the original
  1663. # Deferred. First though, let's try to identify the potentially
  1664. # confusing situation which results when returnValue() is
  1665. # accidentally invoked from a different function, one that wasn't
  1666. # decorated with @inlineCallbacks.
  1667. # The traceback starts in this frame (the one for
  1668. # _inlineCallbacks); the next one down should be the application
  1669. # code.
  1670. excInfo = exc_info()
  1671. assert excInfo is not None
  1672. traceback = excInfo[2]
  1673. assert traceback is not None
  1674. appCodeTrace = traceback.tb_next
  1675. assert appCodeTrace is not None
  1676. if _oldPypyStack:
  1677. # PyPy versions through 7.3.13 add an extra frame; 7.3.14 fixed
  1678. # this discrepancy with CPython. This code can be removed once
  1679. # we no longer need to support PyPy 7.3.13 or older.
  1680. appCodeTrace = appCodeTrace.tb_next
  1681. assert appCodeTrace is not None
  1682. if isFailure:
  1683. # If we invoked this generator frame by throwing an exception
  1684. # into it, then throwExceptionIntoGenerator will consume an
  1685. # additional stack frame itself, so we need to skip that too.
  1686. appCodeTrace = appCodeTrace.tb_next
  1687. assert appCodeTrace is not None
  1688. # Now that we've identified the frame being exited by the
  1689. # exception, let's figure out if returnValue was called from it
  1690. # directly. returnValue itself consumes a stack frame, so the
  1691. # application code will have a tb_next, but it will *not* have a
  1692. # second tb_next.
  1693. assert appCodeTrace.tb_next is not None
  1694. if appCodeTrace.tb_next.tb_next:
  1695. # If returnValue was invoked non-local to the frame which it is
  1696. # exiting, identify the frame that ultimately invoked
  1697. # returnValue so that we can warn the user, as this behavior is
  1698. # confusing.
  1699. ultimateTrace = appCodeTrace
  1700. assert ultimateTrace is not None
  1701. assert ultimateTrace.tb_next is not None
  1702. while ultimateTrace.tb_next.tb_next:
  1703. ultimateTrace = ultimateTrace.tb_next
  1704. assert ultimateTrace is not None
  1705. filename = ultimateTrace.tb_frame.f_code.co_filename
  1706. lineno = ultimateTrace.tb_lineno
  1707. assert ultimateTrace.tb_frame is not None
  1708. assert appCodeTrace.tb_frame is not None
  1709. warnings.warn_explicit(
  1710. "returnValue() in %r causing %r to exit: "
  1711. "returnValue should only be invoked by functions decorated "
  1712. "with inlineCallbacks"
  1713. % (
  1714. ultimateTrace.tb_frame.f_code.co_name,
  1715. appCodeTrace.tb_frame.f_code.co_name,
  1716. ),
  1717. DeprecationWarning,
  1718. filename,
  1719. lineno,
  1720. )
  1721. stopIteration = True
  1722. callbackValue = e.value
  1723. except BaseException:
  1724. status.deferred.errback()
  1725. return
  1726. if stopIteration:
  1727. # Call the callback outside of the exception handler to avoid inappropriate/confusing
  1728. # "During handling of the above exception, another exception occurred:" if the callback
  1729. # itself throws an exception.
  1730. status.deferred.callback(callbackValue)
  1731. return
  1732. if isinstance(result, Deferred):
  1733. # a deferred was yielded, get the result.
  1734. result.addBoth(_gotResultInlineCallbacks, waiting, gen, status, context)
  1735. if waiting[0]:
  1736. # Haven't called back yet, set flag so that we get reinvoked
  1737. # and return from the loop
  1738. waiting[0] = False
  1739. status.waitingOn = result
  1740. return
  1741. result = waiting[1]
  1742. # Reset waiting to initial values for next loop. gotResult uses
  1743. # waiting, but this isn't a problem because gotResult is only
  1744. # executed once, and if it hasn't been executed yet, the return
  1745. # branch above would have been taken.
  1746. waiting[0] = True
  1747. waiting[1] = None
  1748. def _addCancelCallbackToDeferred(
  1749. it: Deferred[_T], status: _CancellationStatus[_T]
  1750. ) -> None:
  1751. """
  1752. Helper for L{_cancellableInlineCallbacks} to add
  1753. L{_handleCancelInlineCallbacks} as the first errback.
  1754. @param it: The L{Deferred} to add the errback to.
  1755. @param status: a L{_CancellationStatus} tracking the current status of C{gen}
  1756. """
  1757. it.callbacks, tmp = [], it.callbacks
  1758. it = it.addErrback(_handleCancelInlineCallbacks, status)
  1759. it.callbacks.extend(tmp)
  1760. it.errback(_InternalInlineCallbacksCancelledError())
  1761. def _handleCancelInlineCallbacks(
  1762. result: Failure, status: _CancellationStatus[_T], /
  1763. ) -> Deferred[_T]:
  1764. """
  1765. Propagate the cancellation of an C{@}L{inlineCallbacks} to the
  1766. L{Deferred} it is waiting on.
  1767. @param result: An L{_InternalInlineCallbacksCancelledError} from
  1768. C{cancel()}.
  1769. @param status: a L{_CancellationStatus} tracking the current status of C{gen}
  1770. @return: A new L{Deferred} that the C{@}L{inlineCallbacks} generator
  1771. can callback or errback through.
  1772. """
  1773. result.trap(_InternalInlineCallbacksCancelledError)
  1774. status.deferred = Deferred(lambda d: _addCancelCallbackToDeferred(d, status))
  1775. # We would only end up here if the inlineCallback is waiting on
  1776. # another Deferred. It needs to be cancelled.
  1777. awaited = status.waitingOn
  1778. assert awaited is not None
  1779. awaited.cancel()
  1780. return status.deferred
  1781. def _cancellableInlineCallbacks(
  1782. gen: Union[
  1783. Generator[Deferred[Any], object, _T],
  1784. Coroutine[Deferred[Any], object, _T],
  1785. ]
  1786. ) -> Deferred[_T]:
  1787. """
  1788. Make an C{@}L{inlineCallbacks} cancellable.
  1789. @param gen: a generator object returned by calling a function or method
  1790. decorated with C{@}L{inlineCallbacks}
  1791. @return: L{Deferred} for the C{@}L{inlineCallbacks} that is cancellable.
  1792. """
  1793. deferred: Deferred[_T] = Deferred(lambda d: _addCancelCallbackToDeferred(d, status))
  1794. status = _CancellationStatus(deferred)
  1795. _inlineCallbacks(None, gen, status, _copy_context())
  1796. return deferred
  1797. class _InternalInlineCallbacksCancelledError(Exception):
  1798. """
  1799. A unique exception used only in L{_cancellableInlineCallbacks} to verify
  1800. that an L{inlineCallbacks} is being cancelled as expected.
  1801. """
  1802. def inlineCallbacks(
  1803. f: Callable[_P, Generator[Deferred[Any], Any, _T]]
  1804. ) -> Callable[_P, Deferred[_T]]:
  1805. """
  1806. L{inlineCallbacks} helps you write L{Deferred}-using code that looks like a
  1807. regular sequential function. For example::
  1808. @inlineCallbacks
  1809. def thingummy():
  1810. thing = yield makeSomeRequestResultingInDeferred()
  1811. print(thing) # the result! hoorj!
  1812. When you call anything that results in a L{Deferred}, you can simply yield it;
  1813. your generator will automatically be resumed when the Deferred's result is
  1814. available. The generator will be sent the result of the L{Deferred} with the
  1815. 'send' method on generators, or if the result was a failure, 'throw'.
  1816. Things that are not L{Deferred}s may also be yielded, and your generator
  1817. will be resumed with the same object sent back. This means C{yield}
  1818. performs an operation roughly equivalent to L{maybeDeferred}.
  1819. Your inlineCallbacks-enabled generator will return a L{Deferred} object, which
  1820. will result in the return value of the generator (or will fail with a
  1821. failure object if your generator raises an unhandled exception). Note that
  1822. you can't use C{return result} to return a value; use C{returnValue(result)}
  1823. instead. Falling off the end of the generator, or simply using C{return}
  1824. will cause the L{Deferred} to have a result of L{None}.
  1825. Be aware that L{returnValue} will not accept a L{Deferred} as a parameter.
  1826. If you believe the thing you'd like to return could be a L{Deferred}, do
  1827. this::
  1828. result = yield result
  1829. returnValue(result)
  1830. The L{Deferred} returned from your deferred generator may errback if your
  1831. generator raised an exception::
  1832. @inlineCallbacks
  1833. def thingummy():
  1834. thing = yield makeSomeRequestResultingInDeferred()
  1835. if thing == 'I love Twisted':
  1836. # will become the result of the Deferred
  1837. returnValue('TWISTED IS GREAT!')
  1838. else:
  1839. # will trigger an errback
  1840. raise Exception('DESTROY ALL LIFE')
  1841. It is possible to use the C{return} statement instead of L{returnValue}::
  1842. @inlineCallbacks
  1843. def loadData(url):
  1844. response = yield makeRequest(url)
  1845. return json.loads(response)
  1846. You can cancel the L{Deferred} returned from your L{inlineCallbacks}
  1847. generator before it is fired by your generator completing (either by
  1848. reaching its end, a C{return} statement, or by calling L{returnValue}).
  1849. A C{CancelledError} will be raised from the C{yield}ed L{Deferred} that
  1850. has been cancelled if that C{Deferred} does not otherwise suppress it.
  1851. """
  1852. @wraps(f)
  1853. def unwindGenerator(*args: _P.args, **kwargs: _P.kwargs) -> Deferred[_T]:
  1854. try:
  1855. gen = f(*args, **kwargs)
  1856. except _DefGen_Return:
  1857. raise TypeError(
  1858. "inlineCallbacks requires %r to produce a generator; instead"
  1859. "caught returnValue being used in a non-generator" % (f,)
  1860. )
  1861. if not isinstance(gen, GeneratorType):
  1862. raise TypeError(
  1863. "inlineCallbacks requires %r to produce a generator; "
  1864. "instead got %r" % (f, gen)
  1865. )
  1866. return _cancellableInlineCallbacks(gen)
  1867. return unwindGenerator
  1868. ## DeferredLock/DeferredQueue
  1869. class _ConcurrencyPrimitive(ABC):
  1870. def __init__(self: Self) -> None:
  1871. self.waiting: List[Deferred[Self]] = []
  1872. def _releaseAndReturn(self, r: _T) -> _T:
  1873. self.release()
  1874. return r
  1875. @overload
  1876. def run(
  1877. self: Self,
  1878. /,
  1879. f: Callable[_P, Deferred[_T]],
  1880. *args: _P.args,
  1881. **kwargs: _P.kwargs,
  1882. ) -> Deferred[_T]:
  1883. ...
  1884. @overload
  1885. def run(
  1886. self: Self,
  1887. /,
  1888. f: Callable[_P, Coroutine[Deferred[Any], Any, _T]],
  1889. *args: _P.args,
  1890. **kwargs: _P.kwargs,
  1891. ) -> Deferred[_T]:
  1892. ...
  1893. @overload
  1894. def run(
  1895. self: Self, /, f: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs
  1896. ) -> Deferred[_T]:
  1897. ...
  1898. def run(
  1899. self: Self,
  1900. /,
  1901. f: Callable[_P, Union[Deferred[_T], Coroutine[Deferred[Any], Any, _T], _T]],
  1902. *args: _P.args,
  1903. **kwargs: _P.kwargs,
  1904. ) -> Deferred[_T]:
  1905. """
  1906. Acquire, run, release.
  1907. This method takes a callable as its first argument and any
  1908. number of other positional and keyword arguments. When the
  1909. lock or semaphore is acquired, the callable will be invoked
  1910. with those arguments.
  1911. The callable may return a L{Deferred}; if it does, the lock or
  1912. semaphore won't be released until that L{Deferred} fires.
  1913. @return: L{Deferred} of function result.
  1914. """
  1915. def execute(ignoredResult: object) -> Deferred[_T]:
  1916. # maybeDeferred arg type requires one of the possible union members
  1917. # and won't accept all possible union members
  1918. return maybeDeferred(f, *args, **kwargs).addBoth(
  1919. self._releaseAndReturn
  1920. ) # type: ignore[return-value]
  1921. return self.acquire().addCallback(execute)
  1922. def __aenter__(self: Self) -> Deferred[Self]:
  1923. """
  1924. We can be used as an asynchronous context manager.
  1925. """
  1926. return self.acquire()
  1927. def __aexit__(
  1928. self,
  1929. __exc_type: Optional[Type[BaseException]],
  1930. __exc_value: Optional[BaseException],
  1931. __traceback: Optional[TracebackType],
  1932. ) -> Deferred[Literal[False]]:
  1933. self.release()
  1934. # We return False to indicate that we have not consumed the
  1935. # exception, if any.
  1936. return succeed(False)
  1937. @abstractmethod
  1938. def acquire(self: Self) -> Deferred[Self]:
  1939. pass
  1940. @abstractmethod
  1941. def release(self) -> None:
  1942. pass
  1943. class DeferredLock(_ConcurrencyPrimitive):
  1944. """
  1945. A lock for event driven systems.
  1946. @ivar locked: C{True} when this Lock has been acquired, false at all other
  1947. times. Do not change this value, but it is useful to examine for the
  1948. equivalent of a "non-blocking" acquisition.
  1949. """
  1950. locked = False
  1951. def _cancelAcquire(self: Self, d: Deferred[Self]) -> None:
  1952. """
  1953. Remove a deferred d from our waiting list, as the deferred has been
  1954. canceled.
  1955. Note: We do not need to wrap this in a try/except to catch d not
  1956. being in self.waiting because this canceller will not be called if
  1957. d has fired. release() pops a deferred out of self.waiting and
  1958. calls it, so the canceller will no longer be called.
  1959. @param d: The deferred that has been canceled.
  1960. """
  1961. self.waiting.remove(d)
  1962. def acquire(self: Self) -> Deferred[Self]:
  1963. """
  1964. Attempt to acquire the lock. Returns a L{Deferred} that fires on
  1965. lock acquisition with the L{DeferredLock} as the value. If the lock
  1966. is locked, then the Deferred is placed at the end of a waiting list.
  1967. @return: a L{Deferred} which fires on lock acquisition.
  1968. @rtype: a L{Deferred}
  1969. """
  1970. d: Deferred[Self] = Deferred(canceller=self._cancelAcquire)
  1971. if self.locked:
  1972. self.waiting.append(d)
  1973. else:
  1974. self.locked = True
  1975. d.callback(self)
  1976. return d
  1977. def release(self: Self) -> None:
  1978. """
  1979. Release the lock. If there is a waiting list, then the first
  1980. L{Deferred} in that waiting list will be called back.
  1981. Should be called by whomever did the L{acquire}() when the shared
  1982. resource is free.
  1983. """
  1984. assert self.locked, "Tried to release an unlocked lock"
  1985. self.locked = False
  1986. if self.waiting:
  1987. # someone is waiting to acquire lock
  1988. self.locked = True
  1989. d = self.waiting.pop(0)
  1990. d.callback(self)
  1991. class DeferredSemaphore(_ConcurrencyPrimitive):
  1992. """
  1993. A semaphore for event driven systems.
  1994. If you are looking into this as a means of limiting parallelism, you might
  1995. find L{twisted.internet.task.Cooperator} more useful.
  1996. @ivar limit: At most this many users may acquire this semaphore at
  1997. once.
  1998. @ivar tokens: The difference between C{limit} and the number of users
  1999. which have currently acquired this semaphore.
  2000. """
  2001. def __init__(self, tokens: int) -> None:
  2002. """
  2003. @param tokens: initial value of L{tokens} and L{limit}
  2004. @type tokens: L{int}
  2005. """
  2006. _ConcurrencyPrimitive.__init__(self)
  2007. if tokens < 1:
  2008. raise ValueError("DeferredSemaphore requires tokens >= 1")
  2009. self.tokens = tokens
  2010. self.limit = tokens
  2011. def _cancelAcquire(self: Self, d: Deferred[Self]) -> None:
  2012. """
  2013. Remove a deferred d from our waiting list, as the deferred has been
  2014. canceled.
  2015. Note: We do not need to wrap this in a try/except to catch d not
  2016. being in self.waiting because this canceller will not be called if
  2017. d has fired. release() pops a deferred out of self.waiting and
  2018. calls it, so the canceller will no longer be called.
  2019. @param d: The deferred that has been canceled.
  2020. """
  2021. self.waiting.remove(d)
  2022. def acquire(self: Self) -> Deferred[Self]:
  2023. """
  2024. Attempt to acquire the token.
  2025. @return: a L{Deferred} which fires on token acquisition.
  2026. """
  2027. assert (
  2028. self.tokens >= 0
  2029. ), "Internal inconsistency?? tokens should never be negative"
  2030. d: Deferred[Self] = Deferred(canceller=self._cancelAcquire)
  2031. if not self.tokens:
  2032. self.waiting.append(d)
  2033. else:
  2034. self.tokens = self.tokens - 1
  2035. d.callback(self)
  2036. return d
  2037. def release(self: Self) -> None:
  2038. """
  2039. Release the token.
  2040. Should be called by whoever did the L{acquire}() when the shared
  2041. resource is free.
  2042. """
  2043. assert (
  2044. self.tokens < self.limit
  2045. ), "Someone released me too many times: too many tokens!"
  2046. self.tokens = self.tokens + 1
  2047. if self.waiting:
  2048. # someone is waiting to acquire token
  2049. self.tokens = self.tokens - 1
  2050. d = self.waiting.pop(0)
  2051. d.callback(self)
  2052. class QueueOverflow(Exception):
  2053. pass
  2054. class QueueUnderflow(Exception):
  2055. pass
  2056. class DeferredQueue(Generic[_T]):
  2057. """
  2058. An event driven queue.
  2059. Objects may be added as usual to this queue. When an attempt is
  2060. made to retrieve an object when the queue is empty, a L{Deferred} is
  2061. returned which will fire when an object becomes available.
  2062. @ivar size: The maximum number of objects to allow into the queue
  2063. at a time. When an attempt to add a new object would exceed this
  2064. limit, L{QueueOverflow} is raised synchronously. L{None} for no limit.
  2065. @ivar backlog: The maximum number of L{Deferred} gets to allow at
  2066. one time. When an attempt is made to get an object which would
  2067. exceed this limit, L{QueueUnderflow} is raised synchronously. L{None}
  2068. for no limit.
  2069. """
  2070. def __init__(
  2071. self, size: Optional[int] = None, backlog: Optional[int] = None
  2072. ) -> None:
  2073. self.waiting: List[Deferred[_T]] = []
  2074. self.pending: List[_T] = []
  2075. self.size = size
  2076. self.backlog = backlog
  2077. def _cancelGet(self, d: Deferred[_T]) -> None:
  2078. """
  2079. Remove a deferred d from our waiting list, as the deferred has been
  2080. canceled.
  2081. Note: We do not need to wrap this in a try/except to catch d not
  2082. being in self.waiting because this canceller will not be called if
  2083. d has fired. put() pops a deferred out of self.waiting and calls
  2084. it, so the canceller will no longer be called.
  2085. @param d: The deferred that has been canceled.
  2086. """
  2087. self.waiting.remove(d)
  2088. def put(self, obj: _T) -> None:
  2089. """
  2090. Add an object to this queue.
  2091. @raise QueueOverflow: Too many objects are in this queue.
  2092. """
  2093. if self.waiting:
  2094. self.waiting.pop(0).callback(obj)
  2095. elif self.size is None or len(self.pending) < self.size:
  2096. self.pending.append(obj)
  2097. else:
  2098. raise QueueOverflow()
  2099. def get(self) -> Deferred[_T]:
  2100. """
  2101. Attempt to retrieve and remove an object from the queue.
  2102. @return: a L{Deferred} which fires with the next object available in
  2103. the queue.
  2104. @raise QueueUnderflow: Too many (more than C{backlog})
  2105. L{Deferred}s are already waiting for an object from this queue.
  2106. """
  2107. if self.pending:
  2108. return succeed(self.pending.pop(0))
  2109. elif self.backlog is None or len(self.waiting) < self.backlog:
  2110. d: Deferred[_T] = Deferred(canceller=self._cancelGet)
  2111. self.waiting.append(d)
  2112. return d
  2113. else:
  2114. raise QueueUnderflow()
  2115. class AlreadyTryingToLockError(Exception):
  2116. """
  2117. Raised when L{DeferredFilesystemLock.deferUntilLocked} is called twice on a
  2118. single L{DeferredFilesystemLock}.
  2119. """
  2120. class DeferredFilesystemLock(lockfile.FilesystemLock):
  2121. """
  2122. A L{FilesystemLock} that allows for a L{Deferred} to be fired when the lock is
  2123. acquired.
  2124. @ivar _scheduler: The object in charge of scheduling retries. In this
  2125. implementation this is parameterized for testing.
  2126. @ivar _interval: The retry interval for an L{IReactorTime} based scheduler.
  2127. @ivar _tryLockCall: An L{IDelayedCall} based on C{_interval} that will manage
  2128. the next retry for acquiring the lock.
  2129. @ivar _timeoutCall: An L{IDelayedCall} based on C{deferUntilLocked}'s timeout
  2130. argument. This is in charge of timing out our attempt to acquire the
  2131. lock.
  2132. """
  2133. _interval = 1
  2134. _tryLockCall: Optional[IDelayedCall] = None
  2135. _timeoutCall: Optional[IDelayedCall] = None
  2136. def __init__(self, name: str, scheduler: Optional[IReactorTime] = None) -> None:
  2137. """
  2138. @param name: The name of the lock to acquire
  2139. @param scheduler: An object which provides L{IReactorTime}
  2140. """
  2141. lockfile.FilesystemLock.__init__(self, name)
  2142. if scheduler is None:
  2143. from twisted.internet import reactor
  2144. scheduler = cast(IReactorTime, reactor)
  2145. self._scheduler = scheduler
  2146. def deferUntilLocked(self, timeout: Optional[float] = None) -> Deferred[None]:
  2147. """
  2148. Wait until we acquire this lock. This method is not safe for
  2149. concurrent use.
  2150. @param timeout: the number of seconds after which to time out if the
  2151. lock has not been acquired.
  2152. @return: a L{Deferred} which will callback when the lock is acquired, or
  2153. errback with a L{TimeoutError} after timing out or an
  2154. L{AlreadyTryingToLockError} if the L{deferUntilLocked} has already
  2155. been called and not successfully locked the file.
  2156. """
  2157. if self._tryLockCall is not None:
  2158. return fail(
  2159. AlreadyTryingToLockError(
  2160. "deferUntilLocked isn't safe for concurrent use."
  2161. )
  2162. )
  2163. def _cancelLock(reason: Union[Failure, Exception]) -> None:
  2164. """
  2165. Cancel a L{DeferredFilesystemLock.deferUntilLocked} call.
  2166. @type reason: L{Failure}
  2167. @param reason: The reason why the call is cancelled.
  2168. """
  2169. assert self._tryLockCall is not None
  2170. self._tryLockCall.cancel()
  2171. self._tryLockCall = None
  2172. if self._timeoutCall is not None and self._timeoutCall.active():
  2173. self._timeoutCall.cancel()
  2174. self._timeoutCall = None
  2175. if self.lock():
  2176. d.callback(None)
  2177. else:
  2178. d.errback(reason)
  2179. d: Deferred[None] = Deferred(lambda deferred: _cancelLock(CancelledError()))
  2180. def _tryLock() -> None:
  2181. if self.lock():
  2182. if self._timeoutCall is not None:
  2183. self._timeoutCall.cancel()
  2184. self._timeoutCall = None
  2185. self._tryLockCall = None
  2186. d.callback(None)
  2187. else:
  2188. if timeout is not None and self._timeoutCall is None:
  2189. reason = Failure(
  2190. TimeoutError(
  2191. "Timed out acquiring lock: %s after %fs"
  2192. % (self.name, timeout)
  2193. )
  2194. )
  2195. self._timeoutCall = self._scheduler.callLater(
  2196. timeout, _cancelLock, reason
  2197. )
  2198. self._tryLockCall = self._scheduler.callLater(self._interval, _tryLock)
  2199. _tryLock()
  2200. return d
  2201. __all__ = [
  2202. "Deferred",
  2203. "DeferredList",
  2204. "succeed",
  2205. "fail",
  2206. "FAILURE",
  2207. "SUCCESS",
  2208. "AlreadyCalledError",
  2209. "TimeoutError",
  2210. "gatherResults",
  2211. "maybeDeferred",
  2212. "ensureDeferred",
  2213. "waitForDeferred",
  2214. "deferredGenerator",
  2215. "inlineCallbacks",
  2216. "returnValue",
  2217. "DeferredLock",
  2218. "DeferredSemaphore",
  2219. "DeferredQueue",
  2220. "DeferredFilesystemLock",
  2221. "AlreadyTryingToLockError",
  2222. "CancelledError",
  2223. ]