Ϫf0UdZddlmZddlZddlZddlZddlmZmZddl m Z m Z m Z ddl mZmZddlmZddlmZdd lmZmZdd lmZmZmZmZdd lmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1ddl2Z2dd l3m4Z4dd lm5Z5m6Z6m7Z7m8Z8ddl9m:Z:m;Z;ddlm?Z?ddl@mAZAmBZBmCZCddlDmEZEmFZFddlGmHZHmIZIe=ZJe.dZKe7dZLeAxrejdkZNGddeOZPGddeOZQGddeOZRGddeSZTdqdZUdrd ZVdsdtd!ZW dud"ZXe1 dvd#ZYe1 dwd$ZYe1 dxd%ZY dyd&ZYeEe4d'd(d)dd*+dzd,ZZd{d-Z[d|d.Z\d}d/Z]d~d0Z^dd1Z_Gd2d3eZ`e`jZae`jZbe"d4ecfZde"d4ecfZee,ecd4fZfe(egecfZhe,e,e/ede6e`jfefehfe,e/eeede6e`jfefehffZieiZjd5ekd6<e.d7Zle.d8ZmGd9d:ZnGd;dd?eOZqe,elerfZse,etelfZue'euelZver>e1 d ddAZwe1 d ddBZw d ddCZwewZxGdDdEeoeve Zx d ddFZy d ddGZzGdHdIeOZ{ddJZ|dKZ}d@Z~GdLdMZe$ecddfZ ddNZeEe4d'dOdddP ddQZGdRdSeZddTZe2j dKUGdVdWe%elZ ddXZeI ddYZ ddZZ dd[Z dd\ZGd]d^eOZ dd_ZGd`daeZGdbdceZGdddeeZGdfdgeOZGdhdieOZGdjdke%eKZGdldmeOZGdndoe?j,ZgdpZy)zU Support for results that aren't immediately available. Maintainer: Glyph Lefkowitz ) annotationsN)ABCabstractmethod)AbstractEventLoopFuture iscoroutine)Context copy_context)Enumwraps)exc_infoimplementation) CoroutineType GeneratorTypeMappingProxyType TracebackType) TYPE_CHECKINGAny AwaitableCallable Coroutine GeneratorGenericIterableListMappingNoReturnOptionalSequenceTupleTypeTypeVarUnioncastoverload)Version) ConcatenateLiteral ParamSpecSelf) IDelayedCall IReactorTime)Logger)lockfile)_PYPYcmp comparable) deprecatedwarnAboutFunction)Failure _extraneous_T_P)ceZdZdZy)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. N__name__ __module__ __qualname____doc__8/usr/lib/python3/dist-packages/twisted/internet/defer.pyr=r=ArDr=ceZdZdZy)CancelledErrorzJ This error is raised by default when a L{Deferred} is cancelled. Nr>rCrDrErHrHHrDrHceZdZdZy) TimeoutErrorzG This error is raised by default when a L{Deferred} times out. Nr>rCrDrErKrKNrIrDrKceZdZdZy)NotACoroutineErrorzb This error is raised when a coroutine is expected and something else is encountered. Nr>rCrDrErMrMTrFrDrMc2tjd||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)errs rElogErrorrS[sKKC JrDc<t}|j||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. )Deferredcallbackresultds rEsucceedrZhsjAJJv HrDc<t}|j||S)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. )rUerrbackrWs rEfailr]|s zAIIf HrDc\ ||i|}t|S#t$r tcYSwxYw)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. )rZ BaseExceptionr])callableargskwargsrXs rEexecutercs:4*6*v v s ++cyNrCfrarbs rE maybeDeferredrhrDcyrerCrfs rErhrhs rDcyrerCrfs rErhrhrirDc8 ||i|}t |tr|St |tr t|St |turtj|S|}t|S#t$r&tttjcYSwxYw)a6 Invoke a function that may or may not return a L{Deferred} or coroutine. Call the given function with the given arguments. Then: - 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. - If the returned object is a L{types.CoroutineType}, wrap it with L{Deferred.fromCoroutine} 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) r_r]r5rUdebug isinstancetyper fromCoroutinerZ)rgrarbrXreturneds rErhrhs<9D#F#&(# FG $F| f &$%%f--x  9 9G7889sA**,BBTwistedz*twisted.internet.defer.Deferred.addTimeout) replacementcJ|jttdy)NzCallback timed out)r\r5rK)deferreds rEtimeoutrzs  W\*>?@ArDc|SrerCargs rEpassthrur~ JrDc|SrerCr|s rE _failthrurrrDc,t|t_y)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)boolrUro)ons rE setDebuggingrs"XHNrDc"tjS)z= Determine whether L{Deferred} debugging is enabled. )rUrorCrDrE getDebuggingrs >>rDcht|tr!|jtt |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 rU)rpr5traprHrK)valuerzs rE_cancelledToTimedOutErrorrs,%! >"7J// LrDc,eZdZdZeZeZy) _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)r?r@rArBobject _NO_RESULT _CONTINUErCrDrErr)s JIrDr._CallbackKeywordArguments _NONE_KWARGS _SelfResultT _NextResultTcLeZdZUdZdZded<dZded<dZded<d dZd d Z y) DebugInfoz Deferred debug helper. NzOptional[Failure] failResultzOptional[List[str]]creatorinvokercRd}|jF|dz }|dj|jjjddz }|dz }|jF|dz }|dj|jjjddz }|dz }|S)NrOz C: Deferred was created: C: z C:z I: First Invoker was: I:z I:)rjoinrstripreplacer)selfinfos rE_getDebugTracebackszDebugInfo._getDebugTracebacksds << # 4 4D BGGDLL)002::4I ID DLD << # 1 1D BGGDLL)002::4I ID DLD rDc|jQtjdd|j}|rd}nd}tj ||j|yy)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})rO) debugInfo)rrPcriticalrrQ)rrformats rE__del__zDebugInfo.__del__psW ?? & LL7L F002I/ KK9K E 'rDreturnstrrNone) r?r@rArBr__annotations__rrrrrCrDrErr[s5%)J!(#'G '#'G ' FrDrceZdZUdZdZdZdZded<dZdZ dZ dZ ded< d0 d1d Z dd e d e f d2d Ze d3d Ze d4d Ze d5dZe d6dZe d7dZe d8dZd9dZe d:dZe d;dZe ddZe d?dZe d@dZe dAdZe dBdZe dCdZe dDdZd9dZ d0 dEdZdFd ZdGd!Zd0dHd"ZdId#ZdId$ZdId%ZdJd&ZdKd'ZdId(ZdLd)ZeZdMd*Ze d0dNd+Z!dOd,Z"e!Z#dPd-Z$e%dQd.Z&e% dRd/Z'y)SrUa 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}. FrNzOptional[DebugInfo] _debugInfoz'Optional[Deferred[Any]]' _chainedTocg|_||_|jr6t|_t j dd|j_yy)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 _cancellerrorr traceback format_stackrr cancellers rE__init__zDeferred.__init__sC402# ::'kDO&/&<&<&>s&CDOO # rDrCc|t}|d}|i}|d}|i}t|sJt|sJ|jj|||f|||ff|jr|j |S)a Add a pair of callbacks (success and error) to this L{Deferred}. These will be executed when the 'master' callback is run. @note: The signature of this function was designed many years before PEP 612; ParamSpec provides no mechanism to annotate parameters like C{callbackArgs}; this is therefore inherently less type-safe than calling C{addCallback} and C{addErrback} separately. @return: C{self}. rC)rr`rappendcalled _runCallbacks)rrVr\ callbackArgscallbackKeywords errbackArgserrbackKeywordss rE addCallbackszDeferred.addCallbackssL ?G  L  #!   K  " O!!!    <)9:+7   ;;     rDcyrerCrrVrarbs rE addCallbackzDeferred.addCallback* rDcyrerCrs rErzDeferred.addCallback3 rDcyrerCrs rErzDeferred.addCallback?rrDcyrerCrs rErzDeferred.addCallbackHrrDcyrerCrs rErzDeferred.addCallbackQrrDcyrerCrs rErzDeferred.addCallback]rrDc*|j|||S)z^ Convenience method for adding just a callback. See L{addCallbacks}. )rrrrs rErzDeferred.addCallbackfs  v VVrDcyrerCrr\rarbs rE addErrbackzDeferred.addErrbackqrrDcyrerCrs rErzDeferred.addErrbackzrrDcyrerCrs rErzDeferred.addErrbackrrDc4|jt|||S)z^ Convenience method for adding just an errback. See L{addCallbacks}. )rr)rr~rs rErzDeferred.addErrbacks%  g4!  rDcyrerCrs rEaddBothzDeferred.addBothrrDcyrerCrs rErzDeferred.addBothrrDcyrerCrs rErzDeferred.addBoth rDcyrerCrs rErzDeferred.addBothrrDcyrerCrs rErzDeferred.addBothrrDcyrerCrs rErzDeferred.addBothrrDcyrerCrs rErzDeferred.addBothrrDc0|j||||||S)z Convenience method for adding a single callable as both a callback and an errback. See L{addCallbacks}. )rrrrrrs rErzDeferred.addBoths.   #" !  rDc dg d fd }|j| d fd }dfd }j|}|j|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 Fc0dd<jy)NTrcancel)rtimedOutsrE timeItOutz&Deferred.addTimeout..timeItOutsHQK KKMrDc8drxst}||S|S)Nr)r)rXtoCallonTimeoutCancelrrzs rEconvertCancelledz-Deferred.addTimeout..convertCancelled"s) {(E,Efg..MrDcHjrj|Sre)activer)rX delayedCalls rE cancelTimeoutz*Deferred.addTimeout..cancelTimeout,s !!#""$MrDr)rXUnion[_SelfResultT, Failure]rz*Union[_SelfResultT, _NextResultT, Failure])rXr7rr7) callLaterr) rrzclockrrrr convertedrrs `` ` @@rE addTimeoutzDeferred.addTimeoutsgN7 oogy9  0  7  BF B   //rDc\||_|j|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}. )rrrVr\rrYs rE chainDeferredzDeferred.chainDeferred:s&0   QYY77rDcJt|trJ|j|y)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)rprU_startRunCallbacks)rrXs rErVzDeferred.callbackUs".fh/// 'rDc|t|j}nt|ts t|}|j|y)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. Nrm)r5rorpr)rr]s rEr\zDeferred.errbackos9@ <tzz2DD'*4=D %rDc,|jdz|_y)zP Stop processing on a L{Deferred} until L{unpause}() is called. rvN)pausedrs rEpausezDeferred.pauseskkAo rDc|jdz |_|jry|jr|jyy)zI Process all callbacks made since L{pause}() was called. rvN)rrrrs rEunpausezDeferred.unpauses5kkAo ;;  ;;     rDc"|jsN|j}|r ||nd|_|js#|jt t yyt |jtr|jjyy)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_suppressAlreadyCalledr\r5rHrprXrUrrs rErzDeferred.cancelso{{I$/3+;; W^%567 X . KK   /rDc|jri|jrd|_y|jrC|jt |_d|jj z}t |t |jrA|jt |_tjdd|j_ d|_d|_ ||_ |jy)NFrT) rrrorrrr=rrrrrXr)rrXextras rErzDeferred._startRunCallbackss ;;**.3+zz??*&/kDOtBBDD(//$ $ ::&"++&/&<&<&>s&CDOO #   rDcbtj|ftftj|ftffS)zT Build a tuple of callback and errback with L{_Sentinel._CONTINUE}. )rrrrs rE _continuationzDeferred._continuations2  4'< 8  4'< 8  rDcb|jry|g}|r|d}|jryd}d|_|jr|jj d}t |j ts |d\}}}n |d\}}}|turyttt|d}|j |_d|_|jd|j_ |xjdzc_|j|d}nV d|_ ||j g|i||_|j |ur t|dd|_ t |j trt!|j dt"} | t"us&t | ts|j jrU|j%|j |_|j jj|j'nXd|j _|j jd|j j_ | |_ |jr|rt |j trQ|j j-|jt/|_ |j |j_ n|jd|j_ |j |ryy#d|_wxYw#t($rt|j* |_YwxYw) 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. NrTrrvFz|Callback returned the Deferred it was attached to; this breaks the callback chain and will raise an exception in the future.rXrm)_runningCallbacksrrrpoprprXr5rr%rUrrrrr4getattrrrrr_ro cleanFailurer) rchaincurrentfinisheditemrVrarbchainee resultResults rErzDeferred._runCallbackss4  ! ! '+VBiG~~H!%G ##((,,Q/!'..':-1!W*HdF.2!W*HdFy(#8F#3T!W=G%,^^GN%)GN))58<**5NNa'NLL) %H4:04G-:*2#NN*-1*5;*#>>W4- (!;5:1 "'..(;(/w~~x'T (J6),A&~~44$MMO18G. $NN44;;G) __class__r?rridr)rcnamerXmyIDs rE__str__zDeferred.__str__ys''x4$x ?? &1"T__2Ea1HIF z !F( 3F5'Qxxq11rDc|SrerCrs rE__iter__zDeferred.__iter__s rDc|jr|St|dt}|tur|St|tr<|j Jd|j _||j_|jt|)NrX) rrrrpr5rrr __failure__ StopIteration)rrrXs rEsendz Deferred.sendsr ;;Kx4 Z K fg &??. ..)-DOO &'-FLL $,, ' 'rDc"|jSre)rrs rE __await__zDeferred.__await__s}}rDc|jdfd }dfd }dfd }j||j|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. cH|jrjyyre) cancelledr) futureAgainrs rE checkCancelz&Deferred.asFuture..checkCancels$$& 'rDc^jsj|jyyre)r# set_exceptionr)rQfutures rE maybeFailz$Deferred.asFuture..maybeFails&##%$$W]]3&rDcJjsj|yyre)r# set_result)rXr(s rE maybeSucceedz'Deferred.asFuture..maybeSucceeds"##%!!&)&rD)r$'Future[_SelfResultT]'rr)rQr5rrrXrrr) create_futureradd_done_callback)rloopr%r)r,r(s` @rEasFuturezDeferred.asFuturesG##%  4 * , 2  - rDcdfd }tdfd }||}| dfd }|j|j||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. c| |j}j|y#t$r t}Y'wxYwre)rXr_r5rV)rX extractedactuals rEadaptz"Deferred.fromFuture..adapts9 &4:MMO  OOI &! &#I  &s %;;cHj|jyrerrV)reselfr( futureCancels rErz#Deferred.fromFuture..cancels MMO OOL )rDc(|ur tS|Sre)rU)rXr6r;s rEuncancelz%Deferred.fromFuture..uncancels%! MrD)rXzFuture[_SelfResultT]rr)r:Deferred[object]rr)rXrrz+Union[_SelfResultT, Deferred[_SelfResultT]])rrr0)clsr(r7rrr=r6r;s ` @@rE fromFuturezDeferred.fromFutures^( 'x  *6{    8  "  ' rDctt|stj|r t|St |d)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)rinspect isgenerator_cancellableInlineCallbacksrM)r?coros rErrzDeferred.fromCoroutines8\ t  3 3D 9.t4 4 D8+>!?@@rDre)rz+Optional[Callable[['Deferred[Any]'], None]]rr)rVzUnion[Callable[..., _NextResultT], Callable[..., Deferred[_NextResultT]], Callable[..., Failure], Callable[..., Union[_NextResultT, Deferred[_NextResultT], Failure]]]r\zUnion[Callable[..., _NextResultT], Callable[..., Deferred[_NextResultT]], Callable[..., Failure], Callable[..., Union[_NextResultT, Deferred[_NextResultT], Failure]], None]rzTuple[Any, ...]rzMapping[str, Any]r_CallbackOrderedArgumentsrrrz'Deferred[_NextResultT]')rVz0Callable[Concatenate[_SelfResultT, _P], Failure]ra_P.argsrb _P.kwargsrDeferred[_NextResultT])rVzOCallable[Concatenate[_SelfResultT, _P], Union[Failure, Deferred[_NextResultT]]]rarGrbrHrrI)rVzECallable[Concatenate[_SelfResultT, _P], Union[Failure, _NextResultT]]rarGrbrHrrI)rVz?Callable[Concatenate[_SelfResultT, _P], Deferred[_NextResultT]]rarGrbrHrrI)rVzTCallable[Concatenate[_SelfResultT, _P], Union[Deferred[_NextResultT], _NextResultT]]rarGrbrHrrI)rVz5Callable[Concatenate[_SelfResultT, _P], _NextResultT]rarGrbrHrrI)rVrrarrbrr'Deferred[Any]')r\z:Callable[Concatenate[Failure, _P], Deferred[_NextResultT]]rarGrbrHr-'Deferred[Union[_SelfResultT, _NextResultT]]')r\z+Callable[Concatenate[Failure, _P], Failure]rarGrbrHrz'Deferred[Union[_SelfResultT]]')r\z0Callable[Concatenate[Failure, _P], _NextResultT]rarGrbrHrrK)r\rrarrbrrrJ)rVz@Callable[Concatenate[Union[_SelfResultT, Failure], _P], Failure]rarGrbrHrrI)rVz_Callable[Concatenate[Union[_SelfResultT, Failure], _P], Union[Failure, Deferred[_NextResultT]]]rarGrbrHrrI)rVzUCallable[Concatenate[Union[_SelfResultT, Failure], _P], Union[Failure, _NextResultT]]rarGrbrHrrI)rVzOCallable[Concatenate[Union[_SelfResultT, Failure], _P], Deferred[_NextResultT]]rarGrbrHrrI)rVzdCallable[Concatenate[Union[_SelfResultT, Failure], _P], Union[Deferred[_NextResultT], _NextResultT]]rarGrbrHrrI)rVzECallable[Concatenate[Union[_SelfResultT, Failure], _P], _NextResultT]rarGrbrHrrI)rVz!Callable[Concatenate[_T, _P], _T]rarGrbrHrDeferred[_SelfResultT])rzfloatrr-rzWOptional[Callable[[Union[_SelfResultT, Failure], float], Union[_NextResultT, Failure]]]rrK)rY'Deferred[_SelfResultT]'rz'Deferred[None]')rXrrr)r]'Optional[Union[Failure, BaseException]]rrrr.)r_CallbackChainr)rrN)rrrrN)rz"Generator[Any, None, _SelfResultT])r1rrr-)r(r-rrN)rEzKUnion[Coroutine[Deferred[Any], Any, _T], Generator[Deferred[Any], Any, _T]]r'Deferred[_T]')(r?r@rArBrrrrrrrorrrrr&rrrrrrVr\rrrrrrr__repr__rr6rr __next__r2 classmethodr@rrrCrDrErUrUs^"HF F&*J#*"  E,0J)0HLDDD Dh (*.:135A1B B  B*&+B,,-B.//B031B2 "3B` B                     W       Q                     G       W K    7    <    )    A    7      R                                                       W       3       8 E0E0E0 E0 7E0N86(4%&N& !!80 Tl 2H((0H D//b/A /A  /A/ArDrUct|tr|S tj|S#t$rt|dwxYw)a Schedule the execution of a coroutine that awaits/yields from L{Deferred}s, wrapping it in a L{Deferred} that will fire on success/failure of the coroutine. If a Deferred is passed to this function, it will be returned directly (mimicking the L{asyncio.ensure_future} function). See L{Deferred.fromCoroutine} for examples of coroutines. @param coro: The coroutine object to schedule, or a L{Deferred}. z! is not a coroutine or a Deferred)rprUrrrM)rEs rEensureDeferredrV2sP"$!  S))$/ /! S%x/P%QR R Ss )Ac0eZdZdZddZddZddZd dZy) FirstErrorz First error to occur in a L{DeferredList} if C{fireOnOneErrback} is set. @ivar subFailure: The L{Failure} that occurred. @ivar index: The index of the L{Deferred} in the L{DeferredList} where it happened. cNtj|||||_||_yre) Exceptionr subFailureindex)rrQr\s rErzFirstError.__init__Xs"4%0! rDcLd|j|jjfzS)z The I{repr} of L{FirstError} instances includes the repr of the wrapped failure's exception and the index of the L{FirstError}. zFirstError[#%d, %r])r\r[rrs rErRzFirstError.__repr__]s" % DOO4I4I'JJJrDc8d|j|jfzS)z The I{str} of L{FirstError} instances includes the I{str} of the entire wrapped failure (including its traceback and exception) and the index of the L{FirstError}. zFirstError[#%d, %s])r\r[rs rErzFirstError.__str__ds % DOO'DDDrDct|tr8t|j|jf|j|jfSy)a+ Comparison between L{FirstError} and other L{FirstError} instances is defined as the comparison of the index and sub-failure of each instance. L{FirstError} instances don't compare equal to anything that isn't a L{FirstError} instance. @since: 8.2 r)rprXr1r\r[)rothers rE__cmp__zFirstError.__cmp__ls: eZ ( DOO4u{{EDTDT6UV VrDN)rQr5r\intrrr)r`rrrb)r?r@rArBrrRrrarCrDrErXrXNs KE rDrXFcyrerC deferredListfireOnOneCallbackfireOnOneErrback consumeErrorss rE _DeferredListrirrDcyrerCrds rEririrrDcyrerCrds rEririrrDcVeZdZdZdZdZ d ddZ d dZd dZy) DeferredLista) L{DeferredList} is a tool for collecting the results of several Deferreds. This tracks a list of L{Deferred}s for their results, and makes a single callback when they have all completed. By default, the ultimate result is a list of (success, result) tuples, 'success' being a boolean. L{DeferredList} exposes the same API that L{Deferred} does, so callbacks and errbacks can be added to it in the same way. L{DeferredList} is implemented by adding callbacks and errbacks to each L{Deferred} in the list passed to it. This means callbacks and errbacks added to the Deferreds before they are passed to L{DeferredList} will change the result that L{DeferredList} sees (i.e., L{DeferredList} is not special). Callbacks and errbacks can also be added to the Deferreds after they are passed to L{DeferredList} and L{DeferredList} may change the result that they see. See the documentation for the C{__init__} arguments for more information. @ivar _deferredList: The L{list} of L{Deferred}s to track. Fct||_dgt|jz|_ tj |t|jdk(r|s|j g||_||_||_ d|_ d}|jD]<}|j|j|j|tf|tf|dz}>y)aj Initialize a DeferredList. @param deferredList: The deferreds to track. @param fireOnOneCallback: (keyword param) a flag indicating that this L{DeferredList} will fire when the first L{Deferred} in C{deferredList} fires with a non-failure result without waiting for any of the other Deferreds. When this flag is set, the DeferredList will fire with a two-tuple: the first element is the result of the Deferred which fired; the second element is the index in C{deferredList} of that Deferred. @param fireOnOneErrback: (keyword param) a flag indicating that this L{DeferredList} will fire when the first L{Deferred} in C{deferredList} fires with a failure result without waiting for any of the other Deferreds. When this flag is set, if a Deferred in the list errbacks, the DeferredList will errback with a L{FirstError} failure wrapping the failure of that Deferred. @param consumeErrors: (keyword param) a flag indicating that failures in any of the included L{Deferred}s should not be propagated to errbacks added to the individual L{Deferred}s after this L{DeferredList} is constructed. After constructing the L{DeferredList}, any 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 does not prevent C{fireOnOneErrback} from working. Nrrrrv)list _deferredListlen resultListrUrrVrfrgrh finishedCountr _cbDeferredSUCCESSFAILURE)rrerfrgrhr\rys rErzDeferredList.__init__sB",/ KORU   S J   $ t!! "a '0A MM"  "3 0*** H  ! !    #W-"G, "  AIE rDc$||f|j|<|xjdz c_|js|tk(r |jr|j ||fn|t k(rC|jr7t|tsJ|jtt||nR|jt|jk(r0|j ttt|j|t k(r |j ry|S)zI (internal) Callback for when one of my deferreds fires. rvN)rsrtrrvrfrVrwrgrpr5r\rXrrr%_DeferredListResultListTrrh)rrXr\ succeededs rEruzDeferredList._cbDeferreds #,V!4 a{{G#(>(> vuo.g%$*?*?!&'222 WZ%>?@##s4??';; d#;C#@$//RS  D$6$6 rDc|js#|jD]} |jyy#t$rtj dY8wxYw)a Cancel this L{DeferredList}. If the L{DeferredList} hasn't fired yet, cancel every L{Deferred} in the list. If the L{DeferredList} has fired, including the case where the C{fireOnOneCallback}/C{fireOnOneErrback} flag is set and the L{DeferredList} fires because one L{Deferred} in the list fires with a non-failure/failure result, do nothing in the C{cancel} method. z-Exception raised from user supplied cancellerN)rrqrr_rPrQ)rrys rErzDeferredList.cancel sW{{ .. QQOO% Q%QKK OPQs1AANFFF)re Iterable[Deferred[_SelfResultT]]rfrrgrrhr)rXrr\rbrzrrzOptional[_SelfResultT]r) r?r@rArBrfrgrrurrCrDrErmrms|, #(!&# D6D D D  DL"+.;? 4QrDrmc\ |D]}|J|\}}|rJ|Dcgc]}|d c}Scc}w)NrvrC)rsrgrXsuccessrrs rE_parseDeferredListResultr4sL  F% %%#NGUN7 % %QAaD %% %s )cDt|d|jtS)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)rgrh)rmrr)rerhs rE gatherResultsr?s#0 t= k*+,rDc$eZdZdZdfd ZxZS) FailureGroupz) More than one failure occurred. c8tt| ||_yre)superrrfailures)rrrs rErzFailureGroup.__init__as lD*,  rD)rzSequence[Failure]rr)r?r@rArBr __classcell__)rs@rErr\s!!rDrc d dfd }t|d fd }gd fd }t|t|D]\}}|j|||f|fS) aV Select the first available result from the sequence of Deferreds and cancel the rest. @return: A cancellable L{Deferred} that fires with the index and output of the element of C{ds} to have a success result first, or that fires with L{FailureGroup} holding a list of their failures if they all fail. Nc4D]}|jyrer)rXrY to_cancels rErzrace..cancelxs  A HHJ rDrct5|D]}|us|jj||fyyrer9) this_output this_indexrY final_resultrwinners rErzzrace..succeededsO >z*F F?HHJ   ! !:{"; < rDcj||fttk(r?jDcgc]\}}| }}}jt |yycc}}wre)rrrsortr\r)rQrignoredrgr failure_staterrs rEfailedzrace..failedsgj'23 } Y /    .;rr)rr) r?r@rArBrrXrrrrCrDrErrsFC rDrcd}ddg t}t |t rttdSt |trPtt|f dfd }|jj|drdd<Sdd<dd<d}#t$rj|cYSt$rj cYSwxYw) rNTrvz Yield waitForDeferred(d), not d!cL||_dr dd<|d<yty)NrFrv)rX_deferGenerator)rrXrygwaitings rE gotResultz"_deferGenerator..gotResults/!" 1:!&GAJ!"GAJ#Ax0rDrF)rrrXrrr) nextrrVr_r\rprUr]rrr%rYr)rryrXrrs`` @rErrsFG  !WF fh ' "DEF F fo . 6:/65R 1 1#2 1 1 HH  Y 'qz# GAJGAJFS     f %O     O s BC:CCz&twisted.internet.defer.inlineCallbacksc0tdfd }|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}. c8t|i|tSre)rrU)rarbrgs rEunwindGeneratorz*deferredGenerator..unwindGeneratorWsq$1&18:>>rD)rarrbrrr>r rgrs` rEdeferredGeneratorrs$x 1X?? rDceZdZddZy)_DefGen_Returnc||_yre)r)rrs rErz_DefGen_Return.__init__bs  rDN)rrrr)r?r@rArrCrDrErrasrDrct|)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. )r)vals rE returnValuerfs  rD) auto_attribsc*eZdZUdZded<dZded<y)_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) rLryNz Optional[Deferred[_SelfResultT]] waitingOn)r?r@rArBrrrCrDrErrvs%$26I/6rDrc@|dr d|d<||d<yt||||y)a Helper for L{_inlineCallbacks} to handle a nested L{Deferred} firing. @param r: The result of the L{Deferred} @param waiting: Whether the L{_inlineCallbacks} was waiting, and the result. @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} @param context: the contextvars context to run `gen` in rFrvN)_inlineCallbacks)rrgenstatuscontexts rE_gotResultInlineCallbacksrs+(qz  C1rDcDddg}d}d} t|t}|r+|jtt|j|}n|j|j |}|r|j,j1|yt|t2r:|j5t6|||||d r d|d <||_y|d}d|d <d|d<#t $r}d}t|dd}Yd}~d}~wt$r}t} | J| d} | J| j} | Jtr| j} | Jr| j} | J| jJ| jjr| } | J| jJ| jjr'| j} | J| jjr'| jjj} | j}| jJ| jJt!j"d| jjj$d| jjj$d t&| |d}|j(}Yd}~d}~wt*$r|j,j/YywxYw) ar 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} @param context: the contextvars context to run `gen` in TNFrvrrzreturnValue() in z causing zX to exit: returnValue should only be invoked by functions decorated with inlineCallbacksr)rpr5runr%throwExceptionIntoGeneratorrrrrrtb_next _oldPypyStacktb_framef_code co_filename tb_linenor warn_explicitco_namerrr_ryr\rVrUrrr)rXrrrr stopIteration callbackValue isFailureeexcInfor appCodeTrace ultimateTracefilenamelinenos rErrsHGMM Z "673I &)EEs!SXXv6f  OO $ $] 3  fh ' NN4gsFG Tqz# #) QZF GAJGAJk  6 M#Aw5MG $jG& && I( (($,,L+ ++ ,33 #/// ,33 #/// ''3 33##++ !- $000$,,888#++33$1$9$9M(444$++33)1188DD&00$--999#,,888&& &..55==$--44<< ' !MGGM  OO # # %  s2AC JC** J7CI6;B5I66&JJcg|jc|_}|jt|}|jj||j t y)z Helper for L{_cancellableInlineCallbacks} to add L{_handleCancelInlineCallbacks} as the first errback. @param it: The L{Deferred} to add the errback to. @param status: a L{_CancellationStatus} tracking the current status of C{gen} N)rr_handleCancelInlineCallbacksextendr\&_InternalInlineCallbacksCancelledError)itrtmps rE_addCancelCallbackToDeferredrAsIBLLBL# 3V z._handleCancelInlineCallbacks.._s)Ea)PrD)rrrUryrr)rXrawaiteds ` rErrQsL KK67PQFOG    NN ??rDcftfd}t|td|t|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. ct|Srerrs rErz-_cancellableInlineCallbacks..ys0LQPV0WrDN)rUrr _copy_context)rryrs @rErDrDjs/&&WXH  *FT3 8 OrDceZdZdZy)rz A unique exception used only in L{_cancellableInlineCallbacks} to verify that an L{inlineCallbacks} is being cancelled as expected. Nr>rCrDrErrrFrDrc0tdfd }|S)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. c |i|}t|tstdd|t |S#t$rtddwxYw)NzinlineCallbacks requires zP to produce a generator; insteadcaught returnValue being used in a non-generatorz% to produce a generator; instead got )rrrprrD)rarbrrgs rErz(inlineCallbacks..unwindGeneratorsn T$V$C #}-$%s, +3// FGJ  s 7A)rarGrbrHrrr rs` rEinlineCallbacksrs$| 1X 0 0 rDceZdZd dZd dZe ddZe ddZe ddZ ddZddZ ddZe dd Z e dd Z y )_ConcurrencyPrimitivecg|_yre)rrs rErz_ConcurrencyPrimitive.__init__s -/ rDc&|j|Sre)release)rrs rE_releaseAndReturnz'_ConcurrencyPrimitive._releaseAndReturns rDcyrerCrrgrarbs rErz_ConcurrencyPrimitive.run rDcyrerCrs rErz_ConcurrencyPrimitive.runrrDcyrerCrs rErz_ConcurrencyPrimitive.runs rDcZdfd }jj|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. cTtgijjSre)rhrr) ignoredResultrargrbrs rErcz*_ConcurrencyPrimitive.run..execute s0!4T4V4<<&& rD)rrrr)acquirer)rrgrarbrcs```` rErz_ConcurrencyPrimitive.runs&*  ||~))'22rDc"|jS)zD We can be used as an asynchronous context manager. )rrs rE __aenter__z _ConcurrencyPrimitive.__aenter__ s||~rDc8|jtdS)NF)rrZ)r_ConcurrencyPrimitive__exc_type _ConcurrencyPrimitive__exc_value _ConcurrencyPrimitive__tracebacks rE __aexit__z_ConcurrencyPrimitive.__aexit__" s u~rDcyrerCrs rErz_ConcurrencyPrimitive.acquire-  rDcyrerCrs rErz_ConcurrencyPrimitive.release1 rrDNrr+rr)rr7rr7) rgCallable[_P, Deferred[_T]]rr+rarGrbrHrr) rg/Callable[_P, Coroutine[Deferred[Any], Any, _T]]rr+rarGrbrHrr) rgCallable[_P, _T]rr+rarGrbrHrr) rgHCallable[_P, Union[Deferred[_T], Coroutine[Deferred[Any], Any, _T], _T]]rr+rarGrbrHrrrr+rDeferred[Self])rzOptional[Type[BaseException]]rzOptional[BaseException]rzOptional[TracebackType]rzDeferred[Literal[False]]r) r?r@rArrr&rrrrrrrCrDrErrs^0  &           ;          *  3: FO   3 T33 3  3  3< 1 - -  "     rDrc,eZdZdZdZddZddZd dZy) DeferredLockz 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. Fc:|jj|ya 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. Nrremovers rE_cancelAcquirezDeferredLock._cancelAcquireA  ArDct|j}|jr|jj ||Sd|_|j ||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)rUrlockedrrrVrs rErzDeferredLock.acquireO sN%t/B/BC ;; LL   "DK JJt rDc|jsJdd|_|jr4d|_|jjd}|j|yy)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)rrrrVrs rErzDeferredLock.release` sP{{???{ <<DK   #A JJt  rDNrr+rYrrrr r)r?r@rArBrrrrrCrDrErr6 sF "rDrc0eZdZdZddZddZd dZd dZy) DeferredSemaphorea 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. cjtj||dkr td||_||_y)ze @param tokens: initial value of L{tokens} and L{limit} @type tokens: L{int} rvz&DeferredSemaphore requires tokens >= 1N)rr ValueErrortokenslimit)rrs rErzDeferredSemaphore.__init__~ s3 &&t, A:EF F  rDc:|jj|yrrrs rErz DeferredSemaphore._cancelAcquire rrDc|jdk\sJdt|j}|js|jj ||S|jdz |_|j ||S)zq Attempt to acquire the token. @return: a L{Deferred} which fires on token acquisition. rz9Internal inconsistency?? tokens should never be negativerrv)rrUrrrrVrs rErzDeferredSemaphore.acquire st KK1  G F G $t/B/BC{{ LL   "++/DK JJt rDc|j|jksJd|jdz|_|jrA|jdz |_|jjd}|j |yy)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!rvrN)rr rrrVrs rErzDeferredSemaphore.release sp KK$** $ B A B $kkAo <<++/DK   #A JJt  rDN)rrbrrrr r)r?r@rArBrrrrrCrDrErrq s   "rDrc eZdZy) QueueOverflowNr?r@rArCrDrEr%r% rDr%c eZdZy)QueueUnderflowNr&rCrDrEr)r) r'rDr)c>eZdZdZ d ddZd dZd dZd dZy) 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. Nc<g|_g|_||_||_yre)rpendingsizebacklog)rr.r/s rErzDeferredQueue.__init__ s ,. !#   rDc:|jj|y)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. Nrrs rE _cancelGetzDeferredQueue._cancelGet rrDc|jr+|jjdj|y|j"t |j |jkr|j j |yt)zq Add an object to this queue. @raise QueueOverflow: Too many objects are in this queue. rN)rrrVr.rrr-rr%)robjs rEputzDeferredQueue.put s` << LL  Q  ( ( - YY #dll"3dii"? LL   $/ !rDc8|jr$t|jjdS|j"t |j |jkr3t |j}|j 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. rr) r-rZrr/rrrrUr1rr)rs rEgetzDeferredQueue.get sq <<4<<++A./ / \\ !S%6%E&AA LL   "H " "rD)NN)r. Optional[int]r/r7rr)rYrrr)r3r7rr)rr)r?r@rArBrr1r4r6rCrDrEr+r+ s:"DH!3@   "#rDr+ceZdZdZy)AlreadyTryingToLockErrorz{ Raised when L{DeferredFilesystemLock.deferUntilLocked} is called twice on a single L{DeferredFilesystemLock}. Nr>rCrDrEr9r9 rFrDr9cFeZdZUdZdZdZded<dZded<d d dZd d dZ y) 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. rvNzOptional[IDelayedCall] _tryLockCall _timeoutCallctjj|||ddlm}t t |}||_y)z @param name: The name of the lock to acquire @param scheduler: An object which provides L{IReactorTime} Nr)reactor)r/FilesystemLockrtwisted.internetr?r%r- _scheduler)rname schedulerr?s rErzDeferredFilesystemLock.__init__$ s6 ((t4   0\73I#rDcjttdSdfd tfddfd 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. z/deferUntilLocked isn't safe for concurrent use.cXjJjjd_j;jjr!jjd_j rj dyj |y)z Cancel a L{DeferredFilesystemLock.deferUntilLocked} call. @type reason: L{Failure} @param reason: The reason why the call is cancelled. N)r<rr=rlockrVr\)reasonrYrs rE _cancelLockz._cancelLockF s$$0 00    $ $ & $D   ,1B1B1I1I1K!!((*$(!yy{ 4  &!rDc$tSre)rH)ryrIs rErz9DeferredFilesystemLock.deferUntilLocked..Y sk.BR6SrDcjrFj!jjd_d_j dyQjEt t djfz}jj|_jjj_y)Nz&Timed out acquiring lock: %s after %fs) rGr=rr<rVr5rKrCrBr _interval)rHrI_tryLockrYrrzs rErMz9DeferredFilesystemLock.deferUntilLocked.._tryLock[ syy{$$0%%,,.(,D%$(! 4 &4+<+<+D$$D#yy'23F )-(A(Af)D%%)OO$=$=dnnh$W!rD)rHzUnion[Failure, Exception]rrr)r<r]r9rU)rrzrIrMrYs``@@@rEdeferUntilLockedz'DeferredFilesystemLock.deferUntilLocked2 sS    ((E   "&%%ST X X.  rDre)rCrrDzOptional[IReactorTime]rr)rzzOptional[float]rzDeferred[None]) r?r@rArBrLr<rr=rrNrCrDrEr;r; s/ I+/L(/+/L(/ $BrDr;)rUrmrZr]rwrvr=rKrrhrVrrrrrrr+r;r9rH)rRr5rr5)rXr7rrQre)rXrOrrJ)r`r rarGrbrHrrQ)rgr rarGrbrHrrQ)rgr rarGrbrHrrQ)rgr rarGrbrHrrQ)rgr rarGrbrHrrQ)ryz'Deferred[object]'rr)r}r7rr7)r}r5rr5)rrrr)rr)rr7rzrMrr7)rEzYUnion[Coroutine[Deferred[Any], Any, _T], Generator[Deferred[Any], Any, _T], Deferred[_T]]rr)FF) rer}rfz Literal[True]rgrrhrrz2Deferred[_DeferredListSingleResultT[_SelfResultT]]r|) rer}rfzLiteral[False]rgrrhrrz0Deferred[_DeferredListResultListT[_SelfResultT]]) rer}rfrrgrrhrrzkUnion[Deferred[_DeferredListSingleResultT[_SelfResultT]], Deferred[_DeferredListResultListT[_SelfResultT]]])F)rsz"List[_DeferredListResultItemT[_T]]rgrrzList[_T])rezIterable[Deferred[_T]]rhrrzDeferred[List[_T]])rzSequence[Deferred[_T]]rzDeferred[tuple[int, _T]])r_DeferableGeneratorryr>rz Deferred[Any])rgz"Callable[..., _DeferableGenerator]rzCallable[..., Deferred[object]])rrrr) rrrz List[Any]rKUnion[Generator[Deferred[Any], Any, _T], Coroutine[Deferred[Any], Any, _T]]r_CancellationStatus[_T]r_Contextrr) rXrrrPrrQrrRrr)rrrrQrr)rXr5rrQrr)rzQUnion[Generator[Deferred[Any], object, _T], Coroutine[Deferred[Any], object, _T]]rr)rgz/Callable[_P, Generator[Deferred[Any], Any, _T]]rr )rB __future__rrBrrabcrrasynciorrr contextvarsr rRr renumr functoolsr sysrrtypesrrrrtypingrrrrrrrrrrrrr r!r"r#r$r%r&attr incrementalr'r(r)r*r+twisted.internet.interfacesr,r-twisted.loggerr.twisted.pythonr/twisted.python.compatr0r1r2twisted.python.deprecater3r4twisted.python.failurer5r6rPr7r8versionrrZr=rHrKrrMrSrZr]rcrhrzr~rrrrrrrrDeferredCallbackDeferredErrbackrFrrrPrrrrrrUrVrXrb_DeferredListSingleResultTr_DeferredListResultItemTryrirmrrrrrvrwrrOrrr_rrsrrrrrrDrrrrrr%r)r+r9r@r;__all__rCrDrErks2  ##::J(OO, 88B!#88B7 h T]t_=.00:= Y 9   (  '.:C$ !*1=F   6     '3<  <!O<! <!<! <!~  Ir1a <B B(  " ! !    CK(3;'!&#+.#CK0   (;(; <<=!! #   o/9L9L1MMN!! #  +;2*> '>~& ~& 'F'FTjAy&jAZS S  S8 (( (V#<#45 |!34 8 FG "'#  6 (    <   -2!&#  6 )    :   #(!&#  6           !LMQ %c *+MQbNS&2&FJ& &AF,(,9=,,:!9!L`  : d 23==&6==@ GIr1a (*RS?)?$?T?J]  T 7',/ 7 72 2 2 2 $22 26 ] ] ] $ ]] ] ]@ 9 95 9  9  42   .YN6NNhW CW t8(8vF-FR I  Y E#GBKE#PycX44cL rD