defer.py 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923
  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 traceback
  16. import types
  17. import warnings
  18. from sys import exc_info, version_info
  19. from functools import wraps
  20. from incremental import Version
  21. # Twisted imports
  22. from twisted.python.compat import cmp, comparable
  23. from twisted.python import lockfile, failure
  24. from twisted.logger import Logger
  25. from twisted.python.deprecate import warnAboutFunction, deprecated
  26. from twisted.python._oldstyle import _oldStyle
  27. log = Logger()
  28. class AlreadyCalledError(Exception):
  29. pass
  30. class CancelledError(Exception):
  31. """
  32. This error is raised by default when a L{Deferred} is cancelled.
  33. """
  34. class TimeoutError(Exception):
  35. """
  36. This error is raised by default when a L{Deferred} times out.
  37. """
  38. def logError(err):
  39. """
  40. Log and return failure.
  41. This method can be used as an errback that passes the failure on to the
  42. next errback unmodified. Note that if this is the last errback, and the
  43. deferred gets garbage collected after being this errback has been called,
  44. the clean up code logs it again.
  45. """
  46. log.failure(None, err)
  47. return err
  48. def succeed(result):
  49. """
  50. Return a L{Deferred} that has already had C{.callback(result)} called.
  51. This is useful when you're writing synchronous code to an
  52. asynchronous interface: i.e., some code is calling you expecting a
  53. L{Deferred} result, but you don't actually need to do anything
  54. asynchronous. Just return C{defer.succeed(theResult)}.
  55. See L{fail} for a version of this function that uses a failing
  56. L{Deferred} rather than a successful one.
  57. @param result: The result to give to the Deferred's 'callback'
  58. method.
  59. @rtype: L{Deferred}
  60. """
  61. d = Deferred()
  62. d.callback(result)
  63. return d
  64. def fail(result=None):
  65. """
  66. Return a L{Deferred} that has already had C{.errback(result)} called.
  67. See L{succeed}'s docstring for rationale.
  68. @param result: The same argument that L{Deferred.errback} takes.
  69. @raise NoCurrentExceptionError: If C{result} is L{None} but there is no
  70. current exception state.
  71. @rtype: L{Deferred}
  72. """
  73. d = Deferred()
  74. d.errback(result)
  75. return d
  76. def execute(callable, *args, **kw):
  77. """
  78. Create a L{Deferred} from a callable and arguments.
  79. Call the given function with the given arguments. Return a L{Deferred}
  80. which has been fired with its callback as the result of that invocation
  81. or its C{errback} with a L{Failure} for the exception thrown.
  82. """
  83. try:
  84. result = callable(*args, **kw)
  85. except:
  86. return fail()
  87. else:
  88. return succeed(result)
  89. def maybeDeferred(f, *args, **kw):
  90. """
  91. Invoke a function that may or may not return a L{Deferred}.
  92. Call the given function with the given arguments. If the returned
  93. object is a L{Deferred}, return it. If the returned object is a L{Failure},
  94. wrap it with L{fail} and return it. Otherwise, wrap it in L{succeed} and
  95. return it. If an exception is raised, convert it to a L{Failure}, wrap it
  96. in L{fail}, and then return it.
  97. @type f: Any callable
  98. @param f: The callable to invoke
  99. @param args: The arguments to pass to C{f}
  100. @param kw: The keyword arguments to pass to C{f}
  101. @rtype: L{Deferred}
  102. @return: The result of the function call, wrapped in a L{Deferred} if
  103. necessary.
  104. """
  105. try:
  106. result = f(*args, **kw)
  107. except:
  108. return fail(failure.Failure(captureVars=Deferred.debug))
  109. if isinstance(result, Deferred):
  110. return result
  111. elif isinstance(result, failure.Failure):
  112. return fail(result)
  113. else:
  114. return succeed(result)
  115. @deprecated(Version('Twisted', 17, 1, 0),
  116. replacement='twisted.internet.defer.Deferred.addTimeout')
  117. def timeout(deferred):
  118. deferred.errback(failure.Failure(TimeoutError("Callback timed out")))
  119. def passthru(arg):
  120. return arg
  121. def setDebugging(on):
  122. """
  123. Enable or disable L{Deferred} debugging.
  124. When debugging is on, the call stacks from creation and invocation are
  125. recorded, and added to any L{AlreadyCalledError}s we raise.
  126. """
  127. Deferred.debug=bool(on)
  128. def getDebugging():
  129. """
  130. Determine whether L{Deferred} debugging is enabled.
  131. """
  132. return Deferred.debug
  133. # See module docstring.
  134. _NO_RESULT = object()
  135. _CONTINUE = object()
  136. @_oldStyle
  137. class Deferred:
  138. """
  139. This is a callback which will be put off until later.
  140. Why do we want this? Well, in cases where a function in a threaded
  141. program would block until it gets a result, for Twisted it should
  142. not block. Instead, it should return a L{Deferred}.
  143. This can be implemented for protocols that run over the network by
  144. writing an asynchronous protocol for L{twisted.internet}. For methods
  145. that come from outside packages that are not under our control, we use
  146. threads (see for example L{twisted.enterprise.adbapi}).
  147. For more information about Deferreds, see doc/core/howto/defer.html or
  148. U{http://twistedmatrix.com/documents/current/core/howto/defer.html}
  149. When creating a Deferred, you may provide a canceller function, which
  150. will be called by d.cancel() to let you do any clean-up necessary if the
  151. user decides not to wait for the deferred to complete.
  152. @ivar called: A flag which is C{False} until either C{callback} or
  153. C{errback} is called and afterwards always C{True}.
  154. @type called: L{bool}
  155. @ivar paused: A counter of how many unmatched C{pause} calls have been made
  156. on this instance.
  157. @type paused: L{int}
  158. @ivar _suppressAlreadyCalled: A flag used by the cancellation mechanism
  159. which is C{True} if the Deferred has no canceller and has been
  160. cancelled, C{False} otherwise. If C{True}, it can be expected that
  161. C{callback} or C{errback} will eventually be called and the result
  162. should be silently discarded.
  163. @type _suppressAlreadyCalled: L{bool}
  164. @ivar _runningCallbacks: A flag which is C{True} while this instance is
  165. executing its callback chain, used to stop recursive execution of
  166. L{_runCallbacks}
  167. @type _runningCallbacks: L{bool}
  168. @ivar _chainedTo: If this L{Deferred} is waiting for the result of another
  169. L{Deferred}, this is a reference to the other Deferred. Otherwise,
  170. L{None}.
  171. """
  172. called = False
  173. paused = False
  174. _debugInfo = None
  175. _suppressAlreadyCalled = False
  176. # Are we currently running a user-installed callback? Meant to prevent
  177. # recursive running of callbacks when a reentrant call to add a callback is
  178. # used.
  179. _runningCallbacks = False
  180. # Keep this class attribute for now, for compatibility with code that
  181. # sets it directly.
  182. debug = False
  183. _chainedTo = None
  184. def __init__(self, canceller=None):
  185. """
  186. Initialize a L{Deferred}.
  187. @param canceller: a callable used to stop the pending operation
  188. scheduled by this L{Deferred} when L{Deferred.cancel} is
  189. invoked. The canceller will be passed the deferred whose
  190. cancelation is requested (i.e., self).
  191. If a canceller is not given, or does not invoke its argument's
  192. C{callback} or C{errback} method, L{Deferred.cancel} will
  193. invoke L{Deferred.errback} with a L{CancelledError}.
  194. Note that if a canceller is not given, C{callback} or
  195. C{errback} may still be invoked exactly once, even though
  196. defer.py will have already invoked C{errback}, as described
  197. above. This allows clients of code which returns a L{Deferred}
  198. to cancel it without requiring the L{Deferred} instantiator to
  199. provide any specific implementation support for cancellation.
  200. New in 10.1.
  201. @type canceller: a 1-argument callable which takes a L{Deferred}. The
  202. return result is ignored.
  203. """
  204. self.callbacks = []
  205. self._canceller = canceller
  206. if self.debug:
  207. self._debugInfo = DebugInfo()
  208. self._debugInfo.creator = traceback.format_stack()[:-1]
  209. def addCallbacks(self, callback, errback=None,
  210. callbackArgs=None, callbackKeywords=None,
  211. errbackArgs=None, errbackKeywords=None):
  212. """
  213. Add a pair of callbacks (success and error) to this L{Deferred}.
  214. These will be executed when the 'master' callback is run.
  215. @return: C{self}.
  216. @rtype: a L{Deferred}
  217. """
  218. assert callable(callback)
  219. assert errback is None or callable(errback)
  220. cbs = ((callback, callbackArgs, callbackKeywords),
  221. (errback or (passthru), errbackArgs, errbackKeywords))
  222. self.callbacks.append(cbs)
  223. if self.called:
  224. self._runCallbacks()
  225. return self
  226. def addCallback(self, callback, *args, **kw):
  227. """
  228. Convenience method for adding just a callback.
  229. See L{addCallbacks}.
  230. """
  231. return self.addCallbacks(callback, callbackArgs=args,
  232. callbackKeywords=kw)
  233. def addErrback(self, errback, *args, **kw):
  234. """
  235. Convenience method for adding just an errback.
  236. See L{addCallbacks}.
  237. """
  238. return self.addCallbacks(passthru, errback,
  239. errbackArgs=args,
  240. errbackKeywords=kw)
  241. def addBoth(self, callback, *args, **kw):
  242. """
  243. Convenience method for adding a single callable as both a callback
  244. and an errback.
  245. See L{addCallbacks}.
  246. """
  247. return self.addCallbacks(callback, callback,
  248. callbackArgs=args, errbackArgs=args,
  249. callbackKeywords=kw, errbackKeywords=kw)
  250. def addTimeout(self, timeout, clock, onTimeoutCancel=None):
  251. """
  252. Time out this L{Deferred} by scheduling it to be cancelled after
  253. C{timeout} seconds.
  254. The timeout encompasses all the callbacks and errbacks added to this
  255. L{defer.Deferred} before the call to L{addTimeout}, and none added
  256. after the call.
  257. If this L{Deferred} gets timed out, it errbacks with a L{TimeoutError},
  258. unless a cancelable function was passed to its initialization or unless
  259. a different C{onTimeoutCancel} callable is provided.
  260. @param timeout: number of seconds to wait before timing out this
  261. L{Deferred}
  262. @type timeout: L{int}
  263. @param clock: The object which will be used to schedule the timeout.
  264. @type clock: L{twisted.internet.interfaces.IReactorTime}
  265. @param onTimeoutCancel: A callable which is called immediately after
  266. this L{Deferred} times out, and not if this L{Deferred} is
  267. otherwise cancelled before the timeout. It takes an arbitrary
  268. value, which is the value of this L{Deferred} at that exact point
  269. in time (probably a L{CancelledError} L{Failure}), and the
  270. C{timeout}. The default callable (if none is provided) will
  271. translate a L{CancelledError} L{Failure} into a L{TimeoutError}.
  272. @type onTimeoutCancel: L{callable}
  273. @return: C{self}.
  274. @rtype: a L{Deferred}
  275. @since: 16.5
  276. """
  277. timedOut = [False]
  278. def timeItOut():
  279. timedOut[0] = True
  280. self.cancel()
  281. delayedCall = clock.callLater(timeout, timeItOut)
  282. def convertCancelled(value):
  283. # if C{deferred} was timed out, call the translation function,
  284. # if provdied, otherwise just use L{cancelledToTimedOutError}
  285. if timedOut[0]:
  286. toCall = onTimeoutCancel or _cancelledToTimedOutError
  287. return toCall(value, timeout)
  288. return value
  289. self.addBoth(convertCancelled)
  290. def cancelTimeout(result):
  291. # stop the pending call to cancel the deferred if it's been fired
  292. if delayedCall.active():
  293. delayedCall.cancel()
  294. return result
  295. self.addBoth(cancelTimeout)
  296. return self
  297. def chainDeferred(self, d):
  298. """
  299. Chain another L{Deferred} to this L{Deferred}.
  300. This method adds callbacks to this L{Deferred} to call C{d}'s callback
  301. or errback, as appropriate. It is merely a shorthand way of performing
  302. the following::
  303. self.addCallbacks(d.callback, d.errback)
  304. When you chain a deferred d2 to another deferred d1 with
  305. d1.chainDeferred(d2), you are making d2 participate in the callback
  306. chain of d1. Thus any event that fires d1 will also fire d2.
  307. However, the converse is B{not} true; if d2 is fired d1 will not be
  308. affected.
  309. Note that unlike the case where chaining is caused by a L{Deferred}
  310. being returned from a callback, it is possible to cause the call
  311. stack size limit to be exceeded by chaining many L{Deferred}s
  312. together with C{chainDeferred}.
  313. @return: C{self}.
  314. @rtype: a L{Deferred}
  315. """
  316. d._chainedTo = self
  317. return self.addCallbacks(d.callback, d.errback)
  318. def callback(self, result):
  319. """
  320. Run all success callbacks that have been added to this L{Deferred}.
  321. Each callback will have its result passed as the first argument to
  322. the next; this way, the callbacks act as a 'processing chain'. If
  323. the success-callback returns a L{Failure} or raises an L{Exception},
  324. processing will continue on the *error* callback chain. If a
  325. callback (or errback) returns another L{Deferred}, this L{Deferred}
  326. will be chained to it (and further callbacks will not run until that
  327. L{Deferred} has a result).
  328. An instance of L{Deferred} may only have either L{callback} or
  329. L{errback} called on it, and only once.
  330. @param result: The object which will be passed to the first callback
  331. added to this L{Deferred} (via L{addCallback}).
  332. @raise AlreadyCalledError: If L{callback} or L{errback} has already been
  333. called on this L{Deferred}.
  334. """
  335. assert not isinstance(result, Deferred)
  336. self._startRunCallbacks(result)
  337. def errback(self, fail=None):
  338. """
  339. Run all error callbacks that have been added to this L{Deferred}.
  340. Each callback will have its result passed as the first
  341. argument to the next; this way, the callbacks act as a
  342. 'processing chain'. Also, if the error-callback returns a non-Failure
  343. or doesn't raise an L{Exception}, processing will continue on the
  344. *success*-callback chain.
  345. If the argument that's passed to me is not a L{failure.Failure} instance,
  346. it will be embedded in one. If no argument is passed, a
  347. L{failure.Failure} instance will be created based on the current
  348. traceback stack.
  349. Passing a string as `fail' is deprecated, and will be punished with
  350. a warning message.
  351. An instance of L{Deferred} may only have either L{callback} or
  352. L{errback} called on it, and only once.
  353. @param fail: The L{Failure} object which will be passed to the first
  354. errback added to this L{Deferred} (via L{addErrback}).
  355. Alternatively, a L{Exception} instance from which a L{Failure} will
  356. be constructed (with no traceback) or L{None} to create a L{Failure}
  357. instance from the current exception state (with a traceback).
  358. @raise AlreadyCalledError: If L{callback} or L{errback} has already been
  359. called on this L{Deferred}.
  360. @raise NoCurrentExceptionError: If C{fail} is L{None} but there is
  361. no current exception state.
  362. """
  363. if fail is None:
  364. fail = failure.Failure(captureVars=self.debug)
  365. elif not isinstance(fail, failure.Failure):
  366. fail = failure.Failure(fail)
  367. self._startRunCallbacks(fail)
  368. def pause(self):
  369. """
  370. Stop processing on a L{Deferred} until L{unpause}() is called.
  371. """
  372. self.paused = self.paused + 1
  373. def unpause(self):
  374. """
  375. Process all callbacks made since L{pause}() was called.
  376. """
  377. self.paused = self.paused - 1
  378. if self.paused:
  379. return
  380. if self.called:
  381. self._runCallbacks()
  382. def cancel(self):
  383. """
  384. Cancel this L{Deferred}.
  385. If the L{Deferred} has not yet had its C{errback} or C{callback} method
  386. invoked, call the canceller function provided to the constructor. If
  387. that function does not invoke C{callback} or C{errback}, or if no
  388. canceller function was provided, errback with L{CancelledError}.
  389. If this L{Deferred} is waiting on another L{Deferred}, forward the
  390. cancellation to the other L{Deferred}.
  391. """
  392. if not self.called:
  393. canceller = self._canceller
  394. if canceller:
  395. canceller(self)
  396. else:
  397. # Arrange to eat the callback that will eventually be fired
  398. # since there was no real canceller.
  399. self._suppressAlreadyCalled = True
  400. if not self.called:
  401. # There was no canceller, or the canceller didn't call
  402. # callback or errback.
  403. self.errback(failure.Failure(CancelledError()))
  404. elif isinstance(self.result, Deferred):
  405. # Waiting for another deferred -- cancel it instead.
  406. self.result.cancel()
  407. def _startRunCallbacks(self, result):
  408. if self.called:
  409. if self._suppressAlreadyCalled:
  410. self._suppressAlreadyCalled = False
  411. return
  412. if self.debug:
  413. if self._debugInfo is None:
  414. self._debugInfo = DebugInfo()
  415. extra = "\n" + self._debugInfo._getDebugTracebacks()
  416. raise AlreadyCalledError(extra)
  417. raise AlreadyCalledError
  418. if self.debug:
  419. if self._debugInfo is None:
  420. self._debugInfo = DebugInfo()
  421. self._debugInfo.invoker = traceback.format_stack()[:-2]
  422. self.called = True
  423. self.result = result
  424. self._runCallbacks()
  425. def _continuation(self):
  426. """
  427. Build a tuple of callback and errback with L{_CONTINUE}.
  428. """
  429. return ((_CONTINUE, (self,), None),
  430. (_CONTINUE, (self,), None))
  431. def _runCallbacks(self):
  432. """
  433. Run the chain of callbacks once a result is available.
  434. This consists of a simple loop over all of the callbacks, calling each
  435. with the current result and making the current result equal to the
  436. return value (or raised exception) of that call.
  437. If L{_runningCallbacks} is true, this loop won't run at all, since
  438. it is already running above us on the call stack. If C{self.paused} is
  439. true, the loop also won't run, because that's what it means to be
  440. paused.
  441. The loop will terminate before processing all of the callbacks if a
  442. L{Deferred} without a result is encountered.
  443. If a L{Deferred} I{with} a result is encountered, that result is taken
  444. and the loop proceeds.
  445. @note: The implementation is complicated slightly by the fact that
  446. chaining (associating two L{Deferred}s with each other such that one
  447. will wait for the result of the other, as happens when a Deferred is
  448. returned from a callback on another L{Deferred}) is supported
  449. iteratively rather than recursively, to avoid running out of stack
  450. frames when processing long chains.
  451. """
  452. if self._runningCallbacks:
  453. # Don't recursively run callbacks
  454. return
  455. # Keep track of all the Deferreds encountered while propagating results
  456. # up a chain. The way a Deferred gets onto this stack is by having
  457. # added its _continuation() to the callbacks list of a second Deferred
  458. # and then that second Deferred being fired. ie, if ever had _chainedTo
  459. # set to something other than None, you might end up on this stack.
  460. chain = [self]
  461. while chain:
  462. current = chain[-1]
  463. if current.paused:
  464. # This Deferred isn't going to produce a result at all. All the
  465. # Deferreds up the chain waiting on it will just have to...
  466. # wait.
  467. return
  468. finished = True
  469. current._chainedTo = None
  470. while current.callbacks:
  471. item = current.callbacks.pop(0)
  472. callback, args, kw = item[
  473. isinstance(current.result, failure.Failure)]
  474. args = args or ()
  475. kw = kw or {}
  476. # Avoid recursion if we can.
  477. if callback is _CONTINUE:
  478. # Give the waiting Deferred our current result and then
  479. # forget about that result ourselves.
  480. chainee = args[0]
  481. chainee.result = current.result
  482. current.result = None
  483. # Making sure to update _debugInfo
  484. if current._debugInfo is not None:
  485. current._debugInfo.failResult = None
  486. chainee.paused -= 1
  487. chain.append(chainee)
  488. # Delay cleaning this Deferred and popping it from the chain
  489. # until after we've dealt with chainee.
  490. finished = False
  491. break
  492. try:
  493. current._runningCallbacks = True
  494. try:
  495. current.result = callback(current.result, *args, **kw)
  496. if current.result is current:
  497. warnAboutFunction(
  498. callback,
  499. "Callback returned the Deferred "
  500. "it was attached to; this breaks the "
  501. "callback chain and will raise an "
  502. "exception in the future.")
  503. finally:
  504. current._runningCallbacks = False
  505. except:
  506. # Including full frame information in the Failure is quite
  507. # expensive, so we avoid it unless self.debug is set.
  508. current.result = failure.Failure(captureVars=self.debug)
  509. else:
  510. if isinstance(current.result, Deferred):
  511. # The result is another Deferred. If it has a result,
  512. # we can take it and keep going.
  513. resultResult = getattr(current.result, 'result', _NO_RESULT)
  514. if resultResult is _NO_RESULT or isinstance(resultResult, Deferred) or current.result.paused:
  515. # Nope, it didn't. Pause and chain.
  516. current.pause()
  517. current._chainedTo = current.result
  518. # Note: current.result has no result, so it's not
  519. # running its callbacks right now. Therefore we can
  520. # append to the callbacks list directly instead of
  521. # using addCallbacks.
  522. current.result.callbacks.append(current._continuation())
  523. break
  524. else:
  525. # Yep, it did. Steal it.
  526. current.result.result = None
  527. # Make sure _debugInfo's failure state is updated.
  528. if current.result._debugInfo is not None:
  529. current.result._debugInfo.failResult = None
  530. current.result = resultResult
  531. if finished:
  532. # As much of the callback chain - perhaps all of it - as can be
  533. # processed right now has been. The current Deferred is waiting on
  534. # another Deferred or for more callbacks. Before finishing with it,
  535. # make sure its _debugInfo is in the proper state.
  536. if isinstance(current.result, failure.Failure):
  537. # Stash the Failure in the _debugInfo for unhandled error
  538. # reporting.
  539. current.result.cleanFailure()
  540. if current._debugInfo is None:
  541. current._debugInfo = DebugInfo()
  542. current._debugInfo.failResult = current.result
  543. else:
  544. # Clear out any Failure in the _debugInfo, since the result
  545. # is no longer a Failure.
  546. if current._debugInfo is not None:
  547. current._debugInfo.failResult = None
  548. # This Deferred is done, pop it from the chain and move back up
  549. # to the Deferred which supplied us with our result.
  550. chain.pop()
  551. def __str__(self):
  552. """
  553. Return a string representation of this C{Deferred}.
  554. """
  555. cname = self.__class__.__name__
  556. result = getattr(self, 'result', _NO_RESULT)
  557. myID = id(self)
  558. if self._chainedTo is not None:
  559. result = ' waiting on Deferred at 0x%x' % (id(self._chainedTo),)
  560. elif result is _NO_RESULT:
  561. result = ''
  562. else:
  563. result = ' current result: %r' % (result,)
  564. return "<%s at 0x%x%s>" % (cname, myID, result)
  565. __repr__ = __str__
  566. def __iter__(self):
  567. return self
  568. def send(self, value=None):
  569. if self.paused:
  570. # If we're paused, we have no result to give
  571. return self
  572. result = getattr(self, 'result', _NO_RESULT)
  573. if result is _NO_RESULT:
  574. return self
  575. if isinstance(result, failure.Failure):
  576. # Clear the failure on debugInfo so it doesn't raise "unhandled
  577. # exception"
  578. self._debugInfo.failResult = None
  579. raise result.value
  580. else:
  581. raise StopIteration(result)
  582. # For PEP-492 support (async/await)
  583. __await__ = __iter__
  584. __next__ = send
  585. def asFuture(self, loop):
  586. """
  587. Adapt a L{Deferred} into a L{asyncio.Future} which is bound to C{loop}.
  588. @note: converting a L{Deferred} to an L{asyncio.Future} consumes both
  589. its result and its errors, so this method implicitly converts
  590. C{self} into a L{Deferred} firing with L{None}, regardless of what
  591. its result previously would have been.
  592. @since: Twisted 17.5.0
  593. @param loop: The asyncio event loop to bind the L{asyncio.Future} to.
  594. @type loop: L{asyncio.AbstractEventLoop} or similar
  595. @param deferred: The Deferred to adapt.
  596. @type deferred: L{Deferred}
  597. @return: A Future which will fire when the Deferred fires.
  598. @rtype: L{asyncio.Future}
  599. """
  600. try:
  601. createFuture = loop.create_future
  602. except AttributeError:
  603. from asyncio import Future
  604. def createFuture():
  605. return Future(loop=loop)
  606. future = createFuture()
  607. def checkCancel(futureAgain):
  608. if futureAgain.cancelled():
  609. self.cancel()
  610. def maybeFail(failure):
  611. if not future.cancelled():
  612. future.set_exception(failure.value)
  613. def maybeSucceed(result):
  614. if not future.cancelled():
  615. future.set_result(result)
  616. self.addCallbacks(maybeSucceed, maybeFail)
  617. future.add_done_callback(checkCancel)
  618. return future
  619. @classmethod
  620. def fromFuture(cls, future):
  621. """
  622. Adapt an L{asyncio.Future} to a L{Deferred}.
  623. @note: This creates a L{Deferred} from a L{asyncio.Future}, I{not} from
  624. a C{coroutine}; in other words, you will need to call
  625. L{asyncio.async}, L{asyncio.ensure_future},
  626. L{asyncio.AbstractEventLoop.create_task} or create an
  627. L{asyncio.Task} yourself to get from a C{coroutine} to a
  628. L{asyncio.Future} if what you have is an awaitable coroutine and
  629. not a L{asyncio.Future}. (The length of this list of techniques is
  630. exactly why we have left it to the caller!)
  631. @since: Twisted 17.5.0
  632. @param future: The Future to adapt.
  633. @type future: L{asyncio.Future}
  634. @return: A Deferred which will fire when the Future fires.
  635. @rtype: L{Deferred}
  636. """
  637. def adapt(result):
  638. try:
  639. extracted = result.result()
  640. except:
  641. extracted = failure.Failure()
  642. adapt.actual.callback(extracted)
  643. futureCancel = object()
  644. def cancel(reself):
  645. future.cancel()
  646. reself.callback(futureCancel)
  647. self = cls(cancel)
  648. adapt.actual = self
  649. def uncancel(result):
  650. if result is futureCancel:
  651. adapt.actual = Deferred()
  652. return adapt.actual
  653. return result
  654. self.addCallback(uncancel)
  655. future.add_done_callback(adapt)
  656. return self
  657. def _cancelledToTimedOutError(value, timeout):
  658. """
  659. A default translation function that translates L{Failure}s that are
  660. L{CancelledError}s to L{TimeoutError}s.
  661. @param value: Anything
  662. @type value: Anything
  663. @param timeout: The timeout
  664. @type timeout: L{int}
  665. @rtype: C{value}
  666. @raise: L{TimeoutError}
  667. @since: 16.5
  668. """
  669. if isinstance(value, failure.Failure):
  670. value.trap(CancelledError)
  671. raise TimeoutError(timeout, "Deferred")
  672. return value
  673. def ensureDeferred(coro):
  674. """
  675. Schedule the execution of a coroutine that awaits/yields from L{Deferred}s,
  676. wrapping it in a L{Deferred} that will fire on success/failure of the
  677. coroutine. If a Deferred is passed to this function, it will be returned
  678. directly (mimicing C{asyncio}'s C{ensure_future} function).
  679. Coroutine functions return a coroutine object, similar to how generators
  680. work. This function turns that coroutine into a Deferred, meaning that it
  681. can be used in regular Twisted code. For example::
  682. import treq
  683. from twisted.internet.defer import ensureDeferred
  684. from twisted.internet.task import react
  685. async def crawl(pages):
  686. results = {}
  687. for page in pages:
  688. results[page] = await treq.content(await treq.get(page))
  689. return results
  690. def main(reactor):
  691. pages = [
  692. "http://localhost:8080"
  693. ]
  694. d = ensureDeferred(crawl(pages))
  695. d.addCallback(print)
  696. return d
  697. react(main)
  698. @param coro: The coroutine object to schedule, or a L{Deferred}.
  699. @type coro: A Python 3.5+ C{async def} C{coroutine}, a Python 3.3+
  700. C{yield from} using L{types.GeneratorType}, or a L{Deferred}.
  701. @rtype: L{Deferred}
  702. """
  703. from types import GeneratorType
  704. if version_info >= (3, 4, 0):
  705. from asyncio import iscoroutine
  706. if iscoroutine(coro) or isinstance(coro, GeneratorType):
  707. return _inlineCallbacks(None, coro, Deferred())
  708. elif version_info >= (3, 3, 0):
  709. if isinstance(coro, GeneratorType):
  710. return _inlineCallbacks(None, coro, Deferred())
  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. def _inlineCallbacks(result, g, deferred):
  1062. """
  1063. See L{inlineCallbacks}.
  1064. """
  1065. # This function is complicated by the need to prevent unbounded recursion
  1066. # arising from repeatedly yielding immediately ready deferreds. This while
  1067. # loop and the waiting variable solve that by manually unfolding the
  1068. # recursion.
  1069. waiting = [True, # waiting for result?
  1070. None] # result
  1071. while 1:
  1072. try:
  1073. # Send the last result back as the result of the yield expression.
  1074. isFailure = isinstance(result, failure.Failure)
  1075. if isFailure:
  1076. result = result.throwExceptionIntoGenerator(g)
  1077. else:
  1078. result = g.send(result)
  1079. except StopIteration as e:
  1080. # fell off the end, or "return" statement
  1081. deferred.callback(getattr(e, "value", None))
  1082. return deferred
  1083. except _DefGen_Return as e:
  1084. # returnValue() was called; time to give a result to the original
  1085. # Deferred. First though, let's try to identify the potentially
  1086. # confusing situation which results when returnValue() is
  1087. # accidentally invoked from a different function, one that wasn't
  1088. # decorated with @inlineCallbacks.
  1089. # The traceback starts in this frame (the one for
  1090. # _inlineCallbacks); the next one down should be the application
  1091. # code.
  1092. appCodeTrace = exc_info()[2].tb_next
  1093. if isFailure:
  1094. # If we invoked this generator frame by throwing an exception
  1095. # into it, then throwExceptionIntoGenerator will consume an
  1096. # additional stack frame itself, so we need to skip that too.
  1097. appCodeTrace = appCodeTrace.tb_next
  1098. # Now that we've identified the frame being exited by the
  1099. # exception, let's figure out if returnValue was called from it
  1100. # directly. returnValue itself consumes a stack frame, so the
  1101. # application code will have a tb_next, but it will *not* have a
  1102. # second tb_next.
  1103. if appCodeTrace.tb_next.tb_next:
  1104. # If returnValue was invoked non-local to the frame which it is
  1105. # exiting, identify the frame that ultimately invoked
  1106. # returnValue so that we can warn the user, as this behavior is
  1107. # confusing.
  1108. ultimateTrace = appCodeTrace
  1109. while ultimateTrace.tb_next.tb_next:
  1110. ultimateTrace = ultimateTrace.tb_next
  1111. filename = ultimateTrace.tb_frame.f_code.co_filename
  1112. lineno = ultimateTrace.tb_lineno
  1113. warnings.warn_explicit(
  1114. "returnValue() in %r causing %r to exit: "
  1115. "returnValue should only be invoked by functions decorated "
  1116. "with inlineCallbacks" % (
  1117. ultimateTrace.tb_frame.f_code.co_name,
  1118. appCodeTrace.tb_frame.f_code.co_name),
  1119. DeprecationWarning, filename, lineno)
  1120. deferred.callback(e.value)
  1121. return deferred
  1122. except:
  1123. deferred.errback()
  1124. return deferred
  1125. if isinstance(result, Deferred):
  1126. # a deferred was yielded, get the result.
  1127. def gotResult(r):
  1128. if waiting[0]:
  1129. waiting[0] = False
  1130. waiting[1] = r
  1131. else:
  1132. _inlineCallbacks(r, g, deferred)
  1133. result.addBoth(gotResult)
  1134. if waiting[0]:
  1135. # Haven't called back yet, set flag so that we get reinvoked
  1136. # and return from the loop
  1137. waiting[0] = False
  1138. return deferred
  1139. result = waiting[1]
  1140. # Reset waiting to initial values for next loop. gotResult uses
  1141. # waiting, but this isn't a problem because gotResult is only
  1142. # executed once, and if it hasn't been executed yet, the return
  1143. # branch above would have been taken.
  1144. waiting[0] = True
  1145. waiting[1] = None
  1146. return deferred
  1147. def inlineCallbacks(f):
  1148. """
  1149. inlineCallbacks helps you write L{Deferred}-using code that looks like a
  1150. regular sequential function. For example::
  1151. @inlineCallbacks
  1152. def thingummy():
  1153. thing = yield makeSomeRequestResultingInDeferred()
  1154. print(thing) # the result! hoorj!
  1155. When you call anything that results in a L{Deferred}, you can simply yield it;
  1156. your generator will automatically be resumed when the Deferred's result is
  1157. available. The generator will be sent the result of the L{Deferred} with the
  1158. 'send' method on generators, or if the result was a failure, 'throw'.
  1159. Things that are not L{Deferred}s may also be yielded, and your generator
  1160. will be resumed with the same object sent back. This means C{yield}
  1161. performs an operation roughly equivalent to L{maybeDeferred}.
  1162. Your inlineCallbacks-enabled generator will return a L{Deferred} object, which
  1163. will result in the return value of the generator (or will fail with a
  1164. failure object if your generator raises an unhandled exception). Note that
  1165. you can't use C{return result} to return a value; use C{returnValue(result)}
  1166. instead. Falling off the end of the generator, or simply using C{return}
  1167. will cause the L{Deferred} to have a result of L{None}.
  1168. Be aware that L{returnValue} will not accept a L{Deferred} as a parameter.
  1169. If you believe the thing you'd like to return could be a L{Deferred}, do
  1170. this::
  1171. result = yield result
  1172. returnValue(result)
  1173. The L{Deferred} returned from your deferred generator may errback if your
  1174. generator raised an exception::
  1175. @inlineCallbacks
  1176. def thingummy():
  1177. thing = yield makeSomeRequestResultingInDeferred()
  1178. if thing == 'I love Twisted':
  1179. # will become the result of the Deferred
  1180. returnValue('TWISTED IS GREAT!')
  1181. else:
  1182. # will trigger an errback
  1183. raise Exception('DESTROY ALL LIFE')
  1184. If you are using Python 3.3 or later, it is possible to use the C{return}
  1185. statement instead of L{returnValue}::
  1186. @inlineCallbacks
  1187. def loadData(url):
  1188. response = yield makeRequest(url)
  1189. return json.loads(response)
  1190. """
  1191. @wraps(f)
  1192. def unwindGenerator(*args, **kwargs):
  1193. try:
  1194. gen = f(*args, **kwargs)
  1195. except _DefGen_Return:
  1196. raise TypeError(
  1197. "inlineCallbacks requires %r to produce a generator; instead"
  1198. "caught returnValue being used in a non-generator" % (f,))
  1199. if not isinstance(gen, types.GeneratorType):
  1200. raise TypeError(
  1201. "inlineCallbacks requires %r to produce a generator; "
  1202. "instead got %r" % (f, gen))
  1203. return _inlineCallbacks(None, gen, Deferred())
  1204. return unwindGenerator
  1205. ## DeferredLock/DeferredQueue
  1206. class _ConcurrencyPrimitive(object):
  1207. def __init__(self):
  1208. self.waiting = []
  1209. def _releaseAndReturn(self, r):
  1210. self.release()
  1211. return r
  1212. def run(*args, **kwargs):
  1213. """
  1214. Acquire, run, release.
  1215. This function takes a callable as its first argument and any
  1216. number of other positional and keyword arguments. When the
  1217. lock or semaphore is acquired, the callable will be invoked
  1218. with those arguments.
  1219. The callable may return a L{Deferred}; if it does, the lock or
  1220. semaphore won't be released until that L{Deferred} fires.
  1221. @return: L{Deferred} of function result.
  1222. """
  1223. if len(args) < 2:
  1224. if not args:
  1225. raise TypeError("run() takes at least 2 arguments, none given.")
  1226. raise TypeError("%s.run() takes at least 2 arguments, 1 given" % (
  1227. args[0].__class__.__name__,))
  1228. self, f = args[:2]
  1229. args = args[2:]
  1230. def execute(ignoredResult):
  1231. d = maybeDeferred(f, *args, **kwargs)
  1232. d.addBoth(self._releaseAndReturn)
  1233. return d
  1234. d = self.acquire()
  1235. d.addCallback(execute)
  1236. return d
  1237. class DeferredLock(_ConcurrencyPrimitive):
  1238. """
  1239. A lock for event driven systems.
  1240. @ivar locked: C{True} when this Lock has been acquired, false at all other
  1241. times. Do not change this value, but it is useful to examine for the
  1242. equivalent of a "non-blocking" acquisition.
  1243. """
  1244. locked = False
  1245. def _cancelAcquire(self, d):
  1246. """
  1247. Remove a deferred d from our waiting list, as the deferred has been
  1248. canceled.
  1249. Note: We do not need to wrap this in a try/except to catch d not
  1250. being in self.waiting because this canceller will not be called if
  1251. d has fired. release() pops a deferred out of self.waiting and
  1252. calls it, so the canceller will no longer be called.
  1253. @param d: The deferred that has been canceled.
  1254. """
  1255. self.waiting.remove(d)
  1256. def acquire(self):
  1257. """
  1258. Attempt to acquire the lock. Returns a L{Deferred} that fires on
  1259. lock acquisition with the L{DeferredLock} as the value. If the lock
  1260. is locked, then the Deferred is placed at the end of a waiting list.
  1261. @return: a L{Deferred} which fires on lock acquisition.
  1262. @rtype: a L{Deferred}
  1263. """
  1264. d = Deferred(canceller=self._cancelAcquire)
  1265. if self.locked:
  1266. self.waiting.append(d)
  1267. else:
  1268. self.locked = True
  1269. d.callback(self)
  1270. return d
  1271. def release(self):
  1272. """
  1273. Release the lock. If there is a waiting list, then the first
  1274. L{Deferred} in that waiting list will be called back.
  1275. Should be called by whomever did the L{acquire}() when the shared
  1276. resource is free.
  1277. """
  1278. assert self.locked, "Tried to release an unlocked lock"
  1279. self.locked = False
  1280. if self.waiting:
  1281. # someone is waiting to acquire lock
  1282. self.locked = True
  1283. d = self.waiting.pop(0)
  1284. d.callback(self)
  1285. class DeferredSemaphore(_ConcurrencyPrimitive):
  1286. """
  1287. A semaphore for event driven systems.
  1288. If you are looking into this as a means of limiting parallelism, you might
  1289. find L{twisted.internet.task.Cooperator} more useful.
  1290. @ivar limit: At most this many users may acquire this semaphore at
  1291. once.
  1292. @type limit: L{int}
  1293. @ivar tokens: The difference between C{limit} and the number of users
  1294. which have currently acquired this semaphore.
  1295. @type tokens: L{int}
  1296. """
  1297. def __init__(self, tokens):
  1298. """
  1299. @param tokens: initial value of L{tokens} and L{limit}
  1300. @type tokens: L{int}
  1301. """
  1302. _ConcurrencyPrimitive.__init__(self)
  1303. if tokens < 1:
  1304. raise ValueError("DeferredSemaphore requires tokens >= 1")
  1305. self.tokens = tokens
  1306. self.limit = tokens
  1307. def _cancelAcquire(self, d):
  1308. """
  1309. Remove a deferred d from our waiting list, as the deferred has been
  1310. canceled.
  1311. Note: We do not need to wrap this in a try/except to catch d not
  1312. being in self.waiting because this canceller will not be called if
  1313. d has fired. release() pops a deferred out of self.waiting and
  1314. calls it, so the canceller will no longer be called.
  1315. @param d: The deferred that has been canceled.
  1316. """
  1317. self.waiting.remove(d)
  1318. def acquire(self):
  1319. """
  1320. Attempt to acquire the token.
  1321. @return: a L{Deferred} which fires on token acquisition.
  1322. """
  1323. assert self.tokens >= 0, "Internal inconsistency?? tokens should never be negative"
  1324. d = Deferred(canceller=self._cancelAcquire)
  1325. if not self.tokens:
  1326. self.waiting.append(d)
  1327. else:
  1328. self.tokens = self.tokens - 1
  1329. d.callback(self)
  1330. return d
  1331. def release(self):
  1332. """
  1333. Release the token.
  1334. Should be called by whoever did the L{acquire}() when the shared
  1335. resource is free.
  1336. """
  1337. assert self.tokens < self.limit, "Someone released me too many times: too many tokens!"
  1338. self.tokens = self.tokens + 1
  1339. if self.waiting:
  1340. # someone is waiting to acquire token
  1341. self.tokens = self.tokens - 1
  1342. d = self.waiting.pop(0)
  1343. d.callback(self)
  1344. class QueueOverflow(Exception):
  1345. pass
  1346. class QueueUnderflow(Exception):
  1347. pass
  1348. class DeferredQueue(object):
  1349. """
  1350. An event driven queue.
  1351. Objects may be added as usual to this queue. When an attempt is
  1352. made to retrieve an object when the queue is empty, a L{Deferred} is
  1353. returned which will fire when an object becomes available.
  1354. @ivar size: The maximum number of objects to allow into the queue
  1355. at a time. When an attempt to add a new object would exceed this
  1356. limit, L{QueueOverflow} is raised synchronously. L{None} for no limit.
  1357. @ivar backlog: The maximum number of L{Deferred} gets to allow at
  1358. one time. When an attempt is made to get an object which would
  1359. exceed this limit, L{QueueUnderflow} is raised synchronously. L{None}
  1360. for no limit.
  1361. """
  1362. def __init__(self, size=None, backlog=None):
  1363. self.waiting = []
  1364. self.pending = []
  1365. self.size = size
  1366. self.backlog = backlog
  1367. def _cancelGet(self, d):
  1368. """
  1369. Remove a deferred d from our waiting list, as the deferred has been
  1370. canceled.
  1371. Note: We do not need to wrap this in a try/except to catch d not
  1372. being in self.waiting because this canceller will not be called if
  1373. d has fired. put() pops a deferred out of self.waiting and calls
  1374. it, so the canceller will no longer be called.
  1375. @param d: The deferred that has been canceled.
  1376. """
  1377. self.waiting.remove(d)
  1378. def put(self, obj):
  1379. """
  1380. Add an object to this queue.
  1381. @raise QueueOverflow: Too many objects are in this queue.
  1382. """
  1383. if self.waiting:
  1384. self.waiting.pop(0).callback(obj)
  1385. elif self.size is None or len(self.pending) < self.size:
  1386. self.pending.append(obj)
  1387. else:
  1388. raise QueueOverflow()
  1389. def get(self):
  1390. """
  1391. Attempt to retrieve and remove an object from the queue.
  1392. @return: a L{Deferred} which fires with the next object available in
  1393. the queue.
  1394. @raise QueueUnderflow: Too many (more than C{backlog})
  1395. L{Deferred}s are already waiting for an object from this queue.
  1396. """
  1397. if self.pending:
  1398. return succeed(self.pending.pop(0))
  1399. elif self.backlog is None or len(self.waiting) < self.backlog:
  1400. d = Deferred(canceller=self._cancelGet)
  1401. self.waiting.append(d)
  1402. return d
  1403. else:
  1404. raise QueueUnderflow()
  1405. class AlreadyTryingToLockError(Exception):
  1406. """
  1407. Raised when L{DeferredFilesystemLock.deferUntilLocked} is called twice on a
  1408. single L{DeferredFilesystemLock}.
  1409. """
  1410. class DeferredFilesystemLock(lockfile.FilesystemLock):
  1411. """
  1412. A L{FilesystemLock} that allows for a L{Deferred} to be fired when the lock is
  1413. acquired.
  1414. @ivar _scheduler: The object in charge of scheduling retries. In this
  1415. implementation this is parameterized for testing.
  1416. @ivar _interval: The retry interval for an L{IReactorTime} based scheduler.
  1417. @ivar _tryLockCall: A L{DelayedCall} based on C{_interval} that will manage
  1418. the next retry for acquiring the lock.
  1419. @ivar _timeoutCall: A L{DelayedCall} based on C{deferUntilLocked}'s timeout
  1420. argument. This is in charge of timing out our attempt to acquire the
  1421. lock.
  1422. """
  1423. _interval = 1
  1424. _tryLockCall = None
  1425. _timeoutCall = None
  1426. def __init__(self, name, scheduler=None):
  1427. """
  1428. @param name: The name of the lock to acquire
  1429. @param scheduler: An object which provides L{IReactorTime}
  1430. """
  1431. lockfile.FilesystemLock.__init__(self, name)
  1432. if scheduler is None:
  1433. from twisted.internet import reactor
  1434. scheduler = reactor
  1435. self._scheduler = scheduler
  1436. def deferUntilLocked(self, timeout=None):
  1437. """
  1438. Wait until we acquire this lock. This method is not safe for
  1439. concurrent use.
  1440. @type timeout: L{float} or L{int}
  1441. @param timeout: the number of seconds after which to time out if the
  1442. lock has not been acquired.
  1443. @return: a L{Deferred} which will callback when the lock is acquired, or
  1444. errback with a L{TimeoutError} after timing out or an
  1445. L{AlreadyTryingToLockError} if the L{deferUntilLocked} has already
  1446. been called and not successfully locked the file.
  1447. """
  1448. if self._tryLockCall is not None:
  1449. return fail(
  1450. AlreadyTryingToLockError(
  1451. "deferUntilLocked isn't safe for concurrent use."))
  1452. def _cancelLock(reason):
  1453. """
  1454. Cancel a L{DeferredFilesystemLock.deferUntilLocked} call.
  1455. @type reason: L{failure.Failure}
  1456. @param reason: The reason why the call is cancelled.
  1457. """
  1458. self._tryLockCall.cancel()
  1459. self._tryLockCall = None
  1460. if self._timeoutCall is not None and self._timeoutCall.active():
  1461. self._timeoutCall.cancel()
  1462. self._timeoutCall = None
  1463. if self.lock():
  1464. d.callback(None)
  1465. else:
  1466. d.errback(reason)
  1467. d = Deferred(lambda deferred: _cancelLock(CancelledError()))
  1468. def _tryLock():
  1469. if self.lock():
  1470. if self._timeoutCall is not None:
  1471. self._timeoutCall.cancel()
  1472. self._timeoutCall = None
  1473. self._tryLockCall = None
  1474. d.callback(None)
  1475. else:
  1476. if timeout is not None and self._timeoutCall is None:
  1477. reason = failure.Failure(TimeoutError(
  1478. "Timed out acquiring lock: %s after %fs" % (
  1479. self.name,
  1480. timeout)))
  1481. self._timeoutCall = self._scheduler.callLater(
  1482. timeout, _cancelLock, reason)
  1483. self._tryLockCall = self._scheduler.callLater(
  1484. self._interval, _tryLock)
  1485. _tryLock()
  1486. return d
  1487. __all__ = ["Deferred", "DeferredList", "succeed", "fail", "FAILURE", "SUCCESS",
  1488. "AlreadyCalledError", "TimeoutError", "gatherResults",
  1489. "maybeDeferred", "ensureDeferred",
  1490. "waitForDeferred", "deferredGenerator", "inlineCallbacks",
  1491. "returnValue",
  1492. "DeferredLock", "DeferredSemaphore", "DeferredQueue",
  1493. "DeferredFilesystemLock", "AlreadyTryingToLockError",
  1494. ]