o 5@gN@sdUdZddlZddlZddlmZmZddlmZmZm Z ddl m Z ddl m Z ddlmZmZddlmZmZdd lmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'ddl(Z(dd l)m*Z*dd l+m,Z,m-Z-dd l.m/Z/dd l0m1Z1ddl2m3Z3m4Z4m5Z5ddl6m7Z7m8Z8ddl9m:Z:m;Z;z ddldZ?Wne@ydZ?GdddZAde#eAfddZBYnwe>ZBe/ZCe$dZDGdddeEZFGdddeEZGGdddeEZHGd d!d!eIZJd"e:de:fd#d$ZKd%eDdd&fd'd(ZLdd%e!e%e:eMfdd)fd*d+ZNd,ed-eDfd.eOd/eOdd&fd0d1ZPd2ed-eDfd.eOd/eOdd&fd3d4ZQe7e*d5d6d7dd8d9ddeDdeDfd?d@ZSd>e:de:fdAdBZTdCeUddfdDdEZVdeUfdFdGZWdHeDd=eXdeDfdIdJZYGdKdLdLe ZZeZj[Z[eZj\Z\ed-eOfZ]ed-eOfZ^e"eOd-fZ_ee`eOfZae"e"e%e]eeZj\fe_eafe"e%e^e]eeZj\fe_eaffZbeiZceaeddM<e$dNddOZee$dPddQZfGdRdSdSZgGdTdUdUeeeZhdVe%eeheDeeDfeeheDeeDfeheDfdeheDfdWdXZie5GdYdZdZeEZje"eeekfZle"eUeefZmeemZnerle'  dd[eeheed\edd]eUd^eUdehelf d_d`Zoe'   dd[eeheed\edd]eUd^eUdehenf dad`Zo   dd[eeheed\eUd]eUd^eUde%ehelehenff dbd`ZoeoZpGdcddddehenZp ddeeemd]eUdeeDfdfdgZq dd[eeheDd^eUdeheeDfdhdiZrdZsdZtGdjdkdkZueeOddfZvdlevd:eheOdehefdmdnZwe7e*d5dodddpd2ed-evfded-eheOffdqdrZxGdsdtdteMZydueOde fdvdwZze(j{ddxGdydzdzZ|e;d%eOd{e%eeheDeOdfeeheDeOdffd|e|ddfd}d~Z}d{e%ed&eOeDfed&eOeDffdeheDfddZ~GdddeEZd2ed-eeheOeOeDffded-eheDffddZe$dddZGdddeeeeZe$dddZGdddeZe$dddZGdddeZGdddeEZGdddeEZGdddeeDZGdddeEZGddde1jZgdZdS)zU Support for results that aren't immediately available. Maintainer: Glyph Lefkowitz N)ABCabstractmethod)AbstractEventLoopFuture iscoroutine)Enum)wraps)exc_info version_info) GeneratorTypeMappingProxyType) TYPE_CHECKINGAny AwaitableCallable Coroutine GeneratorGenericIterableListLiteralMappingNoReturnOptionalTupleTypeTypeVarUnioncastoverload)Version) IDelayedCall IReactorTime)Logger)lockfile)_PYPYcmp comparable) deprecatedwarnAboutFunction)Failure _extraneous) copy_contextTFc @s2eZdZededefdededefddZdS) _NoContextf.argskwargsreturncOs||i|SN)r.r/r0r3r38/usr/lib/python3/dist-packages/twisted/internet/defer.pyrun<sz_NoContext.runN)__name__ __module__ __qualname__ staticmethodrobjectr5r3r3r3r4r-;s(r-r1cCstSr2)r-r3r3r3r4 _copy_context@r;_Tc@eZdZdZdS)AlreadyCalledErrorz This error is raised when one of L{Deferred.callback} or L{Deferred.errback} is called after one of the two had already been called. Nr6r7r8__doc__r3r3r3r4r?Mr?c@r>)CancelledErrorzJ This error is raised by default when a L{Deferred} is cancelled. Nr@r3r3r3r4rCTrBrCc@r>) TimeoutErrorzG This error is raised by default when a L{Deferred} times out. Nr@r3r3r3r4rDZrBrDc@r>)NotACoroutineErrorzb This error is raised when a coroutine is expected and something else is encountered. Nr@r3r3r3r4rE`rBrEerrcCstd||S)a- Log and return failure. This method can be used as an errback that passes the failure on to the next errback unmodified. Note that if this is the last errback, and the deferred gets garbage collected after being this errback has been called, the clean up code logs it again. )logfailure)rFr3r3r4logErrorgs rJresult Deferred[_T]cCt}|||S)a Return a L{Deferred} that has already had C{.callback(result)} called. This is useful when you're writing synchronous code to an asynchronous interface: i.e., some code is calling you expecting a L{Deferred} result, but you don't actually need to do anything asynchronous. Just return C{defer.succeed(theResult)}. See L{fail} for a version of this function that uses a failing L{Deferred} rather than a successful one. @param result: The result to give to the Deferred's 'callback' method. )DeferredcallbackrKdr3r3r4succeedts rR Deferred[Any]cCrM)a2 Return a L{Deferred} that has already had C{.errback(result)} called. See L{succeed}'s docstring for rationale. @param result: The same argument that L{Deferred.errback} takes. @raise NoCurrentExceptionError: If C{result} is L{None} but there is no current exception state. )rNerrbackrPr3r3r4fails rUcallable.r/r0cOs2z ||i|}Wt|StytYSw)a Create a L{Deferred} from a callable and arguments. Call the given function with the given arguments. Return a L{Deferred} which has been fired with its callback as the result of that invocation or its C{errback} with a L{Failure} for the exception thrown. ) BaseExceptionrUrR)rVr/r0rKr3r3r4executes   rXr.cOs^z ||i|}WntytttjdYSwt|tr"|St|tr+t|St|S)a Invoke a function that may or may not return a L{Deferred}. Call the given function with the given arguments. If the returned object is a L{Deferred}, return it. If the returned object is a L{Failure}, wrap it with L{fail} and return it. Otherwise, wrap it in L{succeed} and return it. If an exception is raised, convert it to a L{Failure}, wrap it in L{fail}, and then return it. @param f: The callable to invoke @param args: The arguments to pass to C{f} @param kwargs: The keyword arguments to pass to C{f} @return: The result of the function call, wrapped in a L{Deferred} if necessary.  captureVars)rWrUr*rNdebug isinstancerR)r.r/r0rKr3r3r4 maybeDeferreds   r]Twistedz*twisted.internet.defer.Deferred.addTimeout) replacementdeferredDeferred[object]cCs|ttddS)NzCallback timed out)rTr*rDrbr3r3r4timeoutsreargcC|Sr2r3rfr3r3r4passthrur<ricCrgr2r3rhr3r3r4 _failthrur<rjoncCst|t_dS)z Enable or disable L{Deferred} debugging. When debugging is on, the call stacks from creation and invocation are recorded, and added to any L{AlreadyCalledError}s we raise. N)boolrNr[)rkr3r3r4 setDebuggingsrmcCstjS)z= Determine whether L{Deferred} debugging is enabled. )rNr[r3r3r3r4 getDebuggingsrnvaluecCs"t|tr|tt|d|S)a A default translation function that translates L{Failure}s that are L{CancelledError}s to L{TimeoutError}s. @param value: Anything @param timeout: The timeout @raise TimeoutError: If C{value} is a L{Failure} that is a L{CancelledError}. @raise Exception: If C{value} is a L{Failure} that is not a L{CancelledError}, it is re-raised. @since: 16.5 rN)r\r*traprCrD)rorer3r3r4_cancelledToTimedOutErrors   rqc@seZdZdZeZeZdS) _Sentinela @cvar _NO_RESULT: The result used to represent the fact that there is no result. B{Never ever ever use this as an actual result for a Deferred}. You have been warned. @cvar _CONTINUE: A marker left in L{Deferred.callback}s to indicate a Deferred chain. Always accompanied by a Deferred instance in the args tuple pointing at the Deferred which is chained to the Deferred which has this marker. N)r6r7r8rAr: _NO_RESULT _CONTINUEr3r3r3r4rrs rr _NONE_KWARGS_DeferredResultT) contravariant_NextDeferredResultT) covariantc@sbeZdZUdZdZeeed<dZee e ed<dZ ee e ed<de fddZ d d d Z dS) DebugInfoz Deferred debug helper. N failResultcreatorinvokerr1cCstd}|jdur|d7}|d|jdd7}|d7}|jdur8|d7}|d|jdd7}|d7}|S)NrGz C: Deferred was created: C: z C:z I: First Invoker was: I:z I:)r|joinrstripreplacer})selfinfor3r3r4_getDebugTracebacks:s  zDebugInfo._getDebugTracebackscCsH|jdur"tjddd|}|rd}nd}tj||j|ddSdS)z Print tracebacks and die. If the *last* (and I do mean *last*) callback leaves me in an error state, print a traceback (if said errback is a L{Failure}). NzUnhandled error in Deferred:T)isErrorz(debug: {debugInfo})rG) debugInfo)r{rHcriticalrrI)rrformatr3r3r4__del__Fs zDebugInfo.__del__r1N)r6r7r8rAr{rr*__annotations__r|rstrr}rrr3r3r3r4rz1s  rzc@s^eZdZUdZdZdZdZeee d<dZ dZ dZ dZ de d< dRdeed gdfd dfd d Zed ed efdeddeddedededed dfddZdeddeded dfddZdeddeded dfddZdeddeded dfd d!Z dRd"ed#ed$eeeegefd d%fd&d'ZdSd*d+Zd,eeefd dfd-d.Z dRd/eeee!fd dfd0d1Z"dTd2d3Z#dTd4d5Z$dTd6d7Z%d,ed dfd8d9Z&d e'fd:d;Z(dTdd?Z+e+Z,dUd@dAZ-e.dRdBed d%fdCdDZ/d e0e1deffdEdFZ2e/Z3dGe4d dHfdIdJZ5e6dKe7d d fdLdMZ8e6dNee9dOe1e:fe0dOe1e:ffd dOfdPdQZ;dS)VrNa This is a callback which will be put off until later. Why do we want this? Well, in cases where a function in a threaded program would block until it gets a result, for Twisted it should not block. Instead, it should return a L{Deferred}. This can be implemented for protocols that run over the network by writing an asynchronous protocol for L{twisted.internet}. For methods that come from outside packages that are not under our control, we use threads (see for example L{twisted.enterprise.adbapi}). For more information about Deferreds, see doc/core/howto/defer.html or U{http://twistedmatrix.com/documents/current/core/howto/defer.html} When creating a Deferred, you may provide a canceller function, which will be called by d.cancel() to let you do any clean-up necessary if the user decides not to wait for the deferred to complete. @ivar called: A flag which is C{False} until either C{callback} or C{errback} is called and afterwards always C{True}. @ivar paused: A counter of how many unmatched C{pause} calls have been made on this instance. @ivar _suppressAlreadyCalled: A flag used by the cancellation mechanism which is C{True} if the Deferred has no canceller and has been cancelled, C{False} otherwise. If C{True}, it can be expected that C{callback} or C{errback} will eventually be called and the result should be silently discarded. @ivar _runningCallbacks: A flag which is C{True} while this instance is executing its callback chain, used to stop recursive execution of L{_runCallbacks} @ivar _chainedTo: If this L{Deferred} is waiting for the result of another L{Deferred}, this is a reference to the other Deferred. Otherwise, L{None}. FrN _debugInfozOptional[Deferred[Any]] _chainedTo cancellerrSr1cCs6g|_||_|jrt|_tdd|j_dSdS)aH Initialize a L{Deferred}. @param canceller: a callable used to stop the pending operation scheduled by this L{Deferred} when L{Deferred.cancel} is invoked. The canceller will be passed the deferred whose cancellation is requested (i.e., C{self}). If a canceller is not given, or does not invoke its argument's C{callback} or C{errback} method, L{Deferred.cancel} will invoke L{Deferred.errback} with a L{CancelledError}. Note that if a canceller is not given, C{callback} or C{errback} may still be invoked exactly once, even though defer.py will have already invoked C{errback}, as described above. This allows clients of code which returns a L{Deferred} to cancel it without requiring the L{Deferred} instantiator to provide any specific implementation support for cancellation. New in 10.1. @type canceller: a 1-argument callable which takes a L{Deferred}. The return result is ignored. N) callbacks _cancellerr[rzr traceback format_stackr|rrr3r3r4__init__s zDeferred.__init__r3rO).z;Union[_NextDeferredResultT, Deferred[_NextDeferredResultT]]rT).zDUnion[Failure, _NextDeferredResultT, Deferred[_NextDeferredResultT]] callbackArgscallbackKeywords errbackArgserrbackKeywordszDeferred[_NextDeferredResultT]cCs|durt}|dur d}|duri}|durd}|duri}t|s$Jt|s*J|j|||f|||ff|jr?|ttt|S)z Add a pair of callbacks (success and error) to this L{Deferred}. These will be executed when the 'master' callback is run. @return: C{self}. Nr3) rjrVrappendcalled _runCallbacksrrNrx)rrOrTrrrrr3r3r4 addCallbackss(  zDeferred.addCallbacksr/r0cOs|j|||dS)z^ Convenience method for adding just a callback. See L{addCallbacks}. )rrrrrOr/r0r3r3r4 addCallbackzDeferred.addCallbackz7Deferred[Union[_DeferredResultT, _NextDeferredResultT]]cOs|jt|||dS)z^ Convenience method for adding just an errback. See L{addCallbacks}. )rr)rri)rrTr/r0r3r3r4 addErrbacks zDeferred.addErrbackcOs|j||||||dS)z Convenience method for adding a single callable as both a callback and an errback. See L{addCallbacks}. )rrrrrrr3r3r4addBoth szDeferred.addBothreclockonTimeoutCancelDeferred[_DeferredResultT]cszdgd fdd }||dtdtffdd }|d tttfdtttfffd d }|S) a Time out this L{Deferred} by scheduling it to be cancelled after C{timeout} seconds. The timeout encompasses all the callbacks and errbacks added to this L{defer.Deferred} before the call to L{addTimeout}, and none added after the call. If this L{Deferred} gets timed out, it errbacks with a L{TimeoutError}, unless a cancelable function was passed to its initialization or unless a different C{onTimeoutCancel} callable is provided. @param timeout: number of seconds to wait before timing out this L{Deferred} @param clock: The object which will be used to schedule the timeout. @param onTimeoutCancel: A callable which is called immediately after this L{Deferred} times out, and not if this L{Deferred} is otherwise cancelled before the timeout. It takes an arbitrary value, which is the value of this L{Deferred} at that exact point in time (probably a L{CancelledError} L{Failure}), and the C{timeout}. The default callable (if C{None} is provided) will translate a L{CancelledError} L{Failure} into a L{TimeoutError}. @return: C{self}. @since: 16.5 Fr1Ncsdd<dS)NTr)cancelr3)rtimedOutr3r4 timeItOutGs z&Deferred.addTimeout..timeItOutrocsdr pt}||S|S)Nr)rq)rotoCall)rrrer3r4convertCancelledMs z-Deferred.addTimeout..convertCancelledrKcsr|Sr2)activerrK) delayedCallr3r4 cancelTimeoutWsz*Deferred.addTimeout..cancelTimeoutr) callLaterr:rrrvr*)rrerrrrrr3)rrrrrer4 addTimeout#s"     zDeferred.addTimeoutrQDeferred[None]cCs||_||j|jS)a Chain another L{Deferred} to this L{Deferred}. This method adds callbacks to this L{Deferred} to call C{d}'s callback or errback, as appropriate. It is merely a shorthand way of performing the following:: d1.addCallbacks(d2.callback, d2.errback) When you chain a deferred C{d2} to another deferred C{d1} with C{d1.chainDeferred(d2)}, you are making C{d2} participate in the callback chain of C{d1}. Thus any event that fires C{d1} will also fire C{d2}. However, the converse is B{not} true; if C{d2} is fired, C{d1} will not be affected. Note that unlike the case where chaining is caused by a L{Deferred} being returned from a callback, it is possible to cause the call stack size limit to be exceeded by chaining many L{Deferred}s together with C{chainDeferred}. @return: C{self}. )rrrOrTrrQr3r3r4 chainDeferredbszDeferred.chainDeferredrKcCst|trJ||dS)a7 Run all success callbacks that have been added to this L{Deferred}. Each callback will have its result passed as the first argument to the next; this way, the callbacks act as a 'processing chain'. If the success-callback returns a L{Failure} or raises an L{Exception}, processing will continue on the *error* callback chain. If a callback (or errback) returns another L{Deferred}, this L{Deferred} will be chained to it (and further callbacks will not run until that L{Deferred} has a result). An instance of L{Deferred} may only have either L{callback} or L{errback} called on it, and only once. @param result: The object which will be passed to the first callback added to this L{Deferred} (via L{addCallback}), unless C{result} is a L{Failure}, in which case the behavior is the same as calling C{errback(result)}. @raise AlreadyCalledError: If L{callback} or L{errback} has already been called on this L{Deferred}. N)r\rN_startRunCallbacks)rrKr3r3r4rO}szDeferred.callbackrUcCs6|dur t|jd}n t|tst|}||dS)a Run all error callbacks that have been added to this L{Deferred}. Each callback will have its result passed as the first argument to the next; this way, the callbacks act as a 'processing chain'. Also, if the error-callback returns a non-Failure or doesn't raise an L{Exception}, processing will continue on the *success*-callback chain. If the argument that's passed to me is not a L{Failure} instance, it will be embedded in one. If no argument is passed, a L{Failure} instance will be created based on the current traceback stack. Passing a string as `fail' is deprecated, and will be punished with a warning message. An instance of L{Deferred} may only have either L{callback} or L{errback} called on it, and only once. @param fail: The L{Failure} object which will be passed to the first errback added to this L{Deferred} (via L{addErrback}). Alternatively, a L{Exception} instance from which a L{Failure} will be constructed (with no traceback) or L{None} to create a L{Failure} instance from the current exception state (with a traceback). @raise AlreadyCalledError: If L{callback} or L{errback} has already been called on this L{Deferred}. @raise NoCurrentExceptionError: If C{fail} is L{None} but there is no current exception state. NrY)r*r[r\r)rrUr3r3r4rTs   zDeferred.errbackcCs|jd|_dS)zP Stop processing on a L{Deferred} until L{unpause}() is called. r`N)pausedrr3r3r4pauseszDeferred.pausecCs,|jd|_|jr dS|jr|dSdS)zI Process all callbacks made since L{pause}() was called. r`N)rrrrr3r3r4unpauses  zDeferred.unpausecCs\|js|j}|r ||nd|_|js|ttdSdSt|jtr,|j dSdS)a Cancel this L{Deferred}. If the L{Deferred} has not yet had its C{errback} or C{callback} method invoked, call the canceller function provided to the constructor. If that function does not invoke C{callback} or C{errback}, or if no canceller function was provided, errback with L{CancelledError}. If this L{Deferred} is waiting on another L{Deferred}, forward the cancellation to the other L{Deferred}. TN) rr_suppressAlreadyCalledrTr*rCr\rKrNrrr3r3r4rs   zDeferred.cancelcCs|jr$|jr d|_dS|jr"|jdurt|_d|j}t|t|jr:|jdur0t|_tdd|j_ d|_||_ | dS)NFr~T) rrr[rrzrr?rrr}rKr)rrKextrar3r3r4rs"   zDeferred._startRunCallbackscCstj|ftftj|ftffS)zT Build a tuple of callback and errback with L{_Sentinel._CONTINUE}. )rrrtrurr3r3r4 _continuations  zDeferred._continuationc Cs|jrdS|g}|r |d}|jrdSd}d|_|jr|jd}t|jts0|d\}}}n|d\}}}|turct t t |d}|j|_d|_|j durTd|j _ |jd8_||d}nxz&d|_z||jg|Ri||_|j|urt|dWd|_nd|_wWntyt|jd|_Yn?wt|jt rt|jd t} | tust| t s|jjr||j|_|jj|nd|j_|jj durd|jj _ | |_|js|rt|jtr|j|j durt|_ |j|j _ n |j durd|j _ ||s dSdS) a Run the chain of callbacks once a result is available. This consists of a simple loop over all of the callbacks, calling each with the current result and making the current result equal to the return value (or raised exception) of that call. If L{_runningCallbacks} is true, this loop won't run at all, since it is already running above us on the call stack. If C{self.paused} is true, the loop also won't run, because that's what it means to be paused. The loop will terminate before processing all of the callbacks if a L{Deferred} without a result is encountered. If a L{Deferred} I{with} a result is encountered, that result is taken and the loop proceeds. @note: The implementation is complicated slightly by the fact that chaining (associating two L{Deferred}s with each other such that one will wait for the result of the other, as happens when a Deferred is returned from a callback on another L{Deferred}) is supported iteratively rather than recursively, to avoid running out of stack frames when processing long chains. NrTrr`Fz|Callback returned the Deferred it was attached to; this breaks the callback chain and will raise an exception in the future.rYrK)_runningCallbacksrrrpopr\rKr*rtrrNr:rr{rr)rWr[getattrrsrr cleanFailurerz) rchaincurrentfinisheditemrOr/r0chainee resultResultr3r3r4rs         P      zDeferred._runCallbackscCsj|jj}t|dt}t|}|jdurdt|jd}n |tur$d}nd|}d|d|d|d S) zE Return a string representation of this L{Deferred}. rKNz waiting on Deferred at 0xxrGz current result: ) __class__r6rrsidr)rcnamerKmyIDr3r3r4__str__s   zDeferred.__str__cCrgr2r3rr3r3r4__iter__r<zDeferred.__iter__rocCsX|jr|St|dt}|tur|St|tr(|jdusJd|j_||j_|jt |)NrK) rrrsr\r*rr{ro __failure__ StopIteration)rrorKr3r3r4sends  z Deferred.sendcC|Sr2)rrr3r3r4 __await__szDeferred.__await__loopFuture[_DeferredResultT]cs\|d fdd }dtddffdd }d tddffd d }|||S)a Adapt this L{Deferred} into a L{Future} which is bound to C{loop}. @note: converting a L{Deferred} to an L{Future} consumes both its result and its errors, so this method implicitly converts C{self} into a L{Deferred} firing with L{None}, regardless of what its result previously would have been. @since: Twisted 17.5.0 @param loop: The L{asyncio} event loop to bind the L{Future} to. @return: A L{Future} which will fire when the L{Deferred} fires. futureAgainrr1Ncs|r dSdSr2) cancelledr)rrr3r4 checkCancels z&Deferred.asFuture..checkCancelrIcss |jdSdSr2)r set_exceptionro)rIfuturer3r4 maybeFailsz$Deferred.asFuture..maybeFailrKcss |dSdSr2)r set_resultrrr3r4 maybeSucceedsz'Deferred.asFuture..maybeSucceed)rrr1N) create_futurer*r:radd_done_callback)rrrrrr3)rrr4asFutures  zDeferred.asFuturercsdtddffdd }tdttddffdd }||}|dtdttttfffd d }||||S) a Adapt a L{Future} to a L{Deferred}. @note: This creates a L{Deferred} from a L{Future}, I{not} from a C{coroutine}; in other words, you will need to call L{asyncio.ensure_future}, L{asyncio.loop.create_task} or create an L{asyncio.Task} yourself to get from a C{coroutine} to a L{Future} if what you have is an awaitable coroutine and not a L{Future}. (The length of this list of techniques is exactly why we have left it to the caller!) @since: Twisted 17.5.0 @param future: The L{Future} to adapt. @return: A L{Deferred} which will fire when the L{Future} fires. rKr1Ncs4z|}Wn tyt}Ynw|dSr2)rKrWr*rO)rK extracted)actualr3r4adapts    z"Deferred.fromFuture..adaptreselfcs|dSr2)rrO)r)r futureCancelr3r4r sz#Deferred.fromFuture..cancelcs|ur tS|Sr2)rNr)rrr3r4uncancelsz%Deferred.fromFuture..uncancel)rr:rNrvrrr)clsrrrrrr3)rrrr4 fromFutures zDeferred.fromFuturecororLcCs(t|st|tst|dt|S)a Schedule the execution of a coroutine that awaits on L{Deferred}s, wrapping it in a L{Deferred} that will fire on success/failure of the coroutine. Coroutine functions return a coroutine object, similar to how generators work. This function turns that coroutine into a Deferred, meaning that it can be used in regular Twisted code. For example:: import treq from twisted.internet.defer import Deferred from twisted.internet.task import react async def crawl(pages): results = {} for page in pages: results[page] = await treq.content(await treq.get(page)) return results def main(reactor): pages = [ "http://localhost:8080" ] d = Deferred.fromCoroutine(crawl(pages)) d.addCallback(print) return d react(main) @since: Twisted 21.2.0 @param coro: The coroutine object to schedule. @raise ValueError: If C{coro} is not a coroutine or generator. z is not a coroutine)rr\r rE_cancellableInlineCallbacks)rrr3r3r4 fromCoroutine"s,zDeferred.fromCoroutiner2)rQrr1rr)r1r)\sz,_parseDeferredListResult..r3)r rrKsuccessror3r3r4_parseDeferredListResultTs   rcCs*t|d|d}|ttttt|S)a  Returns, via a L{Deferred}, a list with the results of the given L{Deferred}s - in effect, a "join" of multiple deferred operations. The returned L{Deferred} will fire when I{all} of the provided L{Deferred}s have fired, or when any one of them has failed. This method can be cancelled by calling the C{cancel} method of the L{Deferred}, all the L{Deferred}s in the list will be cancelled. This differs from L{DeferredList} in that you don't need to parse the result for success/failure. @param consumeErrors: (keyword param) a flag, defaulting to False, indicating that failures in any of the given L{Deferred}s should not be propagated to errbacks added to the individual L{Deferred}s after this L{gatherResults} invocation. Any such errors in the individual L{Deferred}s will be converted to a callback result of L{None}. This is useful to prevent spurious 'Unhandled error in Deferred' messages from being logged. This parameter is available since 11.1.0. T)rr)rrrrrNrr=)rrrQr3r3r4 gatherResults_s rc@sBeZdZUdZeZeed<dee ddfddZ defdd Z dS) waitForDeferred# See L{deferredGenerator}. rKrQr1NcCs4tjdtddt|tstd|d||_dS)Nztwisted.internet.defer.waitForDeferred was deprecated in Twisted 15.0.0; please use twisted.internet.defer.inlineCallbacks instead) stacklevelz6You must give waitForDeferred a Deferred. You gave it .)warningswarnDeprecationWarningr\rN TypeErrorrQrr3r3r4rs   zwaitForDeferred.__init__cCs&t|jtr |j|jtu|jSr2)r\rKr*raiseExceptionrsrr3r3r4 getResults   zwaitForDeferred.getResult) r6r7r8rArsrKrrrNr:rr"r3r3r3r4rs  rgcsd}ddg zt}Wnty|YSty+YSwt|tr7ttdSt|t rjt t |fdt dt ddffdd }|j |d r`d d <Sdd <dd<d}q) rNTr`z Yield waitForDeferred(d), not d!rrKr1cs0||_drdd<|d<dStdSNrFr`)rK_deferGenerator)r$rKrbr#waitingr3r4 gotResults  z"_deferGenerator..gotResultrF)nextrrOrWrTr\rNrUr rrr:rQr)r#rbrKr)r3r'r4r&s>         r&z&twisted.internet.defer.inlineCallbacksc*tdtdtdttffdd }|S)aI L{deferredGenerator} and L{waitForDeferred} help you write L{Deferred}-using code that looks like a regular sequential function. Consider the use of L{inlineCallbacks} instead, which can accomplish the same thing in a more concise manner. There are two important functions involved: L{waitForDeferred}, and L{deferredGenerator}. They are used together, like this:: @deferredGenerator def thingummy(): thing = waitForDeferred(makeSomeRequestResultingInDeferred()) yield thing thing = thing.getResult() print(thing) #the result! hoorj! L{waitForDeferred} returns something that you should immediately yield; when your generator is resumed, calling C{thing.getResult()} will either give you the result of the L{Deferred} if it was a success, or raise an exception if it was a failure. Calling C{getResult} is B{absolutely mandatory}. If you do not call it, I{your program will not work}. L{deferredGenerator} takes one of these waitForDeferred-using generator functions and converts it into a function that returns a L{Deferred}. The result of the L{Deferred} will be the last value that your generator yielded unless the last value is a L{waitForDeferred} instance, in which case the result will be L{None}. If the function raises an unhandled exception, the L{Deferred} will errback instead. Remember that C{return result} won't work; use C{yield result; return} in place of that. Note that not yielding anything from your generator will make the L{Deferred} result in L{None}. Yielding a L{Deferred} from your generator is also an error condition; always yield C{waitForDeferred(d)} instead. The L{Deferred} returned from your deferred generator may also errback if your generator raised an exception. For example:: @deferredGenerator def thingummy(): thing = waitForDeferred(makeSomeRequestResultingInDeferred()) yield thing thing = thing.getResult() if thing == 'I love Twisted': # will become the result of the Deferred yield 'TWISTED IS GREAT!' return else: # will trigger an errback raise Exception('DESTROY ALL LIFE') Put succinctly, these functions connect deferred-using code with this 'fake blocking' style in both directions: L{waitForDeferred} converts from a L{Deferred} to the 'blocking' style, and L{deferredGenerator} converts from the 'blocking' style to a L{Deferred}. r/r0r1cst|i|tSr2)r&rN)r/r0r.r3r4unwindGeneratorsz*deferredGenerator..unwindGeneratorrr:rNr.r.r3r-r4deferredGenerators< r1c@seZdZdeddfddZdS)_DefGen_Returnror1NcCs ||_dSr2)ro)rror3r3r4r) z_DefGen_Return.__init__)r6r7r8r:rr3r3r3r4r2(sr2valcCst|)a Return val from a L{inlineCallbacks} generator. Note: this is currently implemented by raising an exception derived from L{BaseException}. You might want to change any 'except:' clauses to an 'except Exception:' clause so as not to catch this exception. Also: while this function currently will work when called from within arbitrary functions called from within the generator, do not rely upon this behavior. )r2)r4r3r3r4 returnValue-s r5) auto_attribsc@s2eZdZUdZeeed<dZeeeed<dS)_CancellationStatusa, Cancellation status of an L{inlineCallbacks} invocation. @ivar deferred: the L{Deferred} to callback or errback when the generator invocation has finished. @ivar waitingOn: the L{Deferred} being waited upon (which L{_inlineCallbacks} must fill out before returning) rbN waitingOn) r6r7r8rArNr:rr8rr3r3r3r4r7=s  r7genstatusc s^ddgt zt|t}|rtt|j}nj|}Wnty@}zj t |ddWYd}~dSd}~wt y}zt }|dusPJ|d}|dusZJ|j }|duscJtdkrq|j }|duspJn tr||j }|dus|J|r|j }|dusJ|j dusJ|j j r|}|dusJ|j dusJ|j j r|j }|dusJ|j j s|jjj} |j} |jdusJ|jdusJtd|jjj|jjjft| | j |jWYd}~dSd}~wtyjYdSwt|tr.dtd dffd d } || d r"d d <|_dSd}dd <dd<q)a5 Carry out the work of L{inlineCallbacks}. Iterate the generator produced by an C{@}L{inlineCallbacks}-decorated function, C{gen}, C{send()}ing it the results of each value C{yield}ed by that generator, until a L{Deferred} is yielded, at which point a callback is added to that L{Deferred} to call this function again. @param result: The last result seen by this generator. Note that this is never a L{Deferred} - by the time this function is invoked, the L{Deferred} has been called back and this will be a particular result at a point in its callback chain. @param gen: a generator object returned by calling a function or method decorated with C{@}L{inlineCallbacks} @param status: a L{_CancellationStatus} tracking the current status of C{gen} TNr`ror)zvreturnValue() in %r causing %r to exit: returnValue should only be invoked by functions decorated with inlineCallbacksr$r1cs0drdd<|d<dSt|dSr%)r5_inlineCallbacks)r$current_contextr9r:r(r3r4r)s z#_inlineCallbacks..gotResultrF)r;r\r*r5rthrowExceptionIntoGeneratorrrrbrOrr2r tb_nextr r%tb_framef_code co_filename tb_linenor warn_explicitco_namerrorWrTrNr:rr8) rKr9r: isFailureeexcInfor appCodeTrace ultimateTracefilenamelinenor)r3r>r4r=Ls!                r=csVdttddffdd t}t|dtdttffdd td||S) z Make an C{@}L{inlineCallbacks} cancellable. @param gen: a generator object returned by calling a function or method decorated with C{@}L{inlineCallbacks} @return: L{Deferred} for the C{@}L{inlineCallbacks} that is cancellable. itr1Ncs4g|j|_}||j||tdSr2)rrextendrT&_InternalInlineCallbacksCancelledError)rOtmp) handleCancelr3r4rs  z+_cancellableInlineCallbacks..cancelrKcs4|tt_j}|dusJ|jS)aS Propagate the cancellation of an C{@}L{inlineCallbacks} to the L{Deferred} it is waiting on. @param result: An L{_InternalInlineCallbacksCancelledError} from C{cancel()}. @return: A new L{Deferred} that the C{@}L{inlineCallbacks} generator can callback or errback through. N)rprQrNrbr8r)rKawaited)rr:r3r4rSs  z1_cancellableInlineCallbacks..handleCancel)rNr:r7r*r=)r9rbr3)rrSr:r4rs  rc@r>)rQz A unique exception used only in L{_cancellableInlineCallbacks} to verify that an L{inlineCallbacks} is being cancelled as expected. Nr@r3r3r3r4rQrBrQcr,)a L{inlineCallbacks} helps you write L{Deferred}-using code that looks like a regular sequential function. For example:: @inlineCallbacks def thingummy(): thing = yield makeSomeRequestResultingInDeferred() print(thing) # the result! hoorj! When you call anything that results in a L{Deferred}, you can simply yield it; your generator will automatically be resumed when the Deferred's result is available. The generator will be sent the result of the L{Deferred} with the 'send' method on generators, or if the result was a failure, 'throw'. Things that are not L{Deferred}s may also be yielded, and your generator will be resumed with the same object sent back. This means C{yield} performs an operation roughly equivalent to L{maybeDeferred}. Your inlineCallbacks-enabled generator will return a L{Deferred} object, which will result in the return value of the generator (or will fail with a failure object if your generator raises an unhandled exception). Note that you can't use C{return result} to return a value; use C{returnValue(result)} instead. Falling off the end of the generator, or simply using C{return} will cause the L{Deferred} to have a result of L{None}. Be aware that L{returnValue} will not accept a L{Deferred} as a parameter. If you believe the thing you'd like to return could be a L{Deferred}, do this:: result = yield result returnValue(result) The L{Deferred} returned from your deferred generator may errback if your generator raised an exception:: @inlineCallbacks def thingummy(): thing = yield makeSomeRequestResultingInDeferred() if thing == 'I love Twisted': # will become the result of the Deferred returnValue('TWISTED IS GREAT!') else: # will trigger an errback raise Exception('DESTROY ALL LIFE') It is possible to use the C{return} statement instead of L{returnValue}:: @inlineCallbacks def loadData(url): response = yield makeRequest(url) return json.loads(response) You can cancel the L{Deferred} returned from your L{inlineCallbacks} generator before it is fired by your generator completing (either by reaching its end, a C{return} statement, or by calling L{returnValue}). A C{CancelledError} will be raised from the C{yield}ed L{Deferred} that has been cancelled if that C{Deferred} does not otherwise suppress it. r/r0r1csRz |i|}Wntytdfwt|ts%td|ft|S)NzkinlineCallbacks requires %r to produce a generator; insteadcaught returnValue being used in a non-generatorzBinlineCallbacks requires %r to produce a generator; instead got %r)r2r r\r r)r/r0r9r-r3r4r.cs   z(inlineCallbacks..unwindGeneratorr/r0r3r-r4inlineCallbacks%s> rU_ConcurrencyPrimitiveT_ConcurrencyPrimitive)boundc @seZdZdeddfddZdedefddZd ed ed efd e d e de ef ddZ dede efddZ de de de de e fddZedede efddZedddZdS)rWrr1NcCs g|_dSr2)r(rr3r3r4rr3z_ConcurrencyPrimitive.__init__r$cCs ||Sr2)release)rr$r3r3r4_releaseAndReturnsz'_ConcurrencyPrimitive._releaseAndReturn%self_319AA2A8B18F4B8EA296D75F279EB07Fr..r/r0cs.dtdttffdd }|S)a Acquire, run, release. This method takes a callable as its first argument and any number of other positional and keyword arguments. When the lock or semaphore is acquired, the callable will be invoked with those arguments. The callable may return a L{Deferred}; if it does, the lock or semaphore won't be released until that L{Deferred} fires. @return: L{Deferred} of function result. ignoredResultr1cstgRijSr2)r]rrZ)r\r/r.r0r[r3r4rXsz*_ConcurrencyPrimitive.run..execute)r:rNrvacquirer)r[r.r/r0rXr3r]r4r5s z_ConcurrencyPrimitive.runcCr)zD We can be used as an asynchronous context manager. )r^rr3r3r4 __aenter__sz _ConcurrencyPrimitive.__aenter__exc_typeexc_valexc_tbcCs|tdS)NF)rYrR)rr`rarbr3r3r4 __aexit__sz_ConcurrencyPrimitive.__aexit__cCrr2r3rr3r3r4r^z_ConcurrencyPrimitive.acquirecCrr2r3rr3r3r4rYrdz_ConcurrencyPrimitive.releaser)r6r7r8rVrr=rZrrvr:rNr5r_rlrcrr^rYr3r3r3r4rW~s(   _DeferredLockT DeferredLockc@sVeZdZdZdZdedeeddfddZdedeefd d Zdeddfd d Z dS) rfz A lock for event driven systems. @ivar locked: C{True} when this Lock has been acquired, false at all other times. Do not change this value, but it is useful to examine for the equivalent of a "non-blocking" acquisition. FrrQr1NcC|j|dSa Remove a deferred d from our waiting list, as the deferred has been canceled. Note: We do not need to wrap this in a try/except to catch d not being in self.waiting because this canceller will not be called if d has fired. release() pops a deferred out of self.waiting and calls it, so the canceller will no longer be called. @param d: The deferred that has been canceled. Nr(removerr3r3r4_cancelAcquire zDeferredLock._cancelAcquirecCs6t|jd}|jr|j||Sd|_|||S)aL Attempt to acquire the lock. Returns a L{Deferred} that fires on lock acquisition with the L{DeferredLock} as the value. If the lock is locked, then the Deferred is placed at the end of a waiting list. @return: a L{Deferred} which fires on lock acquisition. @rtype: a L{Deferred} rT)rNrklockedr(rrOrr3r3r4r^s   zDeferredLock.acquirecCs>|jsJdd|_|jrd|_|jd}||dSdS)z Release the lock. If there is a waiting list, then the first L{Deferred} in that waiting list will be called back. Should be called by whomever did the L{acquire}() when the shared resource is free. z!Tried to release an unlocked lockFTrN)rnr(rrOrr3r3r4rYs zDeferredLock.release) r6r7r8rArnrerNrkr^rYr3r3r3r4rfs _DeferredSemaphoreTDeferredSemaphorec@sdeZdZdZdeddfddZdedeeddfd d Zdedeefd d Z deddfd dZ dS)rpa A semaphore for event driven systems. If you are looking into this as a means of limiting parallelism, you might find L{twisted.internet.task.Cooperator} more useful. @ivar limit: At most this many users may acquire this semaphore at once. @ivar tokens: The difference between C{limit} and the number of users which have currently acquired this semaphore. tokensr1NcCs*t||dkr td||_||_dS)ze @param tokens: initial value of L{tokens} and L{limit} @type tokens: L{int} r`z&DeferredSemaphore requires tokens >= 1N)rWr ValueErrorrqlimit)rrqr3r3r4r s  zDeferredSemaphore.__init__rrQcCrgrhrirr3r3r4rkrz DeferredSemaphore._cancelAcquirecCsN|jdks Jdt|jd}|js|j||S|jd|_|||S)zq Attempt to acquire the token. @return: a L{Deferred} which fires on token acquisition. rz9Internal inconsistency?? tokens should never be negativermr`)rqrNrkr(rrOrr3r3r4r^$s    zDeferredSemaphore.acquirecCsP|j|jks Jd|jd|_|jr&|jd|_|jd}||dSdS)z Release the token. Should be called by whoever did the L{acquire}() when the shared resource is free. z4Someone released me too many times: too many tokens!r`rN)rqrsr(rrOrr3r3r4rY5s   zDeferredSemaphore.release) r6r7r8rArrrorNrkr^rYr3r3r3r4rps   c@ eZdZdS) QueueOverflowNr6r7r8r3r3r3r4ruGruc@rt)QueueUnderflowNrvr3r3r3r4rxKrwrxc@sleZdZdZ ddeedeeddfddZdeeddfd d Z d e ddfd d Z dee fddZ dS) DeferredQueuea An event driven queue. Objects may be added as usual to this queue. When an attempt is made to retrieve an object when the queue is empty, a L{Deferred} is returned which will fire when an object becomes available. @ivar size: The maximum number of objects to allow into the queue at a time. When an attempt to add a new object would exceed this limit, L{QueueOverflow} is raised synchronously. L{None} for no limit. @ivar backlog: The maximum number of L{Deferred} gets to allow at one time. When an attempt is made to get an object which would exceed this limit, L{QueueUnderflow} is raised synchronously. L{None} for no limit. Nsizebacklogr1cCsg|_g|_||_||_dSr2)r(pendingrzr{)rrzr{r3r3r4r`s zDeferredQueue.__init__rQcCrg)a Remove a deferred d from our waiting list, as the deferred has been canceled. Note: We do not need to wrap this in a try/except to catch d not being in self.waiting because this canceller will not be called if d has fired. put() pops a deferred out of self.waiting and calls it, so the canceller will no longer be called. @param d: The deferred that has been canceled. Nrirr3r3r4 _cancelGethrlzDeferredQueue._cancelGetobjcCsL|jr|jd|dS|jdust|j|jkr#|j|dSt)zq Add an object to this queue. @raise QueueOverflow: Too many objects are in this queue. rN)r(rrOrzr r|rru)rr~r3r3r4putvs zDeferredQueue.putcCsR|jr t|jdS|jdust|j|jkr&t|jd}|j||St )a3 Attempt to retrieve and remove an object from the queue. @return: a L{Deferred} which fires with the next object available in the queue. @raise QueueUnderflow: Too many (more than C{backlog}) L{Deferred}s are already waiting for an object from this queue. rNrm) r|rRrr{r r(rNr}rrxrr3r3r4gets   zDeferredQueue.get)NN) r6r7r8rArrrrNr:r}r=rrr3r3r3r4ryOs  ryc@r>)AlreadyTryingToLockErrorz{ Raised when L{DeferredFilesystemLock.deferUntilLocked} is called twice on a single L{DeferredFilesystemLock}. Nr@r3r3r3r4rrBrc@sneZdZUdZdZdZeeed<dZ eeed<dde dee ddfd d Z dd ee dedfd d ZdS)DeferredFilesystemLockaj A L{FilesystemLock} that allows for a L{Deferred} to be fired when the lock is acquired. @ivar _scheduler: The object in charge of scheduling retries. In this implementation this is parameterized for testing. @ivar _interval: The retry interval for an L{IReactorTime} based scheduler. @ivar _tryLockCall: An L{IDelayedCall} based on C{_interval} that will manage the next retry for acquiring the lock. @ivar _timeoutCall: An L{IDelayedCall} based on C{deferUntilLocked}'s timeout argument. This is in charge of timing out our attempt to acquire the lock. r`N _tryLockCall _timeoutCallname schedulerr1cCs6tj|||durddlm}tt|}||_dS)z @param name: The name of the lock to acquire @param scheduler: An object which provides L{IReactorTime} Nr)reactor)r$FilesystemLockrtwisted.internetrrr" _scheduler)rrrrr3r3r4rs    zDeferredFilesystemLock.__init__recsfjdur ttdSdtttfddffdd tfddd fd d S) a Wait until we acquire this lock. This method is not safe for concurrent use. @param timeout: the number of seconds after which to time out if the lock has not been acquired. @return: a L{Deferred} which will callback when the lock is acquired, or errback with a L{TimeoutError} after timing out or an L{AlreadyTryingToLockError} if the L{deferUntilLocked} has already been called and not successfully locked the file. Nz/deferUntilLocked isn't safe for concurrent use.reasonr1csfjdusJjd_jdur!jr!jd_r,ddS|dS)z Cancel a L{DeferredFilesystemLock.deferUntilLocked} call. @type reason: L{Failure} @param reason: The reason why the call is cancelled. N)rrrrlockrOrTr)rQrr3r4 _cancelLocks  z._cancelLockcs tSr2)rCrd)rr3r4s z9DeferredFilesystemLock.deferUntilLocked..csrjdurjd_d_ddSdur8jdur8ttdjf}j |_j j _dS)Nz&Timed out acquiring lock: %s after %fs) rrrrrOr*rDrrr _intervalrr_tryLockrQrrer3r4rs$  z9DeferredFilesystemLock.deferUntilLocked.._tryLockr)rrUrrr*rrN)rrer3rr4deferUntilLockeds  z'DeferredFilesystemLock.deferUntilLockedr2)r6r7r8rArrrr!rrrr"rrrNrr3r3r3r4rs  r)rNrrRrUrrr?rDrr]rrr1rUr5rfrpryrrrCr2)rbrcr1N)FFr)F)rArrabcrrasynciorrrenumr functoolsrsysr r typesr r typingr rrrrrrrrrrrrrrrrrrattr incrementalr twisted.internet.interfacesr!r"twisted.loggerr#twisted.pythonr$twisted.python.compatr%r&r'twisted.python.deprecater(r)twisted.python.failurer*r+ contextvarsr,__copy_context_contextvarsSupport ImportErrorr-r;rHr=rr?rCrDr rErJrRrWrUr:rXr]rerirjrlrmrnrrqrrrsrtDeferredCallbackDeferredErrbackrrrrrurrvrxrzrNrrr_DeferredListSingleResultT_DeferredListResultItemTrrrrrrrr_DeferableGeneratorr&r1r2r5sr7r=rrQrUrVrWrerfrorprurxryrrr__all__r3r3r3r4s  T                    *~  +               @  E     2  T = ;KH f