
    )Jf                    N   d Z ddl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	 ddl
mZ ddlZddlmZ ddlmZ ddlmZ ddlmZ  ej        e          Z G d de          Z G d	 d
e          Z G d de          Z G d de          Z G d de          Z G d de          Z G d de          Z  G d de          Z! G d de!          Z" G d de!          Z# G d de!          Z$ G d de          Z% G d d e          Z& G d! d"e          Z' G d# d$e          Z(dS )%a  The blocking connection adapter module implements blocking semantics on top
of Pika's core AMQP driver. While most of the asynchronous expectations are
removed when using the blocking connection adapter, it attempts to remain true
to the asynchronous RPC nature of the AMQP protocol, supporting server sent
RPC commands.

The user facing classes in the module consist of the
:py:class:`~pika.adapters.blocking_connection.BlockingConnection`
and the :class:`~pika.adapters.blocking_connection.BlockingChannel`
classes.

    )
namedtupledequeN)connection_workflow)select_connection)ExchangeTypec                       e Zd ZdZdZddZd Zd ZeZd Z	d Z
d	 Zed
             Zd Zd Zd Zed             Zed             ZdS )_CallbackResultzo CallbackResult is a non-thread-safe implementation for receiving
    callback results; INTERNAL USE ONLY!
    )_value_class_ready_valuesNc                 X    || _         d| _        d| _        |                                  dS )at  
        :param callable value_class: only needed if the CallbackResult
                                     instance will be used with
                                     `set_value_once` and `append_element`.
                                     *args and **kwargs of the value setter
                                     methods will be passed to this class.

        N)r
   r   r   reset)selfvalue_classs     d/home/alex/cs2snipeproduction/venv/lib/python3.11/site-packages/pika/adapters/blocking_connection.py__init__z_CallbackResult.__init__-   s+     (

    c                 "    d| _         d| _        dS )z!Reset value, but not _value_classFN)r   r   r   s    r   r   z_CallbackResult.reset;   s    r   c                 *    |                                  S )z Called by python runtime to implement truth value testing and the
        built-in operation bool(); NOTE: python 3.x
        )is_readyr   s    r   __bool__z_CallbackResult.__bool__@   s     }}r   c                     | S )z Entry into context manager that automatically resets the object
        on exit; this usage pattern helps garbage-collection by eliminating
        potential circular references.
         r   s    r   	__enter__z_CallbackResult.__enter__I   s	    
 r   c                 .    |                                   dS )zReset valueN)r   r   argskwargss      r   __exit__z_CallbackResult.__exit__P   s    

r   c                     | j         S )zZ
        :returns: True if the object is in a signaled state
        :rtype: bool
        r   r   s    r   r   z_CallbackResult.is_readyT   s    
 {r   c                     | j         S )z)True if the object is in a signaled stater"   r   s    r   readyz_CallbackResult.ready[   s     {r   c                 6    | j         r
J d            d| _         dS )zW Set as ready

        :raises AssertionError: if result was already signalled
        z_CallbackResult was already setTNr"   r   _args_kwargss      r   signal_oncez_CallbackResult.signal_once`   s&    
 ;AA AAAAr   c                     |                                   	  | j        |i |f| _        dS # t          $ r$ t                              d| j        ||            w xY w)z Set as ready with value; the value may be retrieved via the `value`
        property getter

        :raises AssertionError: if result was already set
        z9set_value_once failed: value_class=%r; args=%r; kwargs=%rN)r)   r
   r   	ExceptionLOGGERerrorr   s      r   set_value_oncez_CallbackResult.set_value_onceh   s~     		-D-t>v>>@DLLL 	 	 	LLK!41 1 1 		s	   + .Ac                 ^   | j         r4t          | j        t                    sJ d| j         d| j                    	  | j        |i |}n1# t
          $ r$ t                              d| j        ||            w xY w| j        	|g| _        n| j                            |           d| _         dS )zAppend an element to valueszA_CallbackResult state is incompatible with append_element: ready=z	; values=z9append_element failed: value_class=%r; args=%r; kwargs=%rNT)	r   
isinstancer   listr
   r+   r,   r-   append)r   r   r   values       r   append_elementz_CallbackResult.append_elementw   s    ; 	A*T\4"@"@ 	A 	A 	A%)[[[$,,@	A 	A 	A	%D%t6v66EE 	 	 	LLK!41 1 1 		 <!7DLLL&&&s   A .A9c                     | j         s
J d            t          | j        t                    rt	          | j                  dk    sJ d| j                    | j        d         S )z
        :returns: a reference to the value that was set via `set_value_once`
        :rtype: object
        :raises AssertionError: if result was not set or value is incompatible
                                with `set_value_once`
        _CallbackResult was not set   z;_CallbackResult value is incompatible with set_value_once: r   )r   r0   r   tuplelenr   s    r   r3   z_CallbackResult.value   so     {999999$,.. 	3t|3D3D3I3I3I3I\\ 4J3I3I |Ar   c                     | j         s
J d            t          | j        t                    r| j        sJ d| j                    | j        S )a  
        :returns: a reference to the list containing one or more elements that
            were added via `append_element`
        :rtype: list
        :raises AssertionError: if result was not set or value is incompatible
                                with `append_element`
        r6   z;_CallbackResult value is incompatible with append_element: )r   r0   r   r1   r   s    r   elementsz_CallbackResult.elements   sg     {999999$,-- 	$, 	 	 	\\	 	 	 |r   N)__name__
__module____qualname____doc__	__slots__r   r   r   __nonzero__r   r    r   propertyr$   r)   r.   r4   r3   r;   r   r   r   r	   r	   '   s	         6I     
   K         X      *   X   X  r   r	   c                   *    e Zd ZdZd Zd Zd Zd ZdS )_IoloopTimerContextzgContext manager for registering and safely unregistering a
    SelectConnection ioloop-based timer
    c                     t          |d          s
J |            || _        || _        t                      | _        d| _        dS )z
        :param float duration: non-negative timer duration in seconds
        :param select_connection.SelectConnection connection:
        _adapter_call_laterN)hasattr	_duration_connectionr	   _callback_result_timer_handle)r   duration
connections      r   r   z_IoloopTimerContext.__init__   sN    
 z#899EE:EEE!% / 1 1!r   c                 d    | j                             | j        | j        j                  | _        | S )zRegister a timer)rJ   rG   rI   rK   r)   rL   r   s    r   r   z_IoloopTimerContext.__enter__   s/    !-AAND1=? ?r   c                 d    | j         s(| j                            | j                   d| _        dS dS )z'Unregister timer if it hasn't fired yetN)rK   rJ   _adapter_remove_timeoutrL   r&   s      r   r    z_IoloopTimerContext.__exit__   s?    $ 	&44T5GHHH!%D	& 	&r   c                 4    | j                                         S )zY
        :returns: True if timer has fired, False otherwise
        :rtype: bool
        )rK   r   r   s    r   r   z_IoloopTimerContext.is_ready   s    
 $--///r   N)r=   r>   r?   r@   r   r   r    r   r   r   r   rE   rE      sZ         	" 	" 	"  & & &0 0 0 0 0r   rE   c                   (    e Zd ZdZdZd Zd Zd ZdS )	_TimerEvtz>Represents a timer created via `BlockingConnection.call_later`)timer_id	_callbackc                 "    || _         d| _        dS )zR
        :param callback: see callback in `BlockingConnection.call_later`
        N)rV   rU   r   callbacks     r   r   z_TimerEvt.__init__   s     " r   c                 B    d| j         j        d| j        d| j        dS )N<z
 timer_id=
 callback=>)	__class__r=   rU   rV   r   s    r   __repr__z_TimerEvt.__repr__   s/     151H1H1H15P 	Pr   c                 n    t                               d| j                   |                                  dS )#Dispatch the user's callback methodz(_TimerEvt.dispatch: invoking callback=%rN)r,   debugrV   r   s    r   dispatchz_TimerEvt.dispatch   s/    ?PPPr   Nr=   r>   r?   r@   rA   r   r_   rc   r   r   r   rT   rT      sO        HH)I  P P P    r   rT   c                   (    e Zd ZdZdZd Zd Zd ZdS )"_ConnectionBlockedUnblockedEvtBasezDBase class for `_ConnectionBlockedEvt` and `_ConnectionUnblockedEvt`rV   _method_framec                 "    || _         || _        dS )ac  
        :param callback: see callback parameter in
          `BlockingConnection.add_on_connection_blocked_callback` and
          `BlockingConnection.add_on_connection_unblocked_callback`
        :param pika.frame.Method method_frame: with method_frame.method of type
          `pika.spec.Connection.Blocked` or `pika.spec.Connection.Unblocked`
        Nrg   )r   rY   method_frames      r   r   z+_ConnectionBlockedUnblockedEvtBase.__init__   s     ")r   c                 B    d| j         j        d| j        d| j        dS )Nr[   r\   z, frame=r]   )r^   r=   rV   rh   r   s    r   r_   z+_ConnectionBlockedUnblockedEvtBase.__repr__   s1     N###T^^^T5G5G5GI 	Ir   c                 :    |                      | j                   dS )ra   Nrg   r   s    r   rc   z+_ConnectionBlockedUnblockedEvtBase.dispatch   s    t)*****r   Nrd   r   r   r   rf   rf      sO        NN.I	* 	* 	*I I I+ + + + +r   rf   c                       e Zd ZdZdS )_ConnectionBlockedEvtzBRepresents a Connection.Blocked notification from RabbitMQ broker`Nr=   r>   r?   r@   r   r   r   rn   rn      s        LLLLr   rn   c                       e Zd ZdZdS )_ConnectionUnblockedEvtzDRepresents a Connection.Unblocked notification from RabbitMQ broker`Nro   r   r   r   rq   rq     s        NNNNr   rq   c                      e Zd ZdZ edd          Z edd          Zd*dZd Zd	 Z	d
 Z
d Zej        d             Zd Zed             Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd+dZ d,d!Z!d" Z"d-d#Z#e$d$             Z%e$d%             Z&e$d&             Z'e$d'             Z(e$d(             Z)e$d)             Z*e'Z+e(Z,e)Z-e*Z.dS ).BlockingConnectiona  The BlockingConnection creates a layer on top of Pika's asynchronous core
    providing methods that will block until their expected response has
    returned. Due to the asynchronous nature of the `Basic.Deliver` and
    `Basic.Return` calls from RabbitMQ to your application, you can still
    implement continuation-passing style asynchronous methods if you'd like to
    receive messages from RabbitMQ using
    :meth:`basic_consume <BlockingChannel.basic_consume>` or if you want to be
    notified of a delivery failure when using
    :meth:`basic_publish <BlockingChannel.basic_publish>`.

    For more information about communicating with the blocking_connection
    adapter, be sure to check out the
    :class:`BlockingChannel <BlockingChannel>` class which implements the
    :class:`Channel <pika.channel.Channel>` based communication for the
    blocking_connection adapter.

    To prevent recursion/reentrancy, the blocking connection and channel
    implementations queue asynchronously-delivered events received
    in nested context (e.g., while waiting for `BlockingConnection.channel` or
    `BlockingChannel.queue_declare` to complete), dispatching them synchronously
    once nesting returns to the desired context. This concerns all callbacks,
    such as those registered via `BlockingConnection.call_later`,
    `BlockingConnection.add_on_connection_blocked_callback`,
    `BlockingConnection.add_on_connection_unblocked_callback`,
    `BlockingChannel.basic_consume`, etc.

    Blocked Connection deadlock avoidance: when RabbitMQ becomes low on
    resources, it emits Connection.Blocked (AMQP extension) to the client
    connection when client makes a resource-consuming request on that connection
    or its channel (e.g., `Basic.Publish`); subsequently, RabbitMQ suspsends
    processing requests from that connection until the affected resources are
    restored. See http://www.rabbitmq.com/connection-blocked.html. This
    may impact `BlockingConnection` and `BlockingChannel` operations in a
    way that users might not be expecting. For example, if the user dispatches
    `BlockingChannel.basic_publish` in non-publisher-confirmation mode while
    RabbitMQ is in this low-resource state followed by a synchronous request
    (e.g., `BlockingConnection.channel`, `BlockingChannel.consume`,
    `BlockingChannel.basic_consume`, etc.), the synchronous request will block
    indefinitely (until Connection.Unblocked) waiting for RabbitMQ to reply. If
    the blocked state persists for a long time, the blocking operation will
    appear to hang. In this state, `BlockingConnection` instance and its
    channels will not dispatch user callbacks. SOLUTION: To break this potential
    deadlock, applications may configure the `blocked_connection_timeout`
    connection parameter when instantiating `BlockingConnection`. Upon blocked
    connection timeout, this adapter will raise ConnectionBlockedTimeout
    exception`. See `pika.connection.ConnectionParameters` documentation to
    learn more about the `blocked_connection_timeout` configuration.

     BlockingConnection__OnClosedArgszconnection error'BlockingConnection__OnChannelOpenedArgschannelNc                 N   t          j                    | _        d| _        t	                      | _        t                      | _        t          | j	                  | _
        d| _        |                     ||          | _        | j                            | j
        j                   dS )a4  Create a new instance of the Connection object.

        :param None | pika.connection.Parameters | sequence parameters:
            Connection parameters instance or non-empty sequence of them. If
            None, a `pika.connection.Parameters` instance will be created with
            default settings. See `pika.AMQPConnectionWorkflow` for more
            details about multiple parameter configurations and retries.
        :param _impl_class: for tests/debugging only; implementation class;
            None=default

        :raises RuntimeError:

        r   N)	threadingLock_cleanup_mutex_event_dispatch_suspend_depthr   _ready_eventsset_channels_pending_dispatchr	   _OnClosedArgs_closed_result_impl_create_connectionadd_on_close_callbackr.   )r   
parameters_impl_classs      r   r   zBlockingConnection.__init__B  s    $ (n.. ./* #WW
 +.%%' .d.@AA 
,,ZEE

(()<)KLLLLLr   c                 2    d| j         j        d| j        dS Nr[   z impl=r]   r^   r=   r   r   s    r   r_   zBlockingConnection.__repr__k        !%!8!8!8$***EEr   c                     | S r<   r   r   s    r   r   zBlockingConnection.__enter__n  s    r   c                 @    | j         r|                                  d S d S r<   is_opencloser   exc_typer3   	tracebacks       r   r    zBlockingConnection.__exit__r  s'    < 	JJLLLLL	 	r   c                     | j         5  | j        | j        j                                         | j                                         | j                                         ddd           dS # 1 swxY w Y   dS )z@Clean up members that might inhibit garbage collection

        N)rz   r   ioloopr   r|   clearr   r   r   s    r   _cleanupzBlockingConnection._cleanupw  s       	( 	(z%
!'')))$$&&&%%'''		( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(s   AA--A14A1c              #      K   	 | xj         dz  c_         | j         dk    V  | xj         dz  c_         dS # | xj         dz  c_         w xY w)a\   Context manager that controls access to event dispatcher for
        preventing reentrancy.

        The "as" value is True if the managed code block owns the event
        dispatcher and False if caller higher up in the call stack already owns
        it. Only managed code that gets ownership (got True) is permitted to
        dispatch
        r7   N)r{   r   s    r   _acquire_event_dispatchz*BlockingConnection._acquire_event_dispatch  so      	4..!3..49999 ..!3....D..!3......s	   3 Ac                    |t           j                                        f}t          |t           j        j                  r|f}|s"t	          d                    |                    t          t          dd                    }|pt          j	        }t          j
                    }|                                 	 |                    ||j        |           |j        s/|                                 |                                 |j        /t          |j        j        t&                    r<|j        j        }t(                              d|           |                     |          t(                              d|j        j                   |j        j        S # t0          $ rD t(                              d           |                                 |                                   w xY w)	a  Run connection workflow, blocking until it completes.

        :param None | pika.connection.Parameters | sequence configs: Connection
            parameters instance or non-empty sequence of them.
        :param None | SelectConnection impl_class: for tests/debugging only;
            implementation class;

        :rtype: impl_class

        :raises: exception on failure
        NzEExpected a non-empty sequence of connection parameters, but got {!r}./BlockingConnection_OnConnectionWorkflowDoneArgsresult)on_donecustom_ioloopzConnection workflow failed: %rz!Connection workflow succeeded: %rzError in _create_connection().)pikarN   
Parametersr0   
ValueErrorformatr	   r   r   SelectConnectionIOLoopactivate_pollercreate_connectionr.   r$   pollprocess_timeoutsr3   r   BaseExceptionr,   r-   $_reap_last_connection_workflow_errorinfor+   	exceptionr   r   )r   configs
impl_classon_cw_done_resultr   r-   s         r   r   z%BlockingConnection._create_connection  s    ?11335Ggt9:: 	!jG 	J 99?J J J ,H! !" "  E#4#E
")++   	(()8$ ) & & &
 (- *''))) (- * +18-HH 6)/6=uEEE??FFF?-3:< < <(.55 	 	 	=>>>LLNNNMMOOO		s   ;CF AG(c                     t          | t          j                  r]| j        d         } t          | t          j                  rt          j        |           } n!t          | t          j                  r| j        } | S )a  Extract exception value from the last connection attempt

        :param Exception error: error passed by the `AMQPConnectionWorkflow`
            completion callback.

        :returns: Exception value from the last connection attempt
        :rtype: Exception
        )r0   r   AMQPConnectionWorkflowFailed
exceptionsAMQPConnectorSocketConnectErrorAMQPConnectionErrorAMQPConnectorPhaseErrorBaser   )r-   s    r   r   z7BlockingConnection._reap_last_connection_workflow_error  s}     e0MNN 	($R(E%-MO O ("6u==E/KM M (r   c                 v     j         rt          j                     fd} |            sF j        j                                          j        j                                          |            F j        j        r	 t           j        j
        j        t          j                  s;t                              d j        j
        j                    j        j
        j        t                              d j        j
                   	                                   dS #                                   w xY wdS )a   Flush output and process input while waiting for any of the given
        callbacks to return true. The wait is aborted upon connection-close.
        Otherwise, processing continues until the output is flushed AND at least
        one of the callbacks returns true. If there are no callbacks, then
        processing ends when all output is flushed.

        :param waiters: sequence of zero or more callables taking no args and
                        returning true when it's time to stop processing.
                        Their results are OR'ed together.
        :raises: exceptions passed by impl if opening of connection fails or
            connection closes.
        c                       j         j        pE j        j         s j                                        dk    o pt          d D                       S )Nr   c              3   *   K   | ]} |            V  d S r<   r   ).0r$   s     r   	<genexpr>zEBlockingConnection._flush_output.<locals>.<lambda>.<locals>.<genexpr>  s(      'E'EE'E'E'E'E'E'Er   )r   r$   r   
_transport_get_write_buffer_sizeanyr   waiterss   r   <lambda>z2BlockingConnection._flush_output.<locals>.<lambda>  sd    &, H.. >Z6688A=G [EC'E'EW'E'E'E$E$E	 r   z(Unexpected connection close detected: %rzUser-initiated close: result=%rN)	is_closedr   ConnectionWrongStateErrorr   r   r   r   r   r$   r0   r3   r-   ConnectionClosedByClientr,   r   r   )r   r   is_dones   `` r   _flush_outputz BlockingConnection._flush_output  sT    > 	96888H H H H H ')) 	1J""$$$J..000 ')) 	1 $ 	 
 !$"5";"A","EG G ;LL!K!%!4!:!@B B B-399KK A $ 3 9; ; ; ; 	  	 s    B	D   D6c                 :    | j                             |           dS )a  Called by BlockingChannel instances to request a call to their
        _dispatch_events method or to terminate `process_data_events`;
        BlockingConnection will honor these requests from a safe context.

        :param int channel_number: positive channel number to request a call
            to the channel's `_dispatch_events`; a negative channel number to
            request termination of `process_data_events`
        N)r~   add)r   channel_numbers     r   _request_channel_dispatchz,BlockingConnection._request_channel_dispatch  s!     	'++N;;;;;r   c                    | j         sdS |                                 5 }|s	 ddd           dS t          | j                   }| j                                          |D ]Z}|dk     r		 | j        j        |         }n# t          $ r Y )w xY w|j        r&|                                	                                 [	 ddd           dS # 1 swxY w Y   dS )zXInvoke the `_dispatch_events` method on open channels that requested
        it
        Nr   )
r~   r   r1   r   r   	_channelsKeyErrorr   _get_cookie_dispatch_events)r   dispatch_acquired
candidatesr   impl_channels        r   _dispatch_channel_eventsz+BlockingConnection._dispatch_channel_events  s    . 	F))++ 	B/@$ 	B 	B 	B 	B 	B 	B 	B 	B
 d=>>J+11333", B B!A%%#':#7#GLL   H  ' B ,,..??AAAB	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	Bs:   C8C(A;:C;
BCB1CCCc                 :    | j                             |           dS )zyHandle expiry of a timer that was registered via
        `_adapter_call_later()`

        :param _TimerEvt evt:

        N)r|   r2   r   evts     r   _on_timer_readyz"BlockingConnection._on_timer_ready9  s!     	!!#&&&&&r   c                 2    |                      d|           dS )zHandle callback that was registered via
        `self._impl._adapter_add_callback_threadsafe`.

        :param user_callback: callback passed to our
            `add_callback_threadsafe` by the application.

        r   N)
call_later)r   user_callbacks     r   _on_threadsafe_callbackz*BlockingConnection._on_threadsafe_callbackB  s     	=)))))r   c                 V    | j                             t          ||                     dS )an  Handle Connection.Blocked notification from RabbitMQ broker

        :param callable user_callback: callback passed to
           `add_on_connection_blocked_callback`
        :param select_connection.SelectConnection _impl:
        :param pika.frame.Method method_frame: method frame having `method`
            member of type `pika.spec.Connection.Blocked`
        N)r|   r2   rn   r   r   r   rj   s       r   _on_connection_blockedz)BlockingConnection._on_connection_blockedN  s;     	!!!->>	@ 	@ 	@ 	@ 	@r   c                 V    | j                             t          ||                     dS )ar  Handle Connection.Unblocked notification from RabbitMQ broker

        :param callable user_callback: callback passed to
           `add_on_connection_unblocked_callback`
        :param select_connection.SelectConnection _impl:
        :param pika.frame.Method method_frame: method frame having `method`
            member of type `pika.spec.Connection.Blocked`
        N)r|   r2   rq   r   s       r   _on_connection_unblockedz+BlockingConnection._on_connection_unblockedZ  s;     	!!#M<@@	B 	B 	B 	B 	Br   c                 d   | j         sdS |                                 5 }|s	 ddd           dS t          j        t	          | j                             D ]B}	 | j                                         }n# t          $ r Y  nw xY w|                                 Cddd           dS # 1 swxY w Y   dS )z Dispatch ready connection eventsN)r|   r   compatxranger9   popleft
IndexErrorrc   )r   r   _r   s       r   _dispatch_connection_eventsz.BlockingConnection._dispatch_connection_eventsf  s-   ! 	F))++ 	/@$ 	 	 	 	 	 	 	 	 ]3t'9#:#:;;  ,4466CC!   EE 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s:   B%(B%A21B%2
B <B%?B  B%%B),B)c           	          | j                             t          j        | j        t          j        ||                                dS )aY  RabbitMQ AMQP extension - Add a callback to be notified when the
        connection gets blocked (`Connection.Blocked` received from RabbitMQ)
        due to the broker running low on resources (memory or disk). In this
        state RabbitMQ suspends processing incoming data until the connection
        is unblocked, so it's a good idea for publishers receiving this
        notification to suspend publishing until the connection becomes
        unblocked.

        NOTE: due to the blocking nature of BlockingConnection, if it's sending
        outbound data while the connection is/becomes blocked, the call may
        remain blocked until the connection becomes unblocked, if ever. You
        may use `ConnectionParameters.blocked_connection_timeout` to abort a
        BlockingConnection method call with an exception when the connection
        remains blocked longer than the given timeout value.

        See also `Connection.add_on_connection_unblocked_callback()`

        See also `ConnectionParameters.blocked_connection_timeout`.

        :param callable callback: Callback to call on `Connection.Blocked`,
            having the signature `callback(connection, pika.frame.Method)`,
            where connection is the `BlockingConnection` instance and the method
            frame's `method` member is of type `pika.spec.Connection.Blocked`

        N)r   "add_on_connection_blocked_callback	functoolspartialr   rX   s     r   r   z5BlockingConnection.add_on_connection_blocked_callback{  sT    4 	
55d9'/$??A A	B 	B 	B 	B 	Br   c           	          | j                             t          j        | j        t          j        ||                                dS )a#  RabbitMQ AMQP extension - Add a callback to be notified when the
        connection gets unblocked (`Connection.Unblocked` frame is received from
        RabbitMQ) letting publishers know it's ok to start publishing again.

        :param callable callback: Callback to call on Connection.Unblocked`,
            having the signature `callback(connection, pika.frame.Method)`,
            where connection is the `BlockingConnection` instance and the method
            frame's `method` member is of type `pika.spec.Connection.Unblocked`

        N)r   $add_on_connection_unblocked_callbackr   r   r   rX   s     r   r   z7BlockingConnection.add_on_connection_unblocked_callback  sT     	
77d;'/$??A A	B 	B 	B 	B 	Br   c                     t          j        |           t          |          }| j                            |t          j        | j        |                    }||_        |S )a  Create a single-shot timer to fire after delay seconds. Do not
        confuse with Tornado's timeout where you pass in the time you want to
        have your callback called. Only pass in the seconds until it's to be
        called.

        NOTE: the timer callbacks are dispatched only in the scope of
        specially-designated methods: see
        `BlockingConnection.process_data_events()` and
        `BlockingChannel.start_consuming()`.

        :param float delay: The number of seconds to wait to call callback
        :param callable callback: The callback method with the signature
            callback()
        :returns: Opaque timer id
        :rtype: int

        )rY   )	
validatorsrequire_callbackrT   r   rG   r   r   r   rU   )r   delayrY   r   rU   s        r   r   zBlockingConnection.call_later  s_    $ 	#H---***:119$T%93??A Ar   c                     | j         5  | j        rt          j        d          | j                            t          j        | j        |                     ddd           dS # 1 swxY w Y   dS )a  Requests a call to the given function as soon as possible in the
        context of this connection's thread.

        NOTE: This is the only thread-safe method in `BlockingConnection`. All
        other manipulations of `BlockingConnection` must be performed from the
        connection's thread.

        NOTE: the callbacks are dispatched only in the scope of
        specially-designated methods: see
        `BlockingConnection.process_data_events()` and
        `BlockingChannel.start_consuming()`.

        For example, a thread may request a call to the
        `BlockingChannel.basic_ack` method of a `BlockingConnection` that is
        running in a different thread via::

            connection.add_callback_threadsafe(
                functools.partial(channel.basic_ack, delivery_tag=...))

        NOTE: if you know that the requester is running on the same thread as
        the connection it is more efficient to use the
        `BlockingConnection.call_later()` method with a delay of 0.

        :param callable callback: The callback method; must be callable
        :raises pika.exceptions.ConnectionWrongStateError: if connection is
            closed
        zTBlockingConnection.add_callback_threadsafe() called on closed or closing connection.N)	rz   r   r   r   r    _adapter_add_callback_threadsafer   r   r   rX   s     r   add_callback_threadsafez*BlockingConnection.add_callback_threadsafe  s    8   	K 	K ~ 5 :45 5 5 J77!$">IIK K K	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	Ks   AA##A'*A'c                     | j                             |           t          | j                  D ])\  }}t	          |t
                    r|j        |k    r|} n*dS | j        |= dS )zuRemove a timer if it's still in the timeout stack

        :param timeout_id: The opaque timer id to remove

        N)r   rQ   	enumerater|   r0   rT   rU   )r   
timeout_idir   index_to_removes        r   remove_timeoutz!BlockingConnection.remove_timeout  s{     	
**:666   233 	 	FAs#y)) clj.H.H"# F///r   c                     t                      }| j                            |||j                   |                     |j                   dS )a  RabbitMQ AMQP extension - This method updates the secret used to authenticate this connection. 
        It is used when secrets have an expiration date and need to be renewed, like OAuth 2 tokens.

        :param string new_secret: The new secret
        :param string reason: The reason for the secret update

        :raises pika.exceptions.ConnectionWrongStateError: if connection is
            not open.
        N)r	   r   update_secretr)   r   r   )r   
new_secretreasonr   s       r   r   z BlockingConnection.update_secret  sH     !""
  VV5GHHH6?+++++r      Normal shutdownc                 t   | j         sOd                    | j        j        ||          }t                              |           t          j        |          t                              d||           t          j
        | j        j                  D ]l}|                                }|j         rO	 |                    ||           5# t          j        $ r%}t                              d|           Y d}~dd}~ww xY wm| j                            ||           |                     | j        j                   dS )a&  Disconnect from RabbitMQ. If there are any open channels, it will
        attempt to close them prior to fully disconnecting. Channels which
        have active consumers will attempt to send a Basic.Cancel to RabbitMQ
        to cleanly stop the delivery of messages prior to closing the channel.

        :param int reply_code: The code number for the close
        :param str reply_text: The text reason for the close

        :raises pika.exceptions.ConnectionWrongStateError: if called on a closed
            connection (NEW in v1.0.0)
        z/{}.close({}, {!r}) called on closed connection.zClosing connection (%s): %szAGot ChannelClosed while closing channel from connection.close: %rN)r   r   r^   r=   r,   r-   r   r   r   r   
dictvaluesr   r   r   r   ChannelClosedwarningr   r   r   )r   
reply_code
reply_textmsgr   rv   excs          r   r   zBlockingConnection.close  s[    | 	<CJJ'ZA ACLL6s;;;1:zJJJ #-dj.BCC 		: 		:L"..00G ::MM*j9999!/ : : :NN458: : : : : : : ::: 	
Z0004.788888s   /CC:C55C:r   c                                                       5  fd}|                     |           nHt          | j                  5 }                     |j        |           ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y    j        r                                   j        r                                  dS dS )a  Will make sure that data events are processed. Dispatches timer and
        channel callbacks if not called from the scope of BlockingConnection or
        BlockingChannel callback. Your app can block on this method. If your
        application maintains a long-lived publisher connection, this method
        should be called periodically in order to respond to heartbeats and other
        data events. See `examples/long_running_publisher.py` for an example.

        :param float time_limit: suggested upper bound on processing time in
            seconds. The actual blocking time depends on the granularity of the
            underlying ioloop. Zero means return as soon as possible. None means
            there is no limit on processing time and the function will block
            until I/O produces actionable events. Defaults to 0 for backward
            compatibility. This parameter is NEW in pika 0.10.0.
        c                  >    t           oj        pj                  S r<   )boolr~   r|   )r   r   s   r   r   z8BlockingConnection.process_data_events.<locals>.<lambda>F  s.    -> .B.2.M /A.2.@)C )C r   N)	r   r   rE   r   r   r|   r   r~   r   )r   
time_limitcommon_terminatortimerr   s   `   @r   process_data_eventsz&BlockingConnection.process_data_events5  s    ))++ 		J/@!C !C !C !C !C !""#45555(TZ@@ JE&&u~7HIIIJ J J J J J J J J J J J J J J		J 		J 		J 		J 		J 		J 		J 		J 		J 		J 		J 		J 		J 		J 		J  	/,,...* 	,))+++++	, 	,s5   4B
A3'B
3A7	7B
:A7	;B

BBc                     |dk    s
J |            t          j                    |z   }|}	 |                     |           |t          j                    z
  }|dk    rdS 4)aB  A safer way to sleep than calling time.sleep() directly that would
        keep the adapter from ignoring frames sent from the broker. The
        connection will "sleep" or block the number of seconds specified in
        duration in small intervals.

        :param float duration: The time to sleep in seconds

        r   TN)r   time_nowr  )r   rM   deadliner
  s       r   sleepzBlockingConnection.sleepU  sl     1}}}h}}}?$$x/
	$$Z000!FO$5$55JQ		r   c                    t          | j                  5 }| j                            ||j                  }t          ||           }|                    |           |                    |j                   ddd           n# 1 swxY w Y   |S )a5  Create a new channel with the next available channel number or pass
        in a channel number to use. Must be non-zero if you would like to
        specify but it is recommended that you let Pika manage the channel
        numbers.

        :rtype: pika.adapters.blocking_connection.BlockingChannel
        )r   on_open_callbackN)	r	   _OnChannelOpenedArgsr   rv   r.   BlockingChannel_set_cookier   r   )r   r   opened_argsr   rv   s        r   rv   zBlockingConnection.channeli  s     T677 	8;:---!,!; . = =L
 &lD99G $$W--- !!+"6777	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 s   A!BB	Bc                     | j         j        S zK
        Returns a boolean reporting the current connection state.
        r   r   r   s    r   r   zBlockingConnection.is_closed  s    
 z##r   c                     | j         j        S r  r   r   r   s    r   r   zBlockingConnection.is_open  s    
 z!!r   c                     | j         j        S )zeSpecifies if the server supports basic.nack on the active connection.

        :rtype: bool

        )r   
basic_nackr   s    r   basic_nack_supportedz'BlockingConnection.basic_nack_supported  s     z$$r   c                     | j         j        S )zSpecifies if the server supports consumer cancel notification on the
        active connection.

        :rtype: bool

        )r   consumer_cancel_notifyr   s    r    consumer_cancel_notify_supportedz3BlockingConnection.consumer_cancel_notify_supported  s     z00r   c                     | j         j        S )zrSpecifies if the active connection supports exchange to exchange
        bindings.

        :rtype: bool

        )r   exchange_exchange_bindingsr   s    r   $exchange_exchange_bindings_supportedz7BlockingConnection.exchange_exchange_bindings_supported  s     z44r   c                     | j         j        S )zcSpecifies if the active connection can use publisher confirmations.

        :rtype: bool

        )r   publisher_confirmsr   s    r   publisher_confirms_supportedz/BlockingConnection.publisher_confirms_supported  s     z,,r   NN)r   r   )r   r<   )/r=   r>   r?   r@   r   r   r  r   r_   r   r    r   
contextlibcontextmanagerr   r   staticmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  rv   rC   r   r   r  r"  r%  r(  r  r!  r$  r'  r   r   r   rs   rs     s       0 0d JA13 3M &:&O&/1 1'M 'M 'M 'MRF F F    
( ( ( 4 4 4"9 9 9v   \*,  ,  , \	< 	< 	<B B B8' ' '
* 
* 
*
@ 
@ 
@
B 
B 
B  *B B B<B B B  6(K (K (KT0 0 0(, , ,#9 #9 #9 #9J, , , ,@  (   8 $ $ X$ " " X" % % X% 1 1 X1 5 5 X5 - - X- &J=!E5r   rs   c                       e Zd ZdZdS )_ChannelPendingEvtz-Base class for BlockingChannel pending eventsNro   r   r   r   r.  r.    s        7777r   r.  c                       e Zd ZdZdZd ZdS )_ConsumerDeliveryEvtzThis event represents consumer message delivery `Basic.Deliver`; it
    contains method, properties, and body of the delivered message.
    method
propertiesbodyc                 0    || _         || _        || _        dS )a
  
        :param spec.Basic.Deliver method: NOTE: consumer_tag and delivery_tag
          are valid only within source channel
        :param spec.BasicProperties properties: message properties
        :param bytes body: message body; empty string if no body
        Nr1  r   r2  r3  r4  s       r   r   z_ConsumerDeliveryEvt.__init__  s     $			r   Nr=   r>   r?   r@   rA   r   r   r   r   r0  r0    s4          1I	 	 	 	 	r   r0  c                   8    e Zd ZdZdZd Zd Zed             ZdS )_ConsumerCancellationEvtzThis event represents server-initiated consumer cancellation delivered to
    client via Basic.Cancel. After receiving Basic.Cancel, there will be no
    further deliveries for the consumer identified by `consumer_tag` in
    `Basic.Cancel`
    rj   c                     || _         dS )zy
        :param pika.frame.Method method_frame: method frame with method of type
            `spec.Basic.Cancel`
        Nr:  )r   rj   s     r   r   z!_ConsumerCancellationEvt.__init__  s    
 )r   c                 2    d| j         j        d| j        dS )Nr[   z method_frame=r]   )r^   r=   rj   r   s    r   r_   z!_ConsumerCancellationEvt.__repr__  s(     )-)@)@)@)-):):):< 	<r   c                     | j         j        S )z method of type spec.Basic.Cancel)rj   r2  r   s    r   r2  z_ConsumerCancellationEvt.method  s      ''r   N)	r=   r>   r?   r@   rA   r   r_   rC   r2  r   r   r   r9  r9    s^          "I) ) )< < < ( ( X( ( (r   r9  c                   (    e Zd ZdZdZd Zd Zd ZdS )_ReturnedMessageEvtzEThis event represents a message returned by broker via `Basic.Return`rY   rv   r2  r3  r4  c                 L    || _         || _        || _        || _        || _        dS )a  
        :param callable callback: user's callback, having the signature
            callback(channel, method, properties, body), where
             - channel: pika.Channel
             - method: pika.spec.Basic.Return
             - properties: pika.spec.BasicProperties
             - body: bytes
        :param pika.Channel channel:
        :param pika.spec.Basic.Return method:
        :param pika.spec.BasicProperties properties:
        :param bytes body:
        Nr@  )r   rY   rv   r2  r3  r4  s         r   r   z_ReturnedMessageEvt.__init__  s+     !$			r   c                 ^    d| j         j        | j        | j        | j        | j        | j        fz  S )Nz?<%s callback=%r channel=%r method=%r properties=%r body=%.300r>)r^   r=   rY   rv   r2  r3  r4  r   s    r   r_   z_ReturnedMessageEvt.__repr__  s4    #'>#:DM#'<do#'9#.. 	.r   c                 ^    |                      | j        | j        | j        | j                   dS )zDispatch user's callbackNr@  r   s    r   rc   z_ReturnedMessageEvt.dispatch  s(    dlDK$)LLLLLr   Nrd   r   r   r   r?  r?    sQ        OOGI  &. . .M M M M Mr   r?  c                       e Zd ZdZdZd ZdS )ReturnedMessagezWRepresents a message returned via Basic.Return in publish-acknowledgments
    mode
    r1  c                 0    || _         || _        || _        dS )z
        :param spec.Basic.Return method:
        :param spec.BasicProperties properties: message properties
        :param bytes body: message body; empty string if no body
        Nr1  r6  s       r   r   zReturnedMessage.__init__  s     $			r   Nr7  r   r   r   rE  rE    s4          1I    r   rE  c                       e Zd ZdZdZdZdZdZdZ	 	 ddZ	e
d	             Ze
d
             Ze
d             Ze
d             ZdS )_ConsumerInfoz$Information about an active consumer)consumer_tagauto_ackon_message_callbackalternate_event_sinkstater7            Nc                     |du |du k    sJ d||f            || _         || _        || _        || _        | j        | _        dS )aM  
        NOTE: exactly one of callback/alternate_event_sink musts be non-None.

        :param str consumer_tag:
        :param bool auto_ack: the no-ack value for the consumer
        :param callable on_message_callback: The function for dispatching messages to
            user, having the signature:
            on_message_callback(channel, method, properties, body)
             - channel: BlockingChannel
             - method: spec.Basic.Deliver
             - properties: spec.BasicProperties
             - body: bytes
        :param callable alternate_event_sink: if specified, _ConsumerDeliveryEvt
            and _ConsumerCancellationEvt objects will be diverted to this
            callback instead of being deposited in the channel's
            `_pending_events` container. Signature:
            alternate_event_sink(evt)
        NHexactly one of on_message_callback/alternate_event_sink must be non-None)rI  rJ  rK  rL  
SETTING_UPrM  )r   rI  rJ  rK  rL  s        r   r   z_ConsumerInfo.__init__6  sn    . $t+ D(
 
 
V!57
 
 
 ) #6 $8!_


r   c                 "    | j         | j        k    S )zTrue if in SETTING_UP state)rM  rS  r   s    r   
setting_upz_ConsumerInfo.setting_upW  s     zT_,,r   c                 "    | j         | j        k    S )zTrue if in ACTIVE state)rM  ACTIVEr   s    r   activez_ConsumerInfo.active\  s     zT[((r   c                 "    | j         | j        k    S )zTrue if in TEARING_DOWN state)rM  TEARING_DOWNr   s    r   tearing_downz_ConsumerInfo.tearing_downa  s     zT...r   c                 "    | j         | j        k    S )z$True if in CANCELLED_BY_BROKER state)rM  CANCELLED_BY_BROKERr   s    r   cancelled_by_brokerz!_ConsumerInfo.cancelled_by_brokerf  s     zT555r   r)  )r=   r>   r?   r@   rA   rS  rW  rZ  r]  r   rC   rU  rX  r[  r^  r   r   r   rH  rH  *  s        ..2I JFL
 &*&*	% % % %B - - X- ) ) X) / / X/ 6 6 X6 6 6r   rH  c                   "    e Zd ZdZdZd Zd ZdS )_QueueConsumerGeneratorInfozDContainer for information about the active queue consumer generator )paramsrI  pending_eventsc                 H    || _         || _        t                      | _        dS )z
        :params tuple params: a three-tuple (queue, auto_ack, exclusive) that were
           used to create the queue consumer
        :param str consumer_tag: consumer tag
        N)ra  rI  r   rb  )r   ra  rI  s      r   r   z$_QueueConsumerGeneratorInfo.__init__p  s'     (
 $ggr   c                 B    d| j         j        d| j        d| j        dS )Nr[   z params=z consumer_tag=r]   )r^   r=   ra  rI  r   s    r   r_   z$_QueueConsumerGeneratorInfo.__repr__~  s1     N###T[[[$2C2C2CE 	Er   N)r=   r>   r?   r@   rA   r   r_   r   r   r   r`  r`  l  sB        NN<I& & &E E E E Er   r`  c                      e Zd ZdZ edg d          Z edd          Z edd          Z edd          Zd	Z	d
 Z
d Zd Zd Zd Zd Zed             Zed             Zed             Zed             Zed             Zd fZd Zd Zd Zd Zd Zd Zd Zd Zd ZdGd!Z d" Z!d# Z"d$ Z#	 	 	 	 dHd'Z$	 	 	 dId(Z%d) Z&d* Z'd+ Z(dJd,Z)	 	 	 	 dHd-Z*d. Z+d/ Z,d0 Z-dKd1Z.dLd3Z/dMd4Z0	 	 dNd5Z1dOd6Z2dMd7Z3dPd8Z4d9 Z5e6j7        d%d%d%d%d&fd:Z8dNd;Z9	 	 dQd=Z:	 	 	 	 dRd>Z;	 	 	 	 	 dSd?Z<dTd@Z=dA Z>dUdBZ?	 	 	 dIdCZ@dD ZAdE ZBdF ZCd&S )Vr  al  The BlockingChannel implements blocking semantics for most things that
    one would use callback-passing-style for with the
    :py:class:`~pika.channel.Channel` class. In addition,
    the `BlockingChannel` class implements a :term:`generator` that allows
    you to :doc:`consume messages </examples/blocking_consumer_generator>`
    without using callbacks.

    Example of creating a BlockingChannel::

        import pika

        # Create our connection object
        connection = pika.BlockingConnection()

        # The returned object will be a synchronous channel
        channel = connection.channel()

    BlockingChannel__RxMessageArgs)rv   r2  r3  r4  .BlockingChannel__MethodFrameCallbackResultArgsrj   0BlockingChannel__OnMessageConfirmationReportArgs)BlockingChannel__FlowOkCallbackResultArgsrX  #blocking_channel_consumer_cancelledc                    || _         || _        t                      | _        d| _        d| _        t          | j                  | _        t                      | _
        d| _        d| _        t                      | _        t          | j                  | _        | j                             | j                   | j                             | j        j        t(          j        j        j        gd           | j                             | j                   | j                             | j        j        t(          j        j        j        gd           t8                              d| j                   dS )zCreate a new instance of the Channel

        :param pika.channel.Channel channel_impl: Channel implementation object
            as returned from SelectConnection.channel()
        :param BlockingConnection connection: The connection object

        NF)repliesone_shotzCreated channel=%s)r   rJ   dict_consumer_infos_queue_consumer_generator_delivery_confirmationr	    _OnMessageConfirmationReportArgs_message_confirmation_resultr   _pending_events_puback_return_closing_reason_basic_consume_ok_result_MethodFrameCallbackResultArgs_basic_getempty_resultadd_on_cancel_callback _on_consumer_cancelled_by_brokeradd_callbackr)   r   specBasic	ConsumeOkr   _on_channel_closedr.   GetEmptyr,   r   r   )r   channel_implrN   s      r   r   zBlockingChannel.__init__  sa    "
%  $vv *.& ',# -<1-3 -3)  %ww #  $ )8(9(9% '6/'1 '1# 	
))$*OPPP
)5Y_./ 	  	 	 	
 	
(()@AAA
'6Y_-. 	  	 	 	
 	($*=>>>>>r   c                     | j         S )zReturn the channel object as its channel number

        NOTE: inherited from legacy BlockingConnection; might be error-prone;
        use `channel_number` property instead.

        :rtype: int

        )r   r   s    r   __int__zBlockingChannel.__int__  s     ""r   c                 2    d| j         j        d| j        dS r   r   r   s    r   r_   zBlockingChannel.__repr__  r   r   c                     | S r<   r   r   s    r   r   zBlockingChannel.__enter__   s    r   c                 @    | j         r|                                  d S d S r<   r   r   s       r   r    zBlockingChannel.__exit__  s'    < 	JJLLLLL	 	r   c                     | j                                          t                      | _        t	                      | _        d| _        dS )z6Clean up members that might inhibit garbage collectionN)rs  r   r   rt  rn  ro  rp  r   s    r   r   zBlockingChannel._cleanup  s=    )//111$ww#vv)-&&&r   c                     | j         j        S )zChannel number)r   r   r   s    r   r   zBlockingChannel.channel_number  s     z((r   c                     | j         S )z)The channel's BlockingConnection instance)rJ   r   s    r   rN   zBlockingChannel.connection  s     r   c                     | j         j        S )zFReturns True if the channel is closed.

        :rtype: bool

        r  r   s    r   r   zBlockingChannel.is_closed  s     z##r   c                     | j         j        S )zDReturns True if the channel is open.

        :rtype: bool

        r  r   s    r   r   zBlockingChannel.is_open!  s     z!!r   c                 4    t          j        | j                  S )zqProperty method that returns a list of consumer tags for active
        consumers

        :rtype: list

        )r   dictkeysro  r   s    r   consumer_tagszBlockingChannel.consumer_tags*  s     t3444r   c                      dS )NTr   r   r   r   r   zBlockingChannel.<lambda>4  s    d r   c                       j         r j                                         |s j        }  j        j         fdg|R    j         r&t           j        t          j	                  r	 j        dS dS )a   Flush output and process input while waiting for any of the given
        callbacks to return true. The wait is aborted upon channel-close or
        connection-close.
        Otherwise, processing continues until the output is flushed AND at least
        one of the callbacks returns true. If there are no callbacks, then
        processing ends when all output is flushed.

        :param waiters: sequence of zero or more callables taking no args and
                        returning true when it's time to stop processing.
                        Their results are OR'ed together. An empty sequence is
                        treated as equivalent to a waiter always returning true.
        c                       j         S r<   r   r   s   r   r   z/BlockingChannel._flush_output.<locals>.<lambda>I  s	    t~ r   N)
r   r   _raise_if_not_open_ALWAYS_READY_WAITERSrJ   r   r0   rv  r   ChannelClosedByBrokerr   s   ` r   r   zBlockingChannel._flush_output6  s     > 	,J))+++ 	10G&&'='='='=HHHHH> 	'j)=)3)IK K 	'&&	' 	' 	' 	'r   c           
         || j         u sJ |j        | j        f            t          |t          j        j        j                  s
J |            t          |t          j        j                  s
J |            t          	                    d| j
        |j        |||t          |          nd|           t          |||          | _        dS )a  Called as the result of Basic.Return from broker in
        publisher-acknowledgements mode. Saves the info as a ReturnedMessage
        instance in self._puback_return.

        :param pika.Channel channel: our self._impl channel
        :param pika.spec.Basic.Return method:
        :param pika.spec.BasicProperties properties: message properties
        :param bytes body: returned message body; empty string if no body
        zPublished message was returned: _delivery_confirmation=%s; channel=%s; method=%r; properties=%r; body_size=%d; body_prefix=%.255rN)r   r   r0   r   r}  r~  ReturnBasicPropertiesr,   r  rq  r9   rE  ru  )r   rv   r2  r3  r4  s        r   _on_puback_message_returnedz+BlockingChannel._on_puback_message_returnedO  s     $*$$$w'='+':'<$$$ &$)/"899AA6AAA*di&?@@NN:NNN!"&"="FJ)CIIItT	; 	; 	; .fj$GGr   c                 x    | j                             |           | j                            | j                   dS )a  Append an event to the channel's list of events that are ready for
        dispatch to user and signal our connection that this channel is ready
        for event dispatch

        :param _ChannelPendingEvt evt: an event derived from _ChannelPendingEvt
        N)rt  r2   rN   r   r   r   s     r   _add_pending_eventz"BlockingChannel._add_pending_eventh  s:     	##C(((11$2EFFFFFr   c                     t                               d||            || _        t          |t          j                  r6|                                  | j                            | j	                    dS dS )a/  Callback from impl notifying us that the channel has been closed.
        This may be as the result of user-, broker-, or internal connection
        clean-up initiated closing or meta-closing of the channel.

        If it resulted from receiving `Channel.Close` from broker, we will
        expedite waking up of the event subsystem so that it may respond by
        raising `ChannelClosed` from user's context.

        NOTE: We can't raise exceptions in callbacks in order to protect
        the integrity of the underlying implementation. BlockingConnection's
        underlying asynchronous connection adapter (SelectConnection) uses
        callbacks to communicate with us. If BlockingConnection leaks exceptions
        back into the I/O loop or the asynchronous connection adapter, we
        interrupt their normal workflow and introduce a high likelihood of state
        inconsistency.

        See `pika.Channel.add_on_close_callback()` for additional documentation.

        :param pika.Channel _channel: (unused)
        :param Exception reason:

        z_on_channel_closed: %r; %rN)
r,   rb   rv  r0   r   r  r   rN   r   r   )r   _channelr   s      r   r  z"BlockingChannel._on_channel_closedr  sv    . 	164@@@%fj>?? 	LMMOOO O55t7J6JKKKKK	L 	Lr   c                     t          |          }| j        |j        j                 }|j        st
          j        |_        |j        |                    |           dS | 	                    |           dS )aw  Called by impl when broker cancels consumer via Basic.Cancel.

        This is a RabbitMQ-specific feature. The circumstances include deletion
        of queue being consumed as well as failure of a HA node responsible for
        the queue being consumed.

        :param pika.frame.Method method_frame: method frame with the
            `spec.Basic.Cancel` method

        N)
r9  ro  r2  rI  r[  rH  r]  rM  rL  r  )r   rj   r   consumers       r   r{  z0BlockingChannel._on_consumer_cancelled_by_broker  sx     '|44'(;(HI $ 	?*>HN(4))#.....##C(((((r   c                     t          |||          }| j        |j                 }|j        |                    |           dS |                     |           dS )aB  Called by impl when a message is delivered for a consumer

        :param Channel channel: The implementation channel object
        :param spec.Basic.Deliver method:
        :param pika.spec.BasicProperties properties: message properties
        :param bytes body: delivered message body; empty string if no body
        N)r0  ro  rI  rL  r  )r   r  r2  r3  r4  r   r  s          r   _on_consumer_message_deliveryz-BlockingChannel._on_consumer_message_delivery  sb     #6:t<<'(;<(4))#.....##C(((((r   c                     | j         j                            |           | j                            | j                    dS )zSink for the queue consumer generator's consumer events; append the
        event to queue consumer generator's pending events buffer.

        :param evt: an object of type _ConsumerDeliveryEvt or
          _ConsumerCancellationEvt
        N)rp  rb  r2   rN   r   r   r   s     r   _on_consumer_generator_eventz,BlockingChannel._on_consumer_generator_event  sB     	&5<<SAAA 	1143F2FGGGGGr   c                 
   | j         ryt                              dt          | j                              | j        |                                  t          j        | j                   D ]}|                     |           dS dS )zCancel all consumers.

        NOTE: pending non-ackable messages will be lost; pending ackable
        messages will be rejected.

        zCancelling %i consumersN)	ro  r,   rb   r9   rp  cancelr   r  basic_cancelr   rI  s     r   _cancel_all_consumersz%BlockingChannel._cancel_all_consumers  s      		0LL2C8L4M4MNNN-9 !'0D E E 0 0!!,////		0 		00 0r   c                    | j         r| j                                         }t          |          t          u r?| j        |j        j                 }|                    | |j        |j        |j	                   nst          |          t          u rI| j        |j        j        j        = | j        j                            | j        | j        | |j                   n|                                 | j         dS dS )zCalled by BlockingConnection to dispatch pending events.

        `BlockingChannel` schedules this callback via
        `BlockingConnection._request_channel_dispatch`
        N)rt  r   typer0  ro  r2  rI  rK  r3  r4  r9  rj   r   	callbacksprocessr   _CONSUMER_CANCELLED_CB_KEYrc   )r   r   consumer_infos      r   r   z BlockingChannel._dispatch_events  s    " 	&..00CCyy000 $ 4SZ5L M11$
25.#(L L L L c666()9)@)MN
$,,T-@-1-L-133CE E E E  " 	 	 	 	 	r   r   r   c                 ^    t                               d||            j                                         	                                    j                            ||                                 fd                                             dS #                                   w xY w)zWill invoke a clean shutdown of the channel with the AMQP Broker.

        :param int reply_code: The reply code to close the channel with
        :param str reply_text: The reply text to close the channel with

        zChannel.close(%s, %s))r  r  c                       j         S r<   r  r   s   r   r   z'BlockingChannel.close.<locals>.<lambda>  s	    t~ r   N)r,   rb   r   r  r  r   r   r   )r   r  r  s   `  r   r   zBlockingChannel.close  s     	,j*EEE
%%'''	&&((( J
zJJJ5555666MMOOOOODMMOOOOs   AB B,c                     t          | j                  5 }| j                            ||j                   |                     |j                   |j        j        cddd           S # 1 swxY w Y   dS )a7  Turn Channel flow control off and on.

        NOTE: RabbitMQ doesn't support active=False; per
        https://www.rabbitmq.com/specification.html: "active=false is not
        supported by the server. Limiting prefetch with basic.qos provides much
        better control"

        For more information, please reference:

        http://www.rabbitmq.com/amqp-0-9-1-reference.html#channel.flow

        :param bool active: Turn flow on (True) or off (False)
        :returns: True if broker will start or continue sending; False if not
        :rtype: bool

        )rX  rY   N)	r	   _FlowOkCallbackResultArgsr   flowr.   r   r   r3   rX  )r   rX  flow_ok_results      r   r  zBlockingChannel.flow  s    " T;<< 	/JOO(E  G G G~6777!'.		/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/   AA))A-0A-c                 `    | j         j                            | j        | j        |d           dS )a  Pass a callback function that will be called when Basic.Cancel
        is sent by the broker. The callback function should receive a method
        frame parameter.

        :param callable callback: a callable for handling broker's Basic.Cancel
            notification with the call signature: callback(method_frame)
            where method_frame is of type `pika.frame.Method` with method of
            type `spec.Basic.Cancel`

        F)rm  N)r   r  r   r   r  rX   s     r   rz  z&BlockingChannel.add_on_cancel_callback  sB     	
  +	 	! 	 	 	 	 	r   c                 F      j                              fd           dS )a  Pass a callback function that will be called when a published
        message is rejected and returned by the server via `Basic.Return`.

        :param callable callback: The method to call on callback with the
            signature callback(channel, method, properties, body), where
            - channel: pika.Channel
            - method: pika.spec.Basic.Return
            - properties: pika.spec.BasicProperties
            - body: bytes

        c           	      P                         t          |||                    S r<   )r  r?  )r  r2  r3  r4  rY   r   s       r   r   z8BlockingChannel.add_on_return_callback.<locals>.<lambda><  s7    ''' $
DB BC C r   N)r   add_on_return_callbackrX   s   ``r   r  z&BlockingChannel.add_on_return_callback/  sM     	
))D D D D D	E 	E 	E 	E 	Er   FNc                     t          j        |d           t          j        |d           |                     ||||||          S )a  Sends the AMQP command Basic.Consume to the broker and binds messages
        for the consumer_tag to the consumer callback. If you do not pass in
        a consumer_tag, one will be automatically generated for you. Returns
        the consumer tag.

        NOTE: the consumer callbacks are dispatched only in the scope of
        specially-designated methods: see
        `BlockingConnection.process_data_events` and
        `BlockingChannel.start_consuming`.

        For more information about Basic.Consume, see:
        http://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume

        :param str queue: The queue from which to consume
        :param callable on_message_callback: Required function for dispatching messages
            to user, having the signature:
            on_message_callback(channel, method, properties, body)
            - channel: BlockingChannel
            - method: spec.Basic.Deliver
            - properties: spec.BasicProperties
            - body: bytes
        :param bool auto_ack: if set to True, automatic acknowledgement mode will be used
                              (see http://www.rabbitmq.com/confirms.html). This corresponds
                              with the 'no_ack' parameter in the basic.consume AMQP 0.9.1
                              method
        :param bool exclusive: Don't allow other consumers on the queue
        :param str consumer_tag: You may specify your own consumer tag; if left
          empty, a consumer tag will be generated automatically
        :param dict arguments: Custom key/value pair arguments for the consumer
        :returns: consumer tag
        :rtype: str
        :raises pika.exceptions.DuplicateConsumerTag: if consumer with given
            consumer_tag is already present.

        queuerK  )r  rK  rJ  	exclusiverI  	arguments)r   require_stringr   _basic_consume_impl)r   r  rK  rJ  r  rI  r  s          r   basic_consumezBlockingChannel.basic_consumeA  s\    T 	!%111#$79NOOO'' 3% ( ! ! 	!r   c           	         |du |du k    rt          d||f          |s| j                                        }|| j        v rt	          j        |          t          ||||          | j        |<   	 | j        5 }| j                            | j	        |||||          }	|	|k    sJ |	|f            | 
                    |j                   ddd           n# 1 swxY w Y   n@# t          $ r3 || j        v r(| j        |= | j                            | j                     w xY w| j        |         j        rt          j        | j        |         _        |S )a  The low-level implementation used by `basic_consume` and `consume`.
        See `basic_consume` docstring for more info.

        NOTE: exactly one of on_message_callback/alternate_event_sink musts be
        non-None.

        This method has one additional parameter alternate_event_sink over the
        args described in `basic_consume`.

        :param callable alternate_event_sink: if specified, _ConsumerDeliveryEvt
            and _ConsumerCancellationEvt objects will be diverted to this
            callback instead of being deposited in the channel's
            `_pending_events` container. Signature:
            alternate_event_sink(evt)

        :raises pika.exceptions.DuplicateConsumerTag: if consumer with given
            consumer_tag is already present.

        NrR  )rJ  rK  rL  )rK  r  rJ  r  rI  r  )r   r   _generate_consumer_tagro  r   DuplicateConsumerTagrH  rw  r  r  r   r   r+   rN   r   r   rU  rW  rM  )
r   r  rJ  r  rI  r  rK  rL  	ok_resulttags
             r   r  z#BlockingChannel._basic_consume_implu  s   6  4'-AT-IJJ 35IKL L L  	?
  :<<>>L4///1,??? .; 3!5	.7 .7 .7\*	. 7)j..(,(J%'!-' / ) ) l***S,,?***""9#56667 7 7 7 7 7 7 7 7 7 7 7 7 7 7  	 	 	t333(6 994;N:NOOO	 -8 	L7D7KD .4s1   1C" 8AC
C" CC" CC" "=Dc                 :    	  j                  }n-# t          $ r  t                              d           g cY S w xY w	 |j        s|j        sJ |j                    |j        s j        j        v s
J             |j	        }t          j        |_        t                      5 }|sB                               }|r+|D ](} j                            |j        j        d           ) j                            |j                                        |j         fd           ddd           n# 1 swxY w Y   |rQd                                D              j         v r) j         =  j                             j                    S S                                }|r
J |            g  j         v r) j         =  j                             j                    S S #  j         v r) j         =  j                             j                    w w xY w)a  This method cancels a consumer. This does not affect already
        delivered messages, but it does mean the server will not send any more
        messages for that consumer. The client may receive an arbitrary number
        of messages in between sending the cancel method and receiving the
        cancel-ok reply.

        NOTE: When cancelling an auto_ack=False consumer, this implementation
        automatically Nacks and suppresses any incoming messages that have not
        yet been dispatched to the consumer's callback. However, when cancelling
        a auto_ack=True consumer, this method will return any pending messages
        that arrived before broker confirmed the cancellation.

        :param str consumer_tag: Identifier for the consumer; the result of
            passing a consumer_tag that was created on another channel is
            undefined (bad things will happen)
        :returns: (NEW IN pika 0.10.0) empty sequence for a auto_ack=False
            consumer; for a auto_ack=True consumer, returns a (possibly empty)
            sequence of pending messages that arrived before broker confirmed
            the cancellation (this is done instead of via consumer's callback in
            order to prevent reentrancy/recursion. Each message is four-tuple:
            (channel, method, properties, body)
            - channel: BlockingChannel
            - method: spec.Basic.Deliver
            - properties: spec.BasicProperties
            - body: bytes
        :rtype: list
        zYUser is attempting to cancel an unknown consumer=%s; already cancelled by user or broker?Trequeue)rI  rY   c                        j         j        vS r<   )r   
_consumers)rI  r   s   r   r   z.BlockingChannel.basic_cancel.<locals>.<lambda>  s    L
0EE r   Nc                 6    g | ]}|j         |j        |j        fS r   r1  )r   r   s     r   
<listcomp>z0BlockingChannel.basic_cancel.<locals>.<listcomp>  s5        S^SX>   r   )ro  r   r,   r  rX  r^  rM  r   r  rJ  rH  rZ  r	   _remove_pending_deliveriesbasic_rejectr2  delivery_tagr  r)   r   r   rN   r   r   )r   rI  r  rJ  cancel_ok_resultpending_messagesmessagemessagess   ``      r   r  zBlockingChannel.basic_cancel  s2   8	 0>MM 	 	 	NN78DF F F III		<	P ' %=+L % %#% % %
 "5 I DJ$9999L999$-H"/"<M "" G&6 K'+'F'F$(& (&$' K (8 K KG J33 ' ;T 4 K K K K 
''!--9 ( ; ; ; ""$-EEEEEG G G1G G G G G G G G G G G G G G G8   #'#B#B<#P#P   t333(6 994;N:NOOOO	 4  ::<HH#--X--- t333(6 994;N:NOOOO	 4|t333(6 994;N:NOOOO	 4sD    '<< A"G& "BD3'G& 3D77G& :D7;#G& "G& &4Hc                 |   t                      }g }| j        r| j                                        }t          |          t          u r&|j        j        |k    r|                    |           \t          |          t          u r|j	        j        j        |k    r|                    |           | j        || _        |S )aH  Extract _ConsumerDeliveryEvt objects destined for the given consumer
        from pending events, discarding the _ConsumerCancellationEvt, if any

        :param str consumer_tag:

        :returns: a (possibly empty) sequence of _ConsumerDeliveryEvt destined
            for the given consumer tag
        :rtype: list
        )
r   rt  r   r  r0  r2  rI  r2   r9  rj   )r   rI  remaining_eventsunprocessed_messagesr   s        r   r  z*BlockingChannel._remove_pending_deliveries%  s     !77!" 	)&..00CCyy000:*l::(//444Cyy444#*7<GG ##C((( " 	)  0##r   c                    | j                                         5 }|st          j        d          	 ddd           n# 1 swxY w Y   | j                                         | j        r|                     d           | j        dS dS )a  Processes I/O events and dispatches timers and `basic_consume`
        callbacks until all consumers are cancelled.

        NOTE: this blocking function may not be called from the scope of a
        pika callback, because dispatching `basic_consume` callbacks from this
        context would constitute recursion.

        :raises pika.exceptions.ReentrancyError: if called from the scope of a
            `BlockingConnection` or `BlockingChannel` callback
        :raises ChannelClosed: when this channel is closed by broker.
        zjstart_consuming may not be called from the scope of another BlockingConnection or BlockingChannel callbackNr
  )rN   r   r   ReentrancyErrorr   r  ro  _process_data_events)r   dispatch_alloweds     r   start_consumingzBlockingChannel.start_consumingC  s    _4466 	N:J# N 0MN N NN	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	
%%''' " 	7%%%666 " 	7 	7 	7 	7 	7s   >AAc                 `    |r|                      |           dS |                                  dS )z Cancels all consumers, signalling the `start_consuming` loop to
        exit.

        NOTE: pending non-ackable messages will be lost; pending ackable
        messages will be rejected.

        N)r  r  r  s     r   stop_consumingzBlockingChannel.stop_consuming]  s>      	)l+++++&&(((((r   c              #   *  K   | j                                          |||f}| j        3|| j        j        k    r"t	          d| j        j        d|||f          nt
                              d|           | j                                         }t          ||          | _        	 | 	                    |||||| j
                   n# t          $ r	 d| _         w xY wt
                              d| j                   | j        | j        j        rT| j        j                                        }t          |          t           u r	d| _        dS |j        |j        |j        fV  h||                     d           t+          j                    }	|	|z   }
|}| j        k| j        j        s_|                     |           | j        snA| j        j        rn4|
t+          j                    z
  }|dk    rd	V  n| j        | j        j        _| j        dS dS )
a"  Blocking consumption of a queue instead of via a callback. This
        method is a generator that yields each message as a tuple of method,
        properties, and body. The active generator iterator terminates when the
        consumer is cancelled by client via `BlockingChannel.cancel()` or by
        broker.

        Example:
        ::
            for method, properties, body in channel.consume('queue'):
                print(body)
                channel.basic_ack(method.delivery_tag)

        You should call `BlockingChannel.cancel()` when you escape out of the
        generator loop.

        If you don't cancel this consumer, then next call on the same channel
        to `consume()` with the exact same (queue, auto_ack, exclusive) parameters
        will resume the existing consumer generator; however, calling with
        different parameters will result in an exception.

        :param str queue: The queue name to consume
        :param bool auto_ack: Tell the broker to not expect a ack/nack response
        :param bool exclusive: Don't allow other consumers on the queue
        :param dict arguments: Custom key/value pair arguments for the consumer
        :param float inactivity_timeout: if a number is given (in
            seconds), will cause the method to yield (None, None, None) after the
            given period of inactivity; this permits for pseudo-regular maintenance
            activities to be carried out by the user while waiting for messages
            to arrive. If None is given (default), then the method blocks until
            the next event arrives. NOTE that timing granularity is limited by
            the timer resolution of the underlying implementation.
            NEW in pika 0.10.0.

        :yields: tuple(spec.Basic.Deliver, spec.BasicProperties, str or unicode)

        :raises ValueError: if consumer-creation parameters don't match those
            of the existing queue consumer generator, if any.
            NEW in pika 0.10.0
        :raises ChannelClosed: when this channel is closed by broker.

        NzaConsume with different params not allowed on existing queue consumer generator; previous params: z; new params: z1Creating new queue consumer generator; params: %r)r  rJ  r  rI  r  rL  z'Created new queue consumer generator %rr  g        NNN)r   r  rp  ra  r   r,   rb   r  r`  r  r  r+   r   rb  r   r  r9  r2  r3  r4  r  r   r  )r   r  rJ  r  r  inactivity_timeoutra  rI  r   wait_start_timewait_deadlinedeltas               r   consumezBlockingChannel.consumej  s     ^ 	
%%'''9-)57>>> j )-(F(M(M(M).)(D(DFG G G ? LLL! ! !
  :<<>>L-H.& .&D*
((%'!-')-)J ) L L L L    15. KKA68 8 8 ,8-< 4CKKMM99 88859D2E:s~sx@@@@!) ))T)::: %o//O+.@@M&E1=5D > ))U);;;5 1@ %(9(99C<<,,,,# 1=5D >1 ,88888s   % C Cc                     | j                             |           | j        rGt          | j        t
          j                  r*t                              d| j        |            | j        dS dS )a4  Wrapper for `BlockingConnection.process_data_events()` with common
        channel-specific logic that raises ChannelClosed if broker closed this
        channel.

        NOTE: We need to raise an exception in the context of user's call into
        our API to protect the integrity of the underlying implementation.
        BlockingConnection's underlying asynchronous connection adapter
        (SelectConnection) uses callbacks to communicate with us. If
        BlockingConnection leaks exceptions back into the I/O loop or the
        asynchronous connection adapter, we interrupt their normal workflow and
        introduce a high likelihood of state inconsistency.

        See `BlockingConnection.process_data_events()` for documentation of args
        and behavior.

        :param float time_limit:

        r  z0Channel close by broker detected, raising %r; %rN)	rN   r  r   r0   rv  r   r  r,   rb   )r   r
  s     r   r  z$BlockingChannel._process_data_events  s    & 	++z+BBB> 	'j)=)3)IK K 	'LLK-t5 5 5&&		' 	' 	' 	'r   c                     | j         ?| j         j        }t          |          }|r!t          |d                   t          u r|dz  }nd}|S )a   Returns the number of messages that may be retrieved from the current
        queue consumer generator via `BlockingChannel.consume` without blocking.
        NEW in pika 0.10.0

        :returns: The number of waiting messages
        :rtype: int
        Nr   r7   r   )rp  rb  r9   r  r9  )r   rb  counts      r   get_waiting_message_countz)BlockingChannel.get_waiting_message_count  sY     )5!;JN''E nR0115MMM
Er   c                    | j         t                              d           dS 	 | j         j        \  }}}|so| j         j        }t          j        |                                           D ]<}|                                }| j	        
                    |j        j        d           =|                     | j         j                   d| _         n# d| _         w xY wdS )a  Cancel the queue consumer created by `BlockingChannel.consume`,
        rejecting all pending ackable messages.

        NOTE: If you're looking to cancel a consumer issued with
        BlockingChannel.basic_consume then you should call
        BlockingChannel.basic_cancel.

        :returns: The number of messages requeued by Basic.Nack.
            NEW in 0.10.0: returns 0
        :rtype: int

        NzUcancel: queue consumer generator is inactive (already cancelled by client or broker?)r   Tr  )rp  r,   r  ra  rb  r   r   r  r   r   r  r2  r  r  rI  )r   r   rJ  rb  r   s        r   r  zBlockingChannel.cancel  s    )1NN F G G G1	2!;BNAx 
? "&!?!N  t'E'E'G'GHH ? ?A(0022CJ++
/ , ? ? ? ? d<IJJJ-1D**TD*1111 qs   B C 	Cc                 f    | j                             ||           |                                  dS )a	  Acknowledge one or more messages. When sent by the client, this
        method acknowledges one or more messages delivered via the Deliver or
        Get-Ok methods. When sent by server, this method acknowledges one or
        more messages published with the Publish method on a channel in
        confirm mode. The acknowledgement can be for a single message or a
        set of messages up to and including a specific message.

        :param int delivery_tag: The server-assigned delivery tag
        :param bool multiple: If set to True, the delivery tag is treated as
                              "up to and including", so that multiple messages
                              can be acknowledged with a single method. If set
                              to False, the delivery tag refers to a single
                              message. If the multiple field is 1, and the
                              delivery tag is zero, this indicates
                              acknowledgement of all outstanding messages.
        )r  multipleN)r   	basic_ackr   )r   r  r  s      r   r  zBlockingChannel.basic_ack@  s7    " 	
,JJJr   Tc                 h    | j                             |||           |                                  dS )a?  This method allows a client to reject one or more incoming messages.
        It can be used to interrupt and cancel large incoming messages, or
        return untreatable messages to their original queue.

        :param int delivery_tag: The server-assigned delivery tag
        :param bool multiple: If set to True, the delivery tag is treated as
                              "up to and including", so that multiple messages
                              can be acknowledged with a single method. If set
                              to False, the delivery tag refers to a single
                              message. If the multiple field is 1, and the
                              delivery tag is zero, this indicates
                              acknowledgement of all outstanding messages.
        :param bool requeue: If requeue is true, the server will attempt to
                             requeue the message. If requeue is false or the
                             requeue attempt fails the messages are discarded or
                             dead-lettered.

        )r  r  r  N)r   r  r   )r   r  r  r  s       r   r  zBlockingChannel.basic_nackT  sE    & 	
%' 	 	K 	K 	Kr   c                    | j         rJ t          j        |d           t          | j                  5 }| j         5  | j                            |||j                   |                     |j	        | j         j	                   |r3|j
        }|j        |j        |j        fcddd           cddd           S | j         s
J d            	 ddd           ddd           dS # 1 swxY w Y   	 ddd           dS # 1 swxY w Y   dS )a  Get a single message from the AMQP broker. Returns a sequence with
        the method frame, message properties, and body.

        :param str queue: Name of queue from which to get a message
        :param bool auto_ack: Tell the broker to not expect a reply
        :returns: a three-tuple; (None, None, None) if the queue was empty;
            otherwise (method, properties, body); NOTE: body may be None
        :rtype: (spec.Basic.GetOk|None, spec.BasicProperties|None, bytes|None)
        r  )r  rJ  rY   Nz)wait completed without GetOk and GetEmptyr  )ry  r   r  r	   _RxMessageArgsr   	basic_getr.   r   r   r3   r2  r3  r4  )r   r  rJ  get_ok_resultr   s        r   r  zBlockingChannel.basic_getk  s    ....!%111 T011 	,], , ,
$$%*9 % ; ; ; ""=#9#'#>#GI I I  ,'-C:s~sx?, , , , , , ,	, 	, 	, 	, 	, 	, 	, 	,  6 E ECE E E+, , , , , ,	, 	, 	, 	, 	, 	, 	, 	,, , , , , , , , ,	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	,sA   C;A$C"C;8C"
C;"C&	&C;)C&	*C;;C?C?c           	         | j         rD| j        5  | j                            |||||           |                     | j        j                   | j        j        j        j        }t          |t          j        j        j                  rQt                              d|| j        |||           | j        | j        g}d| _        ng }t%          j        |          t          |t          j        j        j                  s
J |            | j        #| j        g}d| _        t%          j        |          	 ddd           dS # 1 swxY w Y   dS | j                            |||||           |                                  dS )a  Publish to the channel with the given exchange, routing key, and
        body.

        For more information on basic_publish and what the parameters do, see:

            http://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.publish

        NOTE: mandatory may be enabled even without delivery
          confirmation, but in the absence of delivery confirmation the
          synchronous implementation has no way to know how long to wait for
          the Basic.Return.

        :param str exchange: The exchange to publish to
        :param str routing_key: The routing key to bind on
        :param bytes body: The message body; empty string if no body
        :param pika.spec.BasicProperties properties: message properties
        :param bool mandatory: The mandatory flag

        :raises UnroutableError: raised when a message published in
            publisher-acknowledgments mode (see
            `BlockingChannel.confirm_delivery`) is returned via `Basic.Return`
            followed by `Basic.Ack`.
        :raises NackError: raised when a message published in
            publisher-acknowledgements mode is Nack'ed by the broker. See
            `BlockingChannel.confirm_delivery`.

        )exchangerouting_keyr4  r3  	mandatoryz_Message was Nack'ed by broker: nack=%r; channel=%s; exchange=%s; routing_key=%s; mandatory=%r; N)rq  rs  r   basic_publishr   r   r3   rj   r2  r0   r   r}  r~  Nackr,   r  r   ru  r   	NackErrorAckUnroutableError)	r   r  r  r4  r3  r  conf_methodreturned_messagesr  s	            r   r  zBlockingChannel.basic_publish  s-   B & .	!2 #C #C
((% +)' ) ) ) ) ""4#D#MNNN5;HO  k49?+?@@ C NNF#T%8(K!	# # #
 *6-1-@,A).2++,.)$./@AAA &k&*io&9; ; J J=HJ J J *6$($7#8.2+(8BBB	 7?#C #C #C #C #C #C #C #C #C #C #C #C #C #C #C #C #C #CL J$$!'%# % % % %      s   D"E  EEc                     t                      5 }| j                            |j        |||           |                     |j                   ddd           dS # 1 swxY w Y   dS )a_  Specify quality of service. This method requests a specific quality
        of service. The QoS can be specified for the current channel or for all
        channels on the connection. The client can request that messages be sent
        in advance so that when the client finishes processing a message, the
        following message is already held locally, rather than needing to be
        sent down the channel. Prefetching gives a performance improvement.

        :param int prefetch_size:  This field specifies the prefetch window
                                   size. The server will send a message in
                                   advance if it is equal to or smaller in size
                                   than the available prefetch size (and also
                                   falls into other prefetch limits). May be set
                                   to zero, meaning "no specific limit",
                                   although other prefetch limits may still
                                   apply. The prefetch-size is ignored if the
                                   no-ack option is set in the consumer.
        :param int prefetch_count: Specifies a prefetch window in terms of whole
                                   messages. This field may be used in
                                   combination with the prefetch-size field; a
                                   message will only be sent in advance if both
                                   prefetch windows (and those at the channel
                                   and connection level) allow it. The
                                   prefetch-count is ignored if the no-ack
                                   option is set in the consumer.
        :param bool global_qos:    Should the QoS apply to all channels on the
                                   connection.

        )rY   prefetch_sizeprefetch_count
global_qosN)r	   r   	basic_qosr)   r   r   )r   r   r  r  qos_ok_results        r   r  zBlockingChannel.basic_qos  s    :  	7-J  &2+-%	 ! ' ' '
 }5666	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7s   >AA!Ac                     t                      5 }| j                            ||j                   |                     |j                   ddd           dS # 1 swxY w Y   dS )a  This method asks the server to redeliver all unacknowledged messages
        on a specified channel. Zero or more messages may be redelivered. This
        method replaces the asynchronous Recover.

        :param bool requeue: If False, the message will be redelivered to the
                             original recipient. If True, the server will
                             attempt to requeue the message, potentially then
                             delivering it to an alternative subscriber.

        )r  rY   N)r	   r   basic_recoverr)   r   r   )r   r  recover_ok_results      r   r  zBlockingChannel.basic_recover 	  s      	;"3J$$*;*G % I I I09:::	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	;s   <AAAc                 f    | j                             ||           |                                  dS )a7  Reject an incoming message. This method allows a client to reject a
        message. It can be used to interrupt and cancel large incoming messages,
        or return untreatable messages to their original queue.

        :param int delivery_tag: The server-assigned delivery tag
        :param bool requeue: If requeue is true, the server will attempt to
                             requeue the message. If requeue is false or the
                             requeue attempt fails the messages are discarded or
                             dead-lettered.

        )r  r  N)r   r  r   )r   r  r  s      r   r  zBlockingChannel.basic_reject	  s7     	
\7KKKr   c                 z   | j         r"t                              d| j                   dS t	                      5 }| j                            | j        j        |j	                   | 
                    |j                   ddd           n# 1 swxY w Y   d| _         | j                            | j                   dS )zTurn on RabbitMQ-proprietary Confirm mode in the channel.

        For more information see:
            https://www.rabbitmq.com/confirms.html
        z@confirm_delivery: confirmation was already enabled on channel=%sN)ack_nack_callbackrY   T)rq  r,   r-   r   r	   r   confirm_deliveryrs  r.   r)   r   r   r  r  r   select_ok_results     r   r  z BlockingChannel.confirm_delivery	  s	    & 	LL !%!46 6 6 F 	:"2J''"&"C)5 ( 7 7 7
 /8999	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: '+# 	
))$*JKKKKKs   AB

BBc                 "   t          j        |d           t          | j                  5 }| j                            ||||||||j                   |                     |j                   |j	        j
        cddd           S # 1 swxY w Y   dS )a  This method creates an exchange if it does not already exist, and if
        the exchange exists, verifies that it is of the correct and expected
        class.

        If passive set, the server will reply with Declare-Ok if the exchange
        already exists with the same name, and raise an error if not and if the
        exchange does not already exist, the server MUST raise a channel
        exception with reply code 404 (not found).

        :param str exchange: The exchange name consists of a non-empty sequence of
                          these characters: letters, digits, hyphen, underscore,
                          period, or colon.
        :param str exchange_type: The exchange type to use
        :param bool passive: Perform a declare or just check to see if it exists
        :param bool durable: Survive a reboot of RabbitMQ
        :param bool auto_delete: Remove when no more queues are bound to it
        :param bool internal: Can only be published to by other exchanges
        :param dict arguments: Custom key/value pair arguments for the exchange
        :returns: Method frame from the Exchange.Declare-ok response
        :rtype: `pika.frame.Method` having `method` attribute of type
            `spec.Exchange.DeclareOk`

        r  )r  exchange_typepassivedurableauto_deleteinternalr  rY   N)r   r  r	   rx  r   exchange_declarer.   r   r   r3   rj   )	r   r  r  r  r  r  r  r  declare_ok_results	            r   r  z BlockingChannel.exchange_declare9	  s    > 	!(J77735 5 	88IJ''!+'!#*9 ( ; ; ; 09:::$*7	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8s   ABBBc                     t          | j                  5 }| j                            |||j                   |                     |j                   |j        j        cddd           S # 1 swxY w Y   dS )aB  Delete the exchange.

        :param str exchange: The exchange name
        :param bool if_unused: only delete if the exchange is unused
        :returns: Method frame from the Exchange.Delete-ok response
        :rtype: `pika.frame.Method` having `method` attribute of type
            `spec.Exchange.DeleteOk`

        )r  	if_unusedrY   N)	r	   rx  r   exchange_deleter.   r   r   r3   rj   )r   r  r  delete_ok_results       r   r  zBlockingChannel.exchange_deleteh	  s     35 5 	78HJ&&!#)8 ' : : :
 /8999#)6	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7s   AA**A.1A. c                 F   t          j        |d           t          j        |d           t          | j                  5 }| j                            |||||j                   |                     |j                   |j	        j
        cddd           S # 1 swxY w Y   dS )a  Bind an exchange to another exchange.

        :param str destination: The destination exchange to bind
        :param str source: The source exchange to bind to
        :param str routing_key: The routing key to bind on
        :param dict arguments: Custom key/value pair arguments for the binding
        :returns: Method frame from the Exchange.Bind-ok response
        :rtype: `pika.frame.Method` having `method` attribute of type
          `spec.Exchange.BindOk`

        destinationsourcer  r  r  r  rY   N)r   r  r	   rx  r   exchange_bindr.   r   r   r3   rj   )r   r  r  r  r  bind_ok_results         r   r  zBlockingChannel.exchange_bind|	  s     	!+}===!&(333T@AA 
	5J$$''#'6 % 8 8 8 ~6777!'4
	5 
	5 
	5 
	5 
	5 
	5 
	5 
	5 
	5 
	5 
	5 
	5 
	5 
	5 
	5 
	5 
	5 
	5   A
BBBc                     t          | j                  5 }| j                            |||||j                   |                     |j                   |j        j        cddd           S # 1 swxY w Y   dS )a  Unbind an exchange from another exchange.

        :param str destination: The destination exchange to unbind
        :param str source: The source exchange to unbind from
        :param str routing_key: The routing key to unbind
        :param dict arguments: Custom key/value pair arguments for the binding
        :returns: Method frame from the Exchange.Unbind-ok response
        :rtype: `pika.frame.Method` having `method` attribute of type
            `spec.Exchange.UnbindOk`

        r  N)	r	   rx  r   exchange_unbindr.   r   r   r3   rj   )r   r  r  r  r  unbind_ok_results         r   r#  zBlockingChannel.exchange_unbind	  s      35 5 
	78HJ&&''#)8 ' : : : /8999#)6
	7 
	7 
	7 
	7 
	7 
	7 
	7 
	7 
	7 
	7 
	7 
	7 
	7 
	7 
	7 
	7 
	7 
	7   A
A,,A03A0c           
          t          j        |d           t          | j                  5 }| j                            |||||||j                   |                     |j                   |j	        j
        cddd           S # 1 swxY w Y   dS )a  Declare queue, create if needed. This method creates or checks a
        queue. When creating a new queue the client can specify various
        properties that control the durability of the queue and its contents,
        and the level of sharing for the queue.

        Use an empty string as the queue name for the broker to auto-generate
        one. Retrieve this auto-generated queue name from the returned
        `spec.Queue.DeclareOk` method frame.

        :param str queue: The queue name; if empty string, the broker will
            create a unique queue name
        :param bool passive: Only check to see if the queue exists and raise
          `ChannelClosed` if it doesn't
        :param bool durable: Survive reboots of the broker
        :param bool exclusive: Only allow access by the current connection
        :param bool auto_delete: Delete after consumer cancels or disconnects
        :param dict arguments: Custom key/value arguments for the queue
        :returns: Method frame from the Queue.Declare-ok response
        :rtype: `pika.frame.Method` having `method` attribute of type
            `spec.Queue.DeclareOk`

        r  )r  r  r  r  r  r  rY   N)r   r  r	   rx  r   queue_declarer.   r   r   r3   rj   )r   r  r  r  r  r  r  r  s           r   r'  zBlockingChannel.queue_declare	  s    : 	!%111T@AA 	8!J$$#'#*9 % ; ; ; 09:::$*7	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8s   ABB
Bc                     t          | j                  5 }| j                            ||||j                   |                     |j                   |j        j        cddd           S # 1 swxY w Y   dS )a{  Delete a queue from the broker.

        :param str queue: The queue to delete
        :param bool if_unused: only delete if it's unused
        :param bool if_empty: only delete if the queue is empty
        :returns: Method frame from the Queue.Delete-ok response
        :rtype: `pika.frame.Method` having `method` attribute of type
            `spec.Queue.DeleteOk`

        )r  r  if_emptyrY   N)	r	   rx  r   queue_deleter.   r   r   r3   rj   )r   r  r  r)  r  s        r   r*  zBlockingChannel.queue_delete	  s     T@AA 		7 J###!)8	 $ : : : /8999#)6		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7s   A	A++A/2A/c                     t          | j                  5 }| j                            ||j                   |                     |j                   |j        j        cddd           S # 1 swxY w Y   dS )a  Purge all of the messages from the specified queue

        :param str queue: The queue to purge
        :returns: Method frame from the Queue.Purge-ok response
        :rtype: `pika.frame.Method` having `method` attribute of type
            `spec.Queue.PurgeOk`

        )r  rY   N)	r	   rx  r   queue_purger.   r   r   r3   rj   )r   r  purge_ok_results      r   r,  zBlockingChannel.queue_purge	  s     T@AA 	6J""o&D # F F F7888"(5	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6r  c                 F   t          j        |d           t          j        |d           t          | j                  5 }| j                            |||||j                   |                     |j                   |j	        j
        cddd           S # 1 swxY w Y   dS )a  Bind the queue to the specified exchange

        :param str queue: The queue to bind to the exchange
        :param str exchange: The source exchange to bind to
        :param str routing_key: The routing key to bind on
        :param dict arguments: Custom key/value pair arguments for the binding

        :returns: Method frame from the Queue.Bind-ok response
        :rtype: `pika.frame.Method` having `method` attribute of type
            `spec.Queue.BindOk`

        r  r  r  r  r  r  rY   N)r   r  r	   rx  r   
queue_bindr.   r   r   r3   rj   )r   r  r  r  r  r   s         r   r0  zBlockingChannel.queue_bind
  s     	!%111!(J77735 5 		58FJ!!!'#'6 " 8 8 8 ~6777!'4		5 		5 		5 		5 		5 		5 		5 		5 		5 		5 		5 		5 		5 		5 		5 		5 		5 		5r!  c                     t          | j                  5 }| j                            |||||j                   |                     |j                   |j        j        cddd           S # 1 swxY w Y   dS )a  Unbind a queue from an exchange.

        :param str queue: The queue to unbind from the exchange
        :param str exchange: The source exchange to bind from
        :param str routing_key: The routing key to unbind
        :param dict arguments: Custom key/value pair arguments for the binding

        :returns: Method frame from the Queue.Unbind-ok response
        :rtype: `pika.frame.Method` having `method` attribute of type
            `spec.Queue.UnbindOk`

        r/  N)	r	   rx  r   queue_unbindr.   r   r   r3   rj   )r   r  r  r  r  r$  s         r   r2  zBlockingChannel.queue_unbind
  s    " T@AA 		7 J##!'#)8 $ : : : /8999#)6		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7 		7r%  c                     t          | j                  5 }| j                            |j                   |                     |j                   |j        j        cddd           S # 1 swxY w Y   dS )a  Select standard transaction mode. This method sets the channel to use
        standard transactions. The client must use this method at least once on
        a channel before using the Commit or Rollback methods.

        :returns: Method frame from the Tx.Select-ok response
        :rtype: `pika.frame.Method` having `method` attribute of type
            `spec.Tx.SelectOk`

        N)	r	   rx  r   	tx_selectr.   r   r   r3   rj   r  s     r   r4  zBlockingChannel.tx_select;
  s     T@AA 	7 J  !1!@AAA/8999#)6	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7   AA''A+.A+c                     t          | j                  5 }| j                            |j                   |                     |j                   |j        j        cddd           S # 1 swxY w Y   dS )zCommit a transaction.

        :returns: Method frame from the Tx.Commit-ok response
        :rtype: `pika.frame.Method` having `method` attribute of type
            `spec.Tx.CommitOk`

        N)	r	   rx  r   	tx_commitr.   r   r   r3   rj   )r   commit_ok_results     r   r7  zBlockingChannel.tx_commitL
  s     T@AA 	7 J  !1!@AAA/8999#)6	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7r5  c                     t          | j                  5 }| j                            |j                   |                     |j                   |j        j        cddd           S # 1 swxY w Y   dS )zRollback a transaction.

        :returns: Method frame from the Tx.Commit-ok response
        :rtype: `pika.frame.Method` having `method` attribute of type
            `spec.Tx.CommitOk`

        N)	r	   rx  r   tx_rollbackr.   r   r   r3   rj   )r   rollback_ok_results     r   r:  zBlockingChannel.tx_rollback[
  s     T@AA 	9"J""#5#DEEE1:;;;%+8	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9r5  )r   r   )FFNNr  r<   )r   F)r   FT)F)NF)r   r   F)r   T)r  N)NNr  N)FFFFN)FFr)  )Dr=   r>   r?   r@   r   r  rx  rr  r  r  r   r  r_   r   r    r   rC   r   rN   r   r   r  r  r   r  r  r  r{  r  r  r  r   r   r  rz  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   directr  r  r  r#  r'  r*  r,  r0  r2  r4  r7  r:  r   r   r   r  r    s        (  Z(	
 	
 	
 N &0Z8.&J &J"
 (2z:N(L (L$
 !+
3! !
 "G<? <? <?|	# 	# 	#F F F    . . . ) ) X)     X  $ $ X$ " " X" 5 5 X5 +l-' ' '2H H H2G G G L  L  LD) ) )0) ) )"
H 
H 
H0 0 0$  .   */ / /.  "E E E*  % %#' $2! 2! 2! 2!r '+0415L L L L\`P `P `PD$ $ $<7 7 74) ) ) ) #'} } } }~' ' '4  $) ) )V   (   ., , , ,F "& %O! O! O! O!b#7 #7 #7 #7J; ; ; ;    L L L8 (4':!&!&%*"'#'-8 -8 -8 -8^7 7 7 7( >@ $5 5 5 58 %)#$&"&	7 7 7 7< $# %"' $*8 *8 *8 *8X7 7 7 7,6 6 6 5 5 5 58 #!%#	7 7 7 787 7 7"7 7 79 9 9 9 9r   r  ))r@   collectionsr   r   r*  r   loggingrx   pika.compatr   pika.exceptionsr   	pika.specr   pika.validatorsr   pika.adapters.utilsr   pika.adaptersr   pika.exchange_typer   	getLoggerr=   r,   objectr	   rE   rT   rf   rn   rq   rs   r.  r0  r9  r?  rE  rH  r`  r  r   r   r   <module>rH     s   & * ) ) ) ) ) ) )                    $ $ $ $ $ $     $ $ $ $ $ $ 3 3 3 3 3 3 , + + + + + + + + + + +		8	$	$B B B B Bf B B BJ!0 !0 !0 !0 !0& !0 !0 !0H       0+ + + + + + + +0M M M M M> M M MO O O O O@ O O Oy
6 y
6 y
6 y
6 y
6 y
6 y
6 y
6x8 8 8 8 8 8 8 8    -   &( ( ( ( (1 ( ( (4 M  M  M  M  M,  M  M  MF    f   $?6 ?6 ?6 ?6 ?6F ?6 ?6 ?6DE E E E E& E E E.e9 e9 e9 e9 e9f e9 e9 e9 e9 e9r   