U
    ,0[                    @   s  d Z ddlmZmZmZ ddlZddlZddlZddlZddl	m
Z
mZ ddlmZ ddlmZ ddlmZmZ ddlmZmZ dd	lmZ dd
lmZmZ ddlmZ e ZG dd deZG dd deZ G dd deZ!dd Z"dd Z#dcddZ$dd Z%dd Z&eedddddd d!d" Z'd#d$ Z(d%d& Z)d'd( Z*e+ Z,e+ Z-eG d)d* d*Z.d+d, Z/d-d. Z0eG d/d0 d0Z1eG d1d2 d2eZ2G d3d4 d4e.Z3ddd6d7Z4ded8d9Z5d:Z6d5Z7eG d;d< d<Z8d=d> Z9eedd?ddd@dAdB Z:G dCdD dDe;Z<dEdF Z=ej>G dGdH dHe+Z?ej@dIdJ ZAdKdL ZBG dMdN dNeZCdOdP ZDG dQdR dRe+ZEG dSdT dTeEZFG dUdV dVeEZGG dWdX dXeZHG dYdZ dZeZIG d[d\ d\e+ZJG d]d^ d^eZKG d_d` d`ejLZMd*d4dddadbddd9dd.d<dBdPdFdTdVd\d`d^dgZNdS )fa  
Support for results that aren't immediately available.

Maintainer: Glyph Lefkowitz

@var _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.

@var _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.
    )divisionabsolute_importprint_functionN)exc_infoversion_infowraps)Version)cmp
comparable)lockfilefailure)Logger)warnAboutFunction
deprecated)	_oldStylec                   @   s   e Zd ZdS )AlreadyCalledErrorN__name__
__module____qualname__ r   r   8/usr/lib/python3/dist-packages/twisted/internet/defer.pyr   '   s   r   c                   @   s   e Zd ZdZdS )CancelledErrorzJ
    This error is raised by default when a L{Deferred} is cancelled.
    Nr   r   r   __doc__r   r   r   r   r   ,   s   r   c                   @   s   e Zd ZdZdS )TimeoutErrorzG
    This error is raised by default when a L{Deferred} times out.
    Nr   r   r   r   r   r   2   s   r   c                 C   s   t d|  | 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.
    N)logr   )errr   r   r   logError9   s    	r   c                 C   s   t  }||  |S )a6  
    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.

    @rtype: L{Deferred}
    )Deferredcallbackresultdr   r   r   succeedG   s    
r%   c                 C   s   t  }||  |S )aK  
    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.

    @rtype: L{Deferred}
    )r    errbackr"   r   r   r   fail^   s    
r'   c                 O   s.   z| ||}W n   t   Y S X t|S dS )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.
    N)r'   r%   )callableargskwr#   r   r   r   executeq   s
    r+   c                 O   s\   z| ||}W n   t tjtjd Y S X t|tr<|S t|tjrPt |S t|S d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.

    @type f: Any callable
    @param f: The callable to invoke

    @param args: The arguments to pass to C{f}
    @param kw: The keyword arguments to pass to C{f}

    @rtype: L{Deferred}
    @return: The result of the function call, wrapped in a L{Deferred} if
    necessary.
    ZcaptureVarsN)r'   r   Failurer    debug
isinstancer%   )fr)   r*   r#   r   r   r   maybeDeferred   s    
r1   ZTwisted      z*twisted.internet.defer.Deferred.addTimeout)Zreplacementc                 C   s   |  ttd d S )NzCallback timed out)r&   r   r-   r   deferredr   r   r   timeout   s    r6   c                 C   s   | S Nr   )argr   r   r   passthru   s    r9   c                 C   s   t | t_dS )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)boolr    r.   )Zonr   r   r   setDebugging   s    r;   c                   C   s   t jS )z=
    Determine whether L{Deferred} debugging is enabled.
    )r    r.   r   r   r   r   getDebugging   s    r<   c                   @   s   e Zd ZdZdZdZdZdZdZdZ	dZ
d,ddZd-ddZdd	 Zd
d Zdd Zd.ddZdd Zdd Zd/ddZdd Zdd Zdd Zdd Zdd Zd d! Zd"d# ZeZd$d% Zejd0d&d'ZeZ eZ!d(d) Z"e#d*d+ Z$dS )1r    a  
    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}.
    @type called: L{bool}

    @ivar paused: A counter of how many unmatched C{pause} calls have been made
        on this instance.
    @type paused: L{int}

    @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.
    @type _suppressAlreadyCalled: L{bool}

    @ivar _runningCallbacks: A flag which is C{True} while this instance is
        executing its callback chain, used to stop recursive execution of
        L{_runCallbacks}
    @type _runningCallbacks: L{bool}

    @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}.
    FNc                 C   s2   g | _ || _| jr.t | _t dd | j_dS )aD  
        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
            cancelation is requested (i.e., 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.   	DebugInfo
_debugInfo	tracebackformat_stackcreatorself	cancellerr   r   r   __init__  s
    zDeferred.__init__c                 C   sV   t |st|dks t |s t|||f|p.t||ff}| j| | jrR|   | 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}.
        @rtype: a L{Deferred}
        N)r(   AssertionErrorr9   r>   appendcalled_runCallbacks)rF   r!   r&   callbackArgscallbackKeywordserrbackArgserrbackKeywordsZcbsr   r   r   addCallbacks%  s    zDeferred.addCallbacksc                 O   s   | j |||dS )z^
        Convenience method for adding just a callback.

        See L{addCallbacks}.
        )rM   rN   rQ   rF   r!   r)   r*   r   r   r   addCallback;  s    zDeferred.addCallbackc                 O   s   | j t|||dS )z^
        Convenience method for adding just an errback.

        See L{addCallbacks}.
        )rO   rP   )rQ   r9   )rF   r&   r)   r*   r   r   r   
addErrbackE  s    zDeferred.addErrbackc                 O   s   | j ||||||dS )z
        Convenience method for adding a single callable as both a callback
        and an errback.

        See L{addCallbacks}.
        )rM   rO   rN   rP   rR   rS   r   r   r   addBothP  s      zDeferred.addBothc                    sT   dgfdd}| | fdd}|  fd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}
        @type timeout: L{int}

        @param clock: The object which will be used to schedule the timeout.
        @type clock: L{twisted.internet.interfaces.IReactorTime}

        @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 none is provided) will
            translate a L{CancelledError} L{Failure} into a L{TimeoutError}.
        @type onTimeoutCancel: L{callable}

        @return: C{self}.
        @rtype: a L{Deferred}

        @since: 16.5
        Fc                      s   dd<     d S )NTr   )cancelr   )rF   timedOutr   r   	timeItOut  s    z&Deferred.addTimeout.<locals>.timeItOutc                    s   d r pt }|| S | S )Nr   )_cancelledToTimedOutError)valueZtoCall)onTimeoutCancelrX   r6   r   r   convertCancelled  s    
z-Deferred.addTimeout.<locals>.convertCancelledc                    s      r   | S r7   )activerW   r#   )delayedCallr   r   cancelTimeout  s    z*Deferred.addTimeout.<locals>.cancelTimeout)	callLaterrV   )rF   r6   Zclockr\   rY   r]   ra   r   )r`   r\   rF   rX   r6   r   
addTimeout\  s    "

zDeferred.addTimeoutc                 C   s   | |_ | |j|jS )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::

            self.addCallbacks(d.callback, d.errback)

        When you chain a deferred d2 to another deferred d1 with
        d1.chainDeferred(d2), you are making d2 participate in the callback
        chain of d1. Thus any event that fires d1 will also fire d2.
        However, the converse is B{not} true; if d2 is fired 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}.
        @rtype: a L{Deferred}
        )
_chainedTorQ   r!   r&   rF   r$   r   r   r   chainDeferred  s    zDeferred.chainDeferredc                 C   s   t |trt| | dS )a  
        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}).

        @raise AlreadyCalledError: If L{callback} or L{errback} has already been
            called on this L{Deferred}.
        N)r/   r    rI   _startRunCallbacks)rF   r#   r   r   r   r!     s    zDeferred.callbackc                 C   s<   |dkrt j| jd}nt|t js.t |}| | dS )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.Failure} instance,
        it will be embedded in one. If no argument is passed, a
        L{failure.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.
        Nr,   )r   r-   r.   r/   rg   )rF   r'   r   r   r   r&     s
    !
zDeferred.errbackc                 C   s   | j d | _ dS )zP
        Stop processing on a L{Deferred} until L{unpause}() is called.
        r3   N)pausedrF   r   r   r   pause  s    zDeferred.pausec                 C   s(   | j d | _ | j rdS | jr$|   dS )zI
        Process all callbacks made since L{pause}() was called.
        r3   N)rh   rK   rL   ri   r   r   r   unpause  s
    zDeferred.unpausec                 C   sT   | j s:| j}|r||  nd| _| j sP| tt  nt| jt	rP| j
  dS )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)rK   r?   _suppressAlreadyCalledr&   r   r-   r   r/   r#   r    rW   rE   r   r   r   rW   
  s    
zDeferred.cancelc                 C   s   | j rH| jrd| _d S | jrD| jd kr.t | _d| j  }t|t| jrt| jd kr`t | _t d d | j_	d| _ || _
|   d S )NF
T)rK   rl   r.   rA   r@   _getDebugTracebacksr   rB   rC   invokerr#   rL   )rF   r#   Zextrar   r   r   rg   '  s"    

zDeferred._startRunCallbacksc                 C   s   t | fdft | fdffS )zJ
        Build a tuple of callback and errback with L{_CONTINUE}.
        N)	_CONTINUEri   r   r   r   _continuation;  s    

zDeferred._continuationc           
      C   s  | j r
dS | g}|r|d }|jr(dS d}d|_|jr|jd}|t|jtj \}}}|pdd}|pli }|t	kr|d }|j|_d|_|j
dk	rd|j
_| jd8  _|| d}qz@d|_ z,||jf|||_|j|krt|d W 5 d|_ X W n   tj| jd	|_Y q2X t|jtr2t|jd
t}	|	tksVt|	tsV|jjr~|  |j|_|jj|  qq2d|j_|jj
dk	rd|jj
_|	|_q2|rt|jtjr|j  |j
dkrt |_
|j|j
_n|j
dk	rd|j
_|  qdS )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.
        Nr=   Tr   r   r3   Fz|Callback returned the Deferred it was attached to; this breaks the callback chain and will raise an exception in the future.r,   r#   )_runningCallbacksrh   rd   r>   popr/   r#   r   r-   rq   rA   
failResultrJ   r   r.   r    getattr
_NO_RESULTrj   rr   ZcleanFailurer@   )
rF   chainZcurrentZfinisheditemr!   r)   r*   ZchaineeZresultResultr   r   r   rL   C  st    



 

zDeferred._runCallbacksc                 C   s^   | j j}t| dt}t| }| jdk	r8dt| jf }n|tkrFd}n
d|f }d|||f S )zE
        Return a string representation of this C{Deferred}.
        r#   Nz waiting on Deferred at 0x%x z current result: %rz<%s at 0x%x%s>)	__class__r   rv   rw   idrd   )rF   Zcnamer#   ZmyIDr   r   r   __str__  s    

zDeferred.__str__c                 C   s   | S r7   r   ri   r   r   r   __iter__  s    zDeferred.__iter__c                 C   sR   | j r
| S t| dt}|tkr"| S t|tjrFd | j_||j_	|jnt
|d S )Nr#   )rh   rv   rw   r/   r   r-   rA   ru   r[   Z__failure__StopIteration)rF   r[   r#   r   r   r   send  s    zDeferred.sendc                    s~   z
j }W n. tk
r8   ddlm   fdd}Y nX | fdd}fdd}fd	d
}|| | S )a  
        Adapt a L{Deferred} into a L{asyncio.Future} which is bound to C{loop}.

        @note: converting a L{Deferred} to an L{asyncio.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 asyncio event loop to bind the L{asyncio.Future} to.
        @type loop: L{asyncio.AbstractEventLoop} or similar

        @param deferred: The Deferred to adapt.
        @type deferred: L{Deferred}

        @return: A Future which will fire when the Deferred fires.
        @rtype: L{asyncio.Future}
        r   )Futurec                      s
    dS )N)loopr   r   )r   r   r   r   createFuture  s    z'Deferred.asFuture.<locals>.createFuturec                    s   |   r   d S r7   )	cancelledrW   )ZfutureAgainri   r   r   checkCancel  s    z&Deferred.asFuture.<locals>.checkCancelc                    s      s | j d S r7   )r   Zset_exceptionr[   )r   futurer   r   	maybeFail  s    z$Deferred.asFuture.<locals>.maybeFailc                    s      s |  d S r7   )r   Z
set_resultr_   r   r   r   maybeSucceed  s    z'Deferred.asFuture.<locals>.maybeSucceed)Zcreate_futureAttributeErrorasyncior   rQ   add_done_callback)rF   r   r   r   r   r   r   )r   r   r   rF   r   asFuture  s    

zDeferred.asFuturec                    sT    fdd t  fdd}| |}| _ fdd}||   |S )a  
        Adapt an L{asyncio.Future} to a L{Deferred}.

        @note: This creates a L{Deferred} from a L{asyncio.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{asyncio.Future} if what you have is an awaitable coroutine and
            not a L{asyncio.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 Future to adapt.
        @type future: L{asyncio.Future}

        @return: A Deferred which will fire when the Future fires.
        @rtype: L{Deferred}
        c                    s2   z|   }W n   t }Y nX  j| d S r7   )r#   r   r-   actualr!   )r#   Z	extracted)adaptr   r   r   6  s
    z"Deferred.fromFuture.<locals>.adaptc                    s       |  d S r7   )rW   r!   )Zreself)r   futureCancelr   r   rW   =  s    z#Deferred.fromFuture.<locals>.cancelc                    s   | krt   _ jS | S r7   )r    r   r_   )r   r   r   r   uncancelB  s    z%Deferred.fromFuture.<locals>.uncancel)objectr   rT   r   )clsr   rW   rF   r   r   )r   r   r   r   
fromFuture   s    

zDeferred.fromFuture)N)NNNNN)N)N)N)%r   r   r   r   rK   rh   rA   rl   rs   r.   rd   rH   rQ   rT   rU   rV   rc   rf   r!   r&   rj   rk   rW   rg   rr   rL   r}   __repr__r~   r   _extraneousr   	__await____next__r   classmethodr   r   r   r   r   r       sN   ,
       


>
) )r    c                 C   s$   t | tjr | t t|d| S )a.  
    A default translation function that translates L{Failure}s that are
    L{CancelledError}s to L{TimeoutError}s.

    @param value: Anything
    @type value: Anything

    @param timeout: The timeout
    @type timeout: L{int}

    @rtype: C{value}
    @raise: L{TimeoutError}

    @since: 16.5
    r    )r/   r   r-   trapr   r   )r[   r6   r   r   r   rZ   M  s    

rZ   c                 C   sV   ddl m} tdkr:ddlm} || s2t| |r:t| S t| tsRtd| f | S )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 (mimicing C{asyncio}'s C{ensure_future} function).

    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 ensureDeferred
        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 = ensureDeferred(crawl(pages))
            d.addCallback(print)
            return d

        react(main)

    @param coro: The coroutine object to schedule, or a L{Deferred}.
    @type coro: A Python 3.5+ C{async def} C{coroutine}, a Python 3.4+
        C{yield from} using L{types.GeneratorType}, or a L{Deferred}.

    @rtype: L{Deferred}
    r   )GeneratorType)      r   )iscoroutinez#%r is not a coroutine or a Deferred)	typesr   r   r   r   r/   _cancellableInlineCallbacksr    
ValueError)coror   r   r   r   r   ensureDeferredd  s    %
r   c                   @   s$   e Zd ZdZdZdd Zdd ZdS )r@   z 
    Deferred debug helper.
    Nc                 C   st   d}t | dr:|d7 }|d| j dd7 }|d7 }t | drp|d7 }|d| j dd7 }|d7 }|S )	Nrz   rD   z C: Deferred was created:
 C:rm   z
 C:rp   z I: First Invoker was:
 I:z
 I:)hasattrjoinrD   rstripreplacerp   )rF   infor   r   r   ro     s    

zDebugInfo._getDebugTracebacksc                 C   sD   | j dk	r@tjddd |  }|r*d}nd}tj|| j |d dS )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}).
        NzUnhandled error in Deferred:T)ZisErrorz(debug: {debugInfo}))	debugInfo)ru   r   Zcriticalro   r   )rF   r   formatr   r   r   __del__  s    
zDebugInfo.__del__)r   r   r   r   ru   ro   r   r   r   r   r   r@     s   r@   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )
FirstErrora!  
    First error to occur in a L{DeferredList} if C{fireOnOneErrback} is set.

    @ivar subFailure: The L{Failure} that occurred.
    @type subFailure: L{Failure}

    @ivar index: The index of the L{Deferred} in the L{DeferredList} where
        it happened.
    @type index: L{int}
    c                 C   s   t | || || _|| _d S r7   )	ExceptionrH   
subFailureindex)rF   r   r   r   r   r   rH     s    zFirstError.__init__c                 C   s   d| j | jjf S )z
        The I{repr} of L{FirstError} instances includes the repr of the
        wrapped failure's exception and the index of the L{FirstError}.
        zFirstError[#%d, %r])r   r   r[   ri   r   r   r   r     s    zFirstError.__repr__c                 C   s   d| j | jf S )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}.
        zFirstError[#%d, %s])r   r   ri   r   r   r   r}     s    zFirstError.__str__c                 C   s(   t |tr$t| j| jf|j|jfS dS )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=   )r/   r   r
   r   r   )rF   otherr   r   r   __cmp__  s    	


zFirstError.__cmp__N)r   r   r   r   rH   r   r}   r   r   r   r   r   r     s
   
	r   c                   @   s2   e Zd ZdZdZdZd
ddZdd Zdd Zd	S )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.
    Fc                 C   s   t || _dgt| j | _t|  t| jdkrD|sD| | j || _|| _|| _	d| _
d}| jD ]*}|j| j| j|tf|tfd |d }qfdS )a   
        Initialize a DeferredList.

        @param deferredList: The list of deferreds to track.
        @type deferredList:  L{list} of L{Deferred}s

        @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.
        @type fireOnOneCallback: L{bool}

        @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.
        @type fireOnOneErrback: L{bool}

        @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.
        @type consumeErrors: L{bool}
        Nr   )rM   rO   r3   )list_deferredListlen
resultListr    rH   r!   fireOnOneCallbackfireOnOneErrbackconsumeErrorsfinishedCountrQ   _cbDeferredSUCCESSFAILURE)rF   deferredListr   r   r   r   r5   r   r   r   rH     s     #


zDeferredList.__init__c                 C   s   ||f| j |< |  jd7  _| js|tkr@| jr@| ||f nB|tkrf| jrf| t	
t|| n| jt| j kr| | j  |tkr| jrd}|S )zI
        (internal) Callback for when one of my deferreds fires.
        r3   N)r   r   rK   r   r   r!   r   r   r&   r   r-   r   r   r   )rF   r#   r   Z	succeededr   r   r   r   O  s    zDeferredList._cbDeferredc                 C   s:   | j s6| jD ](}z|  W q   td Y qX qdS )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)rK   r   rW   r   r   )rF   r5   r   r   r   rW   d  s    
zDeferredList.cancelN)FFF)	r   r   r   r   r   r   rH   r   rW   r   r   r   r   r     s       
9r   Fc                 C   s$   | D ]\}}|st qdd | D S )Nc                 S   s   g | ]}|d  qS )r3   r   ).0xr   r   r   
<listcomp>  s     z%_parseDListResult.<locals>.<listcomp>)rI   )lr   Zsuccessr[   r   r   r   _parseDListResult{  s    
r   c                 C   s   t | d|d}|t |S )as  
    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.

    @type deferredList:  L{list} of L{Deferred}s

    @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.
    @type consumeErrors: L{bool}
    T)r   r   )r   rT   r   )r   r   r$   r   r   r   gatherResults  s
    
r   Tc                   @   s    e Zd ZdZdd Zdd ZdS )waitForDeferred#
    See L{deferredGenerator}.
    c                 C   s2   t jdtdd t|ts(td|f || _d S )Nztwisted.internet.defer.waitForDeferred was deprecated in Twisted 15.0.0; please use twisted.internet.defer.inlineCallbacks instead   )
stacklevelz9You must give waitForDeferred a Deferred. You gave it %r.)warningswarnDeprecationWarningr/   r    	TypeErrorr$   re   r   r   r   rH     s     
zwaitForDeferred.__init__c                 C   s   t | jtjr| j  | jS r7   )r/   r#   r   r-   ZraiseExceptionri   r   r   r   	getResult  s    
zwaitForDeferred.getResultN)r   r   r   r   rH   r   r   r   r   r   r     s   r   c                    s   d}ddgzt }W n8 tk
r:    |   Y S         Y S X t|trhttdS t|tr|f fdd	}|j	
| d rdd<  S dd< dd< d}qdS )	r   NTz Yield waitForDeferred(d), not d!c                    s.   | |_ d r dd< | d< n
t  d S Nr   Fr3   )r#   _deferGenerator)rr#   r5   gwaitingr   r   	gotResult  s
    
z"_deferGenerator.<locals>.gotResultr   Fr3   )nextr   r!   r&   r/   r    r'   r   r   r$   rV   )r   r5   r#   r   r   r   r   r     s.    



r      z&twisted.internet.defer.inlineCallbacksc                    s   t   fdd}|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}.
    c                     s   t  | |t S r7   )r   r    )r)   kwargsr0   r   r   unwindGenerator5  s    z*deferredGenerator.<locals>.unwindGeneratorr   r0   r   r   r   r   deferredGenerator  s    :r   c                   @   s   e Zd Zdd ZdS )_DefGen_Returnc                 C   s
   || _ d S r7   )r[   )rF   r[   r   r   r   rH   @  s    z_DefGen_Return.__init__N)r   r   r   rH   r   r   r   r   r   ?  s   r   c                 C   s   t | dS )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.
    N)r   )valr   r   r   returnValueE  s    r   c                   @   s$   e Zd ZdZe ZejddZdS )_CancellationStatusa-  
    Cancellation status of an L{inlineCallbacks} invocation.

    @ivar waitingOn: the L{Deferred} being waited upon (which
        L{_inlineCallbacks} must fill out before returning)

    @ivar deferred: the L{Deferred} to callback or errback when the generator
        invocation has finished.
    N)default)r   r   r   r   attrZibr5   	waitingOnr   r   r   r   r   V  s   
r   c           
   
      s  ddgz*t | tj}|r&|  } n
 | } W n tk
rn } zjt|dd W Y dS d}~X Y n t	k
r
 } z~t
 d j}|r|j}|jjr|}|jjr|j}q|jjj}|j}td|jjj|jjjf t|| j|j W Y dS d}~X Y n   j  Y dS X t | tr fdd}	| |	 d rbd	d< | _dS d
 } dd< dd
< qdS )a/  
    Carry out the work of L{inlineCallbacks}.

    Iterate the generator produced by an C{@}L{inlineCallbacks}-decorated
    function, C{g}, 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 g: 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{g}
    TNr[   r   zvreturnValue() in %r causing %r to exit: returnValue should only be invoked by functions decorated with inlineCallbacksc                    s*   d rdd< | d< nt |   d S r   )_inlineCallbacks)r   r   statusr   r   r   r     s    
z#_inlineCallbacks.<locals>.gotResultr   Fr3   )r/   r   r-   ZthrowExceptionIntoGeneratorr   r   r5   r!   rv   r   r   tb_nexttb_framef_codeco_filename	tb_linenor   warn_explicitco_namer   r[   r&   r    rV   r   )
r#   r   r   Z	isFailureeZappCodeTraceZultimateTracefilenamelinenor   r   r   r   r   g  s\    

  



r   c                    s:   fdd t  }t| fddtd|  |S )z
    Make an C{@}L{inlineCallbacks} cancellable.

    @param g: 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.
    c                    s4   g | j  | _ }|   | j | | t  d S r7   )r>   rU   extendr&   &_InternalInlineCallbacksCancelledError)itZtmp)handleCancelr   r   rW     s    
z+_cancellableInlineCallbacks.<locals>.cancelc                    s(   |  t t _j}|  jS )aR  
        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{inlineCallback} generator
            can callback or errback through.
        )r   r   r    r5   r   rW   )r#   Zawaited)rW   r   r   r   r     s
    


z1_cancellableInlineCallbacks.<locals>.handleCancelN)r    r   r   )r   r5   r   )rW   r   r   r   r     s    	r   c                   @   s   e Zd ZdZdS )r   z
    A unique exception used only in L{_cancellableInlineCallbacks} to verify
    that an L{inlineCallbacks} is being cancelled as expected.
    Nr   r   r   r   r   r     s   r   c                    s   t   fdd}|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{yielde}ed L{Deferred} that
    has been cancelled if that C{Deferred} does not otherwise suppress it.
    c                     sV   z | |}W n" t k
r0   td f Y nX t|tjsNtd |f t|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)r   r   r/   r   r   r   )r)   r   genr   r   r   r   A  s    
z(inlineCallbacks.<locals>.unwindGeneratorr   r   r   r   r   inlineCallbacks  s    ;r   c                   @   s$   e Zd Zdd Zdd Zdd ZdS )_ConcurrencyPrimitivec                 C   s
   g | _ d S r7   )r   ri   r   r   r   rH   T  s    z_ConcurrencyPrimitive.__init__c                 C   s   |    |S r7   )release)rF   r   r   r   r   _releaseAndReturnX  s    z'_ConcurrencyPrimitive._releaseAndReturnc                     sr   t  dk r. stdtd d jjf  dd \ dd   fdd} }|| |S )a  
        Acquire, run, release.

        This function 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.
        r   z-run() takes at least 2 arguments, none given.z,%s.run() takes at least 2 arguments, 1 givenr   Nc                    s    t f }|j |S r7   )r1   rV   r   )ZignoredResultr$   r)   r0   r   rF   r   r   r+   s  s    z*_ConcurrencyPrimitive.run.<locals>.execute)r   r   r{   r   acquirerT   )r)   r   r+   r$   r   r   r   run]  s    

z_ConcurrencyPrimitive.runN)r   r   r   rH   r   r   r   r   r   r   r   S  s   r   c                   @   s,   e Zd ZdZdZdd Zdd Zdd Zd	S )
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                 C   s   | j | dS 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. 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.
        Nr   removere   r   r   r   _cancelAcquire  s    zDeferredLock._cancelAcquirec                 C   s4   t | jd}| jr | j| nd| _||  |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}
        rG   T)r    r   lockedr   rJ   r!   re   r   r   r   r     s    	
zDeferredLock.acquirec                 C   s:   | j stdd| _ | jr6d| _ | jd}||  dS )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 lockFTr   N)r  rI   r   rt   r!   re   r   r   r   r     s    zDeferredLock.releaseN)r   r   r   r   r  r   r   r   r   r   r   r   r   ~  s
   r   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )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.
    @type limit: L{int}

    @ivar tokens: The difference between C{limit} and the number of users
        which have currently acquired this semaphore.
    @type tokens: L{int}
    c                 C   s*   t |  |dk rtd|| _|| _dS )ze
        @param tokens: initial value of L{tokens} and L{limit}
        @type tokens: L{int}
        r3   z&DeferredSemaphore requires tokens >= 1N)r   rH   r   tokenslimit)rF   r  r   r   r   rH     s
    
zDeferredSemaphore.__init__c                 C   s   | j | dS r   r   re   r   r   r   r     s    z DeferredSemaphore._cancelAcquirec                 C   sL   | j dkstdt| jd}| j s2| j| n| j d | _ ||  |S )zq
        Attempt to acquire the token.

        @return: a L{Deferred} which fires on token acquisition.
        r   z9Internal inconsistency??  tokens should never be negativer  r3   )r  rI   r    r   r   rJ   r!   re   r   r   r   r     s    
zDeferredSemaphore.acquirec                 C   sL   | j | jk std| j d | _ | jrH| j d | _ | jd}||  dS )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!r3   r   N)r  r  rI   r   rt   r!   re   r   r   r   r     s    zDeferredSemaphore.releaseN)r   r   r   r   rH   r   r   r   r   r   r   r   r    s
   r  c                   @   s   e Zd ZdS )QueueOverflowNr   r   r   r   r   r  	  s   r  c                   @   s   e Zd ZdS )QueueUnderflowNr   r   r   r   r   r    s   r  c                   @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )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                 C   s   g | _ g | _|| _|| _d S r7   )r   pendingsizebacklog)rF   r
  r  r   r   r   rH   %  s    zDeferredQueue.__init__c                 C   s   | j | dS )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.
        Nr   re   r   r   r   
_cancelGet,  s    zDeferredQueue._cancelGetc                 C   sL   | j r| j d| n.| jdks4t| j| jk rB| j| nt dS )zq
        Add an object to this queue.

        @raise QueueOverflow: Too many objects are in this queue.
        r   N)r   rt   r!   r
  r   r	  rJ   r  )rF   objr   r   r   put;  s
    zDeferredQueue.putc                 C   sV   | j rt| j dS | jdks0t| j| jk rLt| jd}| j| |S t	 dS )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.
        r   Nr  )
r	  r%   rt   r  r   r   r    r  rJ   r  re   r   r   r   getI  s    
zDeferredQueue.get)NN)r   r   r   r   rH   r  r  r  r   r   r   r   r    s
   
r  c                   @   s   e Zd ZdZdS )AlreadyTryingToLockErrorz{
    Raised when L{DeferredFilesystemLock.deferUntilLocked} is called twice on a
    single L{DeferredFilesystemLock}.
    Nr   r   r   r   r   r  ^  s   r  c                   @   s0   e Zd ZdZdZdZdZdddZd	ddZdS )
DeferredFilesystemLockai  
    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: A L{DelayedCall} based on C{_interval} that will manage
        the next retry for acquiring the lock.

    @ivar _timeoutCall: A L{DelayedCall} based on C{deferUntilLocked}'s timeout
        argument.  This is in charge of timing out our attempt to acquire the
        lock.
    r3   Nc                 C   s0   t j| | |dkr&ddlm} |}|| _dS )z
        @param name: The name of the lock to acquire
        @param scheduler: An object which provides L{IReactorTime}
        Nr   )reactor)r   FilesystemLockrH   Ztwisted.internetr  
_scheduler)rF   nameZ	schedulerr  r   r   r   rH   |  s
    zDeferredFilesystemLock.__init__c                    sR   j dk	rttdS fdd t fdd fdd  S )	a(  
        Wait until we acquire this lock.  This method is not safe for
        concurrent use.

        @type timeout: L{float} or L{int}
        @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.c                    sV   j   d_ jdk	r4j r4j  d_ rH d n
 |  dS )z
            Cancel a L{DeferredFilesystemLock.deferUntilLocked} call.

            @type reason: L{failure.Failure}
            @param reason: The reason why the call is cancelled.
            N)_tryLockCallrW   _timeoutCallr^   lockr!   r&   reason)r$   rF   r   r   _cancelLock  s    

z<DeferredFilesystemLock.deferUntilLocked.<locals>._cancelLockc                    s
    t  S r7   )r   r4   )r  r   r   <lambda>      z9DeferredFilesystemLock.deferUntilLocked.<locals>.<lambda>c                     s     r4jd k	r"j  d _d _d  nNd k	rpjd krpttdjf } j	
 | _j	
j_d S )Nz&Timed out acquiring lock: %s after %fs)r  r  rW   r  r!   r   r-   r   r  r  rb   	_intervalr  r  _tryLockr$   rF   r6   r   r   r     s,    

   z9DeferredFilesystemLock.deferUntilLocked.<locals>._tryLock)r  r'   r  r    )rF   r6   r   r  r   deferUntilLocked  s    
z'DeferredFilesystemLock.deferUntilLocked)N)N)	r   r   r   r   r  r  r  rH   r!  r   r   r   r   r  f  s   
r  r   r   )N)F)F)Or   Z
__future__r   r   r   r   rB   r   r   sysr   r   	functoolsr   Zincrementalr	   Ztwisted.python.compatr
   r   Ztwisted.pythonr   r   Ztwisted.loggerr   Ztwisted.python.deprecater   r   Ztwisted.python._oldstyler   r   r   r   r   r   r   r%   r'   r+   r1   r6   r9   r;   r<   r   rw   rq   r    rZ   r   r@   r   r   r   r   r   r   r   r   r   BaseExceptionr   r   sr   r   r   r   r   r   r   r   r  r  r  r  r  r  r  __all__r   r   r   r   <module>   s   
"
     	6-3

"8
B
p&M+?LKf        