defer.py 70 KB

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