
    )Jfv                        d Z ddlZddlZddlmZ ddlmZmZm	Z	m
Z
 ddlmZ ddlZddlmZmZ ddlmZ ddlmZ dd	lmZ  ej        e          Z G d
 dej                  Z edg d          Z G d de          Z G d dej        j                   Z! G d de
j"                  Z# G d dej$                  Z%dS )a  Using Pika with a Twisted reactor.

The interfaces in this module are Deferred-based when possible. This means that
the connection.channel() method and most of the channel methods return
Deferreds instead of taking a callback argument and that basic_consume()
returns a Twisted DeferredQueue where messages from the server will be
stored. Refer to the docstrings for TwistedProtocolConnection.channel() and the
TwistedChannel class for details.

    N)
namedtuple)defererrorreactorprotocol)Failure)
exceptionsspec)nbio_interface)check_callback_arg)ExchangeTypec                   6     e Zd ZdZd fd	Zd Zd Zd Z xZS )ClosableDeferredQueuez
    Like the normal Twisted DeferredQueue, but after close() is called with an
    exception instance all pending Deferreds are errbacked and further attempts
    to call get() or put() return a Failure wrapping that exception.
    Nc                 h    d | _         t          t          |                               ||           d S N)closedsuperr   __init__)selfsizebacklog	__class__s      c/home/alex/cs2snipeproduction/venv/lib/python3.11/site-packages/pika/adapters/twisted_connection.pyr   zClosableDeferredQueue.__init__(   s1    #T**33D'BBBBB    c                     | j         r3t                              d           t          j        | j                   S t          j                            | |          S )z}
        Like the original :meth:`DeferredQueue.put` method, but returns an
        errback if the queue is closed.

        z-Impossible to put to the queue, it is closed.)r   LOGGERr   r   failDeferredQueueput)r   objs     r   r   zClosableDeferredQueue.put,   sL     ; 	+LLHIII:dk***"&&tS111r   c                     | j         r3t                              d           t          j        | j                   S t          j                            |           S )a  
        Returns a Deferred that will fire with the next item in the queue, when
        it's available.

        The Deferred will errback if the queue is closed.

        :returns: Deferred that fires with the next item.
        :rtype: Deferred

        z/Impossible to get from the queue, it is closed.)r   r   r   r   r   r   getr   s    r   r"   zClosableDeferredQueue.get7   sJ     ; 	+LLJKKK:dk***"&&t,,,r   c                     | j         r t                              d| j                    || _         | j        r3| j                                                            |           | j        3g | _        dS )zPCloses the queue.

        Errback the pending calls to :meth:`get()`.

        z)Queue was already closed with reason: %s.N)r   r   warningwaitingpoperrbackpending)r   reasons     r   closezClosableDeferredQueue.closeG   sv     ; 	(NNF;( ( (l 	/L&&v... l 	/r   NN)	__name__
__module____qualname____doc__r   r   r"   r+   __classcell__r   s   @r   r   r   !   sz         C C C C C C	2 	2 	2- - -       r   r   ReceivedMessagechannelmethod
propertiesbodyc                      e Zd ZdZ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ed             Zed             Zd Zd Zd4dZd5dZ	 	 	 	 d6dZd7dZd8dZ	 	 d9dZd:dZd;dZd7d Zd<d"Zd# Z d$ Z!d% Z"	 	 d=d&Z#e$j%        dddddfd'Z&d9d(Z'	 	 	 	 d>d)Z(d* Z)d+ Z*d?d,Z+	 	 	 	 	 d@d-Z,dAd.Z-d/ Z.	 	 	 dBd0Z/d1 Z0d2 Z1d3 Z2dS )CTwistedChannela
  A wrapper around Pika's Channel.

    Channel methods that normally take a callback argument are wrapped to
    return a Deferred that fires with whatever would be passed to the callback.
    If the channel gets closed, all pending Deferreds are errbacked with a
    ChannelClosed exception. The returned Deferreds fire with whatever
    arguments the callback to the original method would receive.

    Some methods like basic_consume and basic_get are wrapped in a special way,
    see their docstrings for details.
    c                    || _         d | _        t                      | _        i | _        d | _        | j                             | j        t          j	        j
        gd           i | _        d| _        d | _        i | _        d | _        t!          j                    | _        | j                             | j                   | j                             | j                   d S NF)_channel_closedset_calls
_consumers_basic_get_deferredadd_callback_on_getemptyr
   BasicGetEmpty_queue_name_to_consumer_tags_delivery_confirmation_delivery_message_id_deliveries_puback_returnr   Deferred	on_closedadd_on_close_callback_on_channel_closedadd_on_cancel_callback _on_consumer_cancelled_by_broker)r   r5   s     r   r   zTwistedChannel.__init__g   s    ee#' ""4#4tz7J6K#(	* 	* 	* -/)&+#$(! #))++D,CDDD,,1	3 	3 	3 	3 	3r   c                 N    d                     | j        j        | j                  S )Nz<{cls} channel={chan!r}>)clschan)formatr   r-   r=   r#   s    r   __repr__zTwistedChannel.__repr__   s+    )00'dm 1 = = 	=r   c                    || _         | j        D ]}|                    | j                    | j                                        D ]}|                    | j                    | j                                        D ]}|                    | j                    t                      | _        i | _        i | _        | j        	                    | j                    d S r   )
r>   r@   r(   rJ   valuesrA   r+   r?   rM   callback)r   r=   r*   dconsumers        r   rO   z!TwistedChannel._on_channel_closed   s     	$ 	$AIIdl####!((** 	$ 	$AIIdl####..00 	) 	)HNN4<((((ee-----r   c                 ,    |                      |          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

        )_on_consumer_cancelled)r   method_frames     r   rQ   z/TwistedChannel._on_consumer_cancelled_by_broker   s     **<888r   c                 `   |j         j        }|| j        vrt                              d|           |S | j        |                             t          j                               | j        |= | j        	                                D ](}	 |
                    |           # t          $ r Y %w xY w|S )a  Called when the broker cancels a consumer via Basic.Cancel or when
        the broker responds to a Basic.Cancel request by Basic.CancelOk.

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

        z%basic_cancel - consumer not found: %s)r6   consumer_tagrA   r   r%   r+   r	   ConsumerCancelledrG   rX   removeKeyError)r   framer`   ctagss       r   r]   z%TwistedChannel._on_consumer_cancelled   s     |0t..NNB') ) )L%++J,H,J,JKKKOL)6==?? 	 	E\****   s   B
B+*B+c                     | j         t                              d           dS | j                             d           dS )z3Callback the Basic.Get deferred with None.
        Nz7Got Basic.GetEmpty but no Basic.Get calls were pending.)rB   r   r%   rY   )r   _method_frames     r   rD   zTwistedChannel._on_getempty   sJ     #+NN + , , ,F ))$/////r   c                 t     t           j        |          t          j                   fd            }|S )a#  Wrap Pika's Channel method to make it return a Deferred that fires
        when the method completes and errbacks if the channel gets closed. If
        the original method's callback would receive more than one argument,
        the Deferred fires with a tuple of argument values.

        c                  H   j         rt          j        j                   S t          j                    j                                                           j                   fd}||d<   	  | i | n## t          $ r t          j                    cY S w xY wS )Nc                      t          |           dk    r$                    t          |                      dS  j        |   dS )z
                Make sure that the deferred is called with a single argument.
                In case the original callback fires with more than one, convert
                to a tuple.
                   N)lenrY   tuple)argsrZ   s    r   single_argumentzMTwistedChannel._wrap_channel_method.<locals>.wrapped.<locals>.single_argument   sG     t99q==JJuT{{+++++AJ%%%%r   rY   )	r>   r   r   rL   r@   addaddCallback_clear_call	Exception)rn   kwargsro   rZ   r6   r   s      @r   wrappedz4TwistedChannel._wrap_channel_method.<locals>.wrapped   s    | 0z$,///  AKOOAMM$*A...	& 	& 	& 	& 	& "1F:$''''' $ $ $z||###$Hs   6A? ?BB)getattrr=   	functoolswraps)r   nameru   r6   s   `  @r   _wrap_channel_methodz#TwistedChannel._wrap_channel_method   sQ     --		 	 	 	 	 	 	 
!	 	6 r   c                 :    | j                             |           |S r   r@   discardr   retrZ   s      r   rr   zTwistedChannel._clear_call       A
r   c                     | j         j        S r   )r=   channel_numberr#   s    r   r   zTwistedChannel.channel_number   s    }++r   c                     | j         j        S r   )r=   
connectionr#   s    r   r   zTwistedChannel.connection   s    }''r   c                     | j         j        S )zFReturns True if the channel is closed.

        :rtype: bool

        )r=   	is_closedr#   s    r   r   zTwistedChannel.is_closed   s     }&&r   c                     | j         j        S )zoReturns True if client-initiated closing of the channel is in
        progress.

        :rtype: bool

        )r=   
is_closingr#   s    r   r   zTwistedChannel.is_closing  s     }''r   c                     | j         j        S )zDReturns True if the channel is open.

        :rtype: bool

        )r=   is_openr#   s    r   r   zTwistedChannel.is_open  s     }$$r   c                     | j         j        S r   )r=   flow_activer#   s    r   r   zTwistedChannel.flow_active  s    }((r   c                     | j         j        S r   )r=   consumer_tagsr#   s    r   r   zTwistedChannel.consumer_tags  s    }**r   c                 F    | j                             |j        |           dS )a   Pass in a Deferred and a list replies from the RabbitMQ broker which
        you'd like the Deferred to be callbacked on with the frame as callback
        value.

        :param Deferred deferred: The Deferred to callback
        :param list replies: The replies to callback on

        N)r=   rC   rY   )r   deferredrepliess      r   callback_deferredz TwistedChannel.callback_deferred  s%     	""8#4g>>>>>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
            message as only argument. The message is a named tuple with
            the following attributes
            - channel: this TwistedChannel
            - method: pika.spec.Basic.Return
            - properties: pika.spec.BasicProperties
            - body: bytes
        c                 <     t          |||                    S Nr4   r3   )r=   r6   r7   r8   rY   r   s       r   <lambda>z7TwistedChannel.add_on_return_callback.<locals>.<lambda>9  s1    xx !)	  8 8 r   N)r=   add_on_return_callbackr   rY   s   ``r   r   z%TwistedChannel.add_on_return_callback,  sC     	,,    		
 		
 		
 		
 		
r   r   Fc                 :    | j                             ||          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 integer delivery_tag: int/long 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.

        )delivery_tagmultiple)r=   	basic_ack)r   r   r   s      r   r   zTwistedChannel.basic_ackC  s(    $ }&&% ' : : 	:r    c                 x    |                      d          } ||          }|                    | j                  S )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. It may also be sent from the server to the client in
        the event of the consumer being unexpectedly cancelled (i.e. cancelled
        for any reason other than the server receiving the corresponding
        basic.cancel from the client). This allows clients to be notified of
        the loss of consumers due to events such as queue deletion.

        This method wraps :meth:`Channel.basic_cancel
        <pika.channel.Channel.basic_cancel>` and closes any deferred queue
        associated with that consumer.

        :param str consumer_tag: Identifier for the consumer
        :returns: Deferred that fires on the Basic.CancelOk response
        :rtype: Deferred
        :raises ValueError:

        basic_cancel)r`   )rz   rq   r]   )r   r`   ru   rZ   s       r   r   zTwistedChannel.basic_cancelX  s>    * ++N;;G...}}T8999r   Nc           	      l   	  j         rt          j         j                   S t                      	t          j                     j                                       	 fd}	 fd}	  j                            ||||||           n## t          $ r t          j                    cY S w xY wS )al  Consume from a server queue.

        Sends the AMQP 0-9-1 command Basic.Consume to the broker and binds
        messages for the consumer_tag to a
        :class:`ClosableDeferredQueue`. If you do not pass in a
        consumer_tag, one will be automatically generated for you.

        For more information on basic_consume, see:
        Tutorial 2 at http://www.rabbitmq.com/getstarted.html
        http://www.rabbitmq.com/confirms.html
        http://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume

        :param str queue: The queue to consume from. Use the empty string to
            specify the most recent server-named queue for this channel.
        :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: Specify your own consumer tag
        :param dict arguments: Custom key/value pair arguments for the consumer
        :returns: Deferred that fires with a tuple
            ``(queue_object, consumer_tag)``. The Deferred will errback with an
            instance of :class:`exceptions.ChannelClosed` if the call fails.
            The queue object is an instance of :class:`ClosableDeferredQueue`,
            where data received from the queue will be stored. Clients should
            use its :meth:`get() <ClosableDeferredQueue.get>` method to fetch
            an individual message, which will return a Deferred firing with a
            namedtuple whose attributes are:
            - channel: this TwistedChannel
            - method: pika.spec.Basic.Deliver
            - properties: pika.spec.BasicProperties
            - body: bytes
        :rtype: Deferred

        c                 
   | j         j        }j                            t	                                                    |           j        |<   j                                       	                    |f           d S r   )
r6   r`   rG   
setdefaultr?   rp   rA   r@   r}   rY   )rd   r`   rZ   queue	queue_objr   s     r   on_consume_okz3TwistedChannel.basic_consume.<locals>.on_consume_ok  s{     <4L-88suu !c,///,5DOL)K"""JJ	<011111r   c                 T                         t          |||                     dS )zjAdd the ReceivedMessage to the queue, while replacing the
            channel implementation.
            r4   N)r   r3   )r=   r6   r7   r8   r   r   s       r   on_message_callbackz9TwistedChannel.basic_consume.<locals>.on_message_callback  sC     MM !)	      r   )r   r   auto_ack	exclusiver`   	argumentsrY   )
r>   r   r   r   rL   r@   rp   r=   basic_consumers   )
r   r   r   r   r`   r   r   r   rZ   r   s
   ``      @@r   r   zTwistedChannel.basic_consumeq  s   T < 	,:dl+++)++	N	2 	2 	2 	2 	2 	2 	2 	2
	 
	 
	 
	 
	 
		 M''$7!#)#& (      	  	  	 :<<	  s   /!B B10B1c                       j         t          j                     fd} fd}                      d          ||          }|                    |           |                    |           | _         |S )a  Get a single message from the AMQP broker.

        Will return If the queue is empty, it will return None.
        If you want to
        be notified of Basic.GetEmpty, use the Channel.add_callback method
        adding your Basic.GetEmpty callback which should expect only one
        parameter, frame. Due to implementation details, this cannot be called
        a second time until the callback is executed.  For more information on
        basic_get and its parameters, see:

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

        This method wraps :meth:`Channel.basic_get
        <pika.channel.Channel.basic_get>`.

        :param str queue: The queue from which to get a message. Use the empty
                      string to specify the most recent server-named queue
                      for this channel.
        :param bool auto_ack: Tell the broker to not expect a reply
        :returns: Deferred that fires with a namedtuple whose attributes are:
             - channel: this TwistedChannel
             - method: pika.spec.Basic.GetOk
             - properties: pika.spec.BasicProperties
             - body: bytes
            If the queue is empty, None will be returned.
        :rtype: Deferred
        :raises pika.exceptions.DuplicateGetOkCallback:

        Nc                 @    | d S | \  }}}}t          |||          S r   r   )resultr=   r6   r7   r8   r   s        r   create_namedtuplez3TwistedChannel.basic_get.<locals>.create_namedtuple  s>    ~t17.Hfj$"%	   r   c                     d _         | S r   )rB   r   r   s    r   cleanup_attributez3TwistedChannel.basic_get.<locals>.cleanup_attribute  s    '+D$Mr   	basic_get)r   r   )rB   r	   DuplicateGetOkCallbackrz   rq   addBoth)r   r   r   r   r   rZ   s   `     r   r   zTwistedChannel.basic_get  s    < #/3555		 		 		 		 			 	 	 	 	 3D%%k22(, , ,	'(((			#$$$#$ r   Tc                 <    | j                             |||          S )aL  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 integer delivery_tag: int/long 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   requeue)r=   
basic_nack)r   r   r   r   s       r   r   zTwistedChannel.basic_nack  s,    & }''% ( 
 
 	
r   c                 :   | j         rt          j        | j                   S | j                            |||||          }| j        st          j        |          S | xj        dz  c_        t          j                    | j	        | j        <   | j	        | j                 S )a  Publish to the channel with the given exchange, routing key and body.

        This method wraps :meth:`Channel.basic_publish
        <pika.channel.Channel.basic_publish>`, but makes sure the channel is
        not closed before publishing.

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

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

        :param str exchange: The exchange to publish to
        :param str routing_key: The routing key to bind on
        :param bytes body: The message body
        :param pika.spec.BasicProperties properties: Basic.properties
        :param bool mandatory: The mandatory flag
        :returns: A Deferred that fires with the result of the channel's
            basic_publish.
        :rtype: Deferred
        :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_keyr8   r7   	mandatoryrk   )
r>   r   r   r=   basic_publishrH   succeedrI   rL   rJ   )r   r   r   r8   r7   r   r   s          r   r   zTwistedChannel.basic_publish  s    B < 	,:dl+++,,#! - ! ! * 	?=((( %%*%%:?.:J:JDT67#D$=>>r   c                 D     |                      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 by
                                   consumers who have enabled the no-ack
                                   option.
        :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 by consumers who
                                   have enabled the no-ack option.
        :param bool global_qos:    Should the QoS apply to all channels on the
                                   connection.
        :returns: Deferred that fires on the Basic.QosOk response
        :rtype: Deferred

        	basic_qos)prefetch_sizeprefetch_count
global_qosrz   )r   r   r   r   s       r   r   zTwistedChannel.basic_qosF  s5    @ 6t((55')!
 
 
 	
r   c                 :    | j                             ||          S )a_  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 integer delivery_tag: int/long 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.
        :raises: TypeError

        )r   r   )r=   basic_reject)r   r   r   s      r   r   zTwistedChannel.basic_rejectl  s(     }))%w * 8 8 	8r   c                 @     |                      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.
        :returns: Deferred that fires on the Basic.RecoverOk response
        :rtype: Deferred

        basic_recover)r   r   )r   r   s     r   r   zTwistedChannel.basic_recover|  s%     :t((99'JJJJr   Normal shutdownc                 :    | j                             ||          S )a  Invoke a graceful shutdown of the channel with the AMQP Broker.

        If channel is OPENING, transition to CLOSING and suppress the incoming
        Channel.OpenOk, if any.

        :param int reply_code: The reason code to send to broker
        :param str reply_text: The reason text to send to broker

        :raises ChannelWrongStateError: if channel is closed or closing

        )
reply_code
reply_text)r=   r+   r   r   r   s      r   r+   zTwistedChannel.close  s     }""jZ"PPPr   c                 0     j         r.t                              d           t          j        d          S                      d          } | j                  } fd}|                    |            j        	                     j
                   |S )a  Turn on Confirm mode in the channel. Pass in a callback to be
        notified by the Broker when a message has been confirmed as received or
        rejected (Basic.Ack, Basic.Nack) from the broker to the publisher.

        For more information see:
            http://www.rabbitmq.com/confirms.html#publisher-confirms

        :returns: Deferred that fires on the Confirm.SelectOk response
        :rtype: Deferred

        z3confirm_delivery: confirmation was already enabled.Nconfirm_delivery)ack_nack_callbackc                 X    d_         d_        t                              d           | S )NTr   zDelivery confirmation enabled.)rH   rI   r   debugr   s    r   set_delivery_confirmationzBTwistedChannel.confirm_delivery.<locals>.set_delivery_confirmation  s+    *.D'()D%LL9:::Mr   )rH   r   r   r   r   rz   _on_delivery_confirmationrq   r=   r   _on_puback_message_returned)r   ru   rZ   r   s   `   r   r   zTwistedChannel.confirm_delivery  s     & 	'LLNOOO=&&&++,>??Gd&DEEE	 	 	 	 	 	
/000 	,,T-MNNNr   c                 :   |j         j        | j        vrt                              d           dS |j         j        r(fd| j        D             }|                                 ng}|D ],}| j        |         }| j        |= t          |j         t          j	        j
        j                  rgt                              d|j         | j                   | j        | j        g}d| _        ng }|                    t!          j        |                     t          |j         t          j	        j
        j                  sJ | j        8| j        g}d| _        |                    t!          j        |                     |                    |j                    .dS )a  Invoked by pika when RabbitMQ responds to a Basic.Publish RPC
        command, passing in either a Basic.Ack or Basic.Nack frame with
        the delivery tag of the message that was published. The delivery tag
        is an integer counter indicating the message number that was sent
        on the channel via Basic.Publish. Here we're just doing house keeping
        to keep track of stats and remove message numbers that we expect
        a delivery confirmation of from the list used to keep track of messages
        that are pending confirmation.

        :param pika.frame.Method method_frame: Basic.Ack or Basic.Nack frame

        z3Delivery tag %s not found in the pending deliveriesNc                      g | ]
}|k    |S  r   ).0tagr   s     r   
<listcomp>z<TwistedChannel._on_delivery_confirmation.<locals>.<listcomp>  s#    KKKCsl7J7JC7J7J7Jr   z3Message was Nack'ed by broker: nack=%r; channel=%s;)r6   r   rJ   r   r   r   sort
isinstancepikar
   rE   Nackr%   r   rK   r(   r	   	NackErrorAckUnroutableErrorrY   )r   r^   tagsr   rZ   returned_messagesr   s         @r   r   z(TwistedChannel._on_delivery_confirmation  s    $*7t///LLN%' ' 'F' 	"KKKK4#3KKKDIIKKKK >D 	4 	4C %A %,-ty/CDD 4 I ')<> > > &2)-)<(=%*.D''(*%		*./@AABBBB!,"5ty7JKKKKK&2)-)<(=%*.D'IIj89JKKLLLLJJ|23333/	4 	4r   c           
      F   t          |t          j        j                  s
J |            t          |t          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=%.255rNr4   )r   r
   rE   ReturnBasicPropertiesr   r%   rH   r   rl   r3   rK   )r   r5   r6   r7   r8   s        r   r   z*TwistedChannel._on_puback_message_returned  s     &$*"344<<f<<<*d&:;;GGZGGG!"&"="FJ)CIIItT	; 	; 	; .d*4A A Ar   c                 F     |                      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
        :raises ValueError:
        :returns: Deferred that fires on the Exchange.BindOk response
        :rtype: Deferred

        exchange_binddestinationsourcer   r   r   r   r   r   r   r   s        r   r   zTwistedChannel.exchange_bind  s7     :t((99##	
 
 
 	
r   c           	      L     |                      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: Deferred that fires on the Exchange.DeclareOk response
        :rtype: Deferred
        :raises ValueError:

        exchange_declare)r   exchange_typepassivedurableauto_deleteinternalr   r   )r   r   r   r   r   r   r   r   s           r   r   zTwistedChannel.exchange_declare  sB    @ =t(();<<'#
 
 
 	
r   c                 B     |                      d          ||          S )a  Delete the exchange.

        :param str exchange: The exchange name
        :param bool if_unused: only delete if the exchange is unused
        :returns: Deferred that fires on the Exchange.DeleteOk response
        :rtype: Deferred
        :raises ValueError:

        exchange_delete)r   	if_unusedr   )r   r   r   s      r   r   zTwistedChannel.exchange_delete=  s2     <t(():;;
 
 
 	
r   c                 F     |                      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: Deferred that fires on the Exchange.UnbindOk response
        :rtype: Deferred
        :raises ValueError:

        exchange_unbindr   r   r   s        r   r   zTwistedChannel.exchange_unbindL  s8      <t(():;;##	
 
 
 	
r   c                 @     |                      d          |          S )a  Turn Channel flow control off and on.

        Returns a Deferred that will fire with a bool indicating the channel
        flow state. For more information, please reference:

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

        :param bool active: Turn flow on or off
        :returns: Deferred that fires with the channel flow state
        :rtype: Deferred
        :raises ValueError:

        flow)activer   )r   r   s     r   r   zTwistedChannel.flowc  s%     1t((00????r   c                 4    | j                                         S )zOpen the channel)r=   openr#   s    r   r   zTwistedChannel.opens  s    }!!###r   c                 F     |                      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: Deferred that fires on the Queue.BindOk response
        :rtype: Deferred
        :raises ValueError:

        
queue_bindr   r   r   r   r   r   r   r   r   r   s        r   r  zTwistedChannel.queue_bindw  s7     7t((66#	
 
 
 	
r   c                 J     |                      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

        :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
        :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: Deferred that fires on the Queue.DeclareOk response
        :rtype: Deferred
        :raises ValueError:

        queue_declare)r   r   r   r   r   r   r   )r   r   r   r   r   r   r   s          r   r  zTwistedChannel.queue_declare  s=    6 :t((99#
 
 
 	
r   c                                            d          } ||||          } fd}|                    ||          S )a  Delete a queue from the broker.


        This method wraps :meth:`Channel.queue_delete
        <pika.channel.Channel.queue_delete>`, and removes the reference to the
        queue object after it gets deleted on the server.

        :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: Deferred that fires on the Queue.DeleteOk response
        :rtype: Deferred
        :raises ValueError:

        queue_delete)r   r   if_emptyc                 0   t          j                            |t                                          D ]_}j        |                             t          j        d|z                       j        |= j        |                             |           `| S )NzQueue %s was deleted.)	listrG   r"   r?   rA   r+   r	   ra   rb   )r   
queue_namer`   r   s      r   _clear_consumerz4TwistedChannel.queue_delete.<locals>._clear_consumer  s     $599*ceeLL!N !N " "-330/*<> >? ? ? OL11*=DD " " " "Jr   )rz   rq   )r   r   r   r  ru   rZ   r  s   `      r   r  zTwistedChannel.queue_delete  s]      ++N;;G%9xHHH		 		 		 		 		 }}_e444r   c                 @     |                      d          |          S )zPurge all of the messages from the specified queue

        :param str queue: The queue to purge
        :returns: Deferred that fires on the Queue.PurgeOk response
        :rtype: Deferred
        :raises ValueError:

        queue_purge)r   r   )r   r   s     r   r  zTwistedChannel.queue_purge  s%     8t((77eDDDDr   c                 F     |                      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: Deferred that fires on the Queue.UnbindOk response
        :rtype: Deferred
        :raises ValueError:

        queue_unbindr  r   r  s        r   r  zTwistedChannel.queue_unbind  s7      9t((88#	
 
 
 	
r   c                 <     |                      d                      S )zCommit a transaction.

        :returns: Deferred that fires on the Tx.CommitOk response
        :rtype: Deferred
        :raises ValueError:

        	tx_commitr   r#   s    r   r  zTwistedChannel.tx_commit  s      6t((55777r   c                 <     |                      d                      S )zRollback a transaction.

        :returns: Deferred that fires on the Tx.RollbackOk response
        :rtype: Deferred
        :raises ValueError:

        tx_rollbackr   r#   s    r   r  zTwistedChannel.tx_rollback  s      8t((77999r   c                 <     |                      d                      S )aV  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: Deferred that fires on the Tx.SelectOk response
        :rtype: Deferred
        :raises ValueError:

        	tx_selectr   r#   s    r   r  zTwistedChannel.tx_select  s      6t((55777r   )r   F)r   )FFNN)F)NFTr<   )r   r   F)T)r   r   )r   N)NNr   Nr,   )FFFFN)FF)NNN)3r-   r.   r/   r0   r   rV   rO   rQ   r]   rD   rz   rr   propertyr   r   r   r   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  r  r  r  r  r  r  r   r   r   r:   r:   Z   s       
 
3 3 32= = =. . .$9 9 9  00 0 0% % %N   , , X, ( ( X( ' ' X' ( ( X( % % X% ) ) X) + + X+
	? 	? 	?
 
 
.: : : :*: : : :6  % %#' $R R R Rh5 5 5 5n
 
 
 
: "& %/? /? /? /?b$
 $
 $
 $
L8 8 8 8 K K K KQ Q Q Q  <.4 .4 .4`A A A0 >@ $
 
 
 
, (4':!&!&%*"'#'(
 (
 (
 (
T
 
 
 
  %)#$&"&	
 
 
 
.@ @ @ $ $ $
 
 
 
* $# %"' $"
 "
 "
 "
H5 5 5 5@	E 	E 	E #!%#	
 
 
 
.8 8 8: : :
8 
8 
8 
8 
8r   r:   c                   X     e Zd ZdZ fdZd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Z xZS )_TwistedConnectionAdaptera8  A Twisted-specific implementation of a Pika Connection.

    NOTE: since `base_connection.BaseConnection`'s primary responsibility is
    management of the transport, we use `pika.connection.Connection` directly
    as our base class because this adapter uses a different transport
    management strategy.

    c                     t          t          |                               ||||d           |pt          | _        d | _        d S )NF)
parameterson_open_callbackon_open_error_callbackon_close_callbackinternal_connection_workflow)r   r  r   r   _reactor
_transport)r   r  r  r  r  custom_reactorr   s         r   r   z"_TwistedConnectionAdapter.__init__  sS    '..77!-#9/). 	8 	0 	0 	0 '1'r   c                 r    t          |d           t          | j                            ||                    S )zXImplement
        :py:meth:`pika.connection.Connection._adapter_call_later()`.

        rY   )r   _TimerHandler!  	callLater)r   delayrY   s      r   _adapter_call_laterz-_TwistedConnectionAdapter._adapter_call_later'  s4    
 	8Z000DM33E8DDEEEr   c                 .    |                                  dS )z\Implement
        :py:meth:`pika.connection.Connection._adapter_remove_timeout()`.

        N)cancel)r   
timeout_ids     r   _adapter_remove_timeoutz1_TwistedConnectionAdapter._adapter_remove_timeout/  s    
 	r   c                 Z    t          |d           | j                            |           dS )zeImplement
        :py:meth:`pika.connection.Connection._adapter_add_callback_threadsafe()`.

        rY   N)r   r!  callFromThreadr   s     r    _adapter_add_callback_threadsafez:_TwistedConnectionAdapter._adapter_add_callback_threadsafe6  s0    
 	8Z000$$X.....r   c                     t           )zImplement pure virtual
        :py:ref:meth:`pika.connection.Connection._adapter_connect_stream()`
         method.

        NOTE: This should not be called due to our initialization of Connection
        via `internal_connection_workflow=False`
        )NotImplementedErrorr#   s    r   _adapter_connect_streamz1_TwistedConnectionAdapter._adapter_connect_stream>  s
     "!r   c                 8    | j                                          dS )zImplement pure virtual
        :py:ref:meth:`pika.connection.Connection._adapter_disconnect_stream()`
         method.

        N)r"  loseConnectionr#   s    r   _adapter_disconnect_streamz4_TwistedConnectionAdapter._adapter_disconnect_streamH  s     	&&(((((r   c                 :    | j                             |           dS )zoImplement pure virtual
        :py:ref:meth:`pika.connection.Connection._adapter_emit_data()` method.

        N)r"  writer   datas     r   _adapter_emit_dataz,_TwistedConnectionAdapter._adapter_emit_dataP  s     
 	d#####r   c                 <    || _         |                                  dS )zIntroduces transport to protocol after transport is connected.

        :param twisted.internet.interfaces.ITransport transport:
        :raises Exception: Exception-based exception on error

        N)r"  _on_stream_connectedr   	transports     r   connection_madez)_TwistedConnectionAdapter.connection_madeW  s#     $!!#####r   c                     d| _         |j        }t          |t          j                  r	|| _        d}t                              |t          j	        nt          j
        d|           |                     |           dS )a   Called upon loss or closing of TCP connection.

        NOTE: `connection_made()` and `connection_lost()` are each called just
        once and in that order. All other callbacks are called between them.

        :param Failure: A Twisted Failure instance wrapping an exception.

        Nzconnection_lost: %r)r"  valuer   twisted_errorConnectionDone_errorr   logloggingDEBUGERROR_on_stream_terminated)r   r   s     r   connection_lostz)_TwistedConnectionAdapter.connection_lostb  sv     e]9:: 	DKE

EM7==w}(%	1 	1 	1""5)))))r   c                 0    |                      |           dS )zCalled to deliver incoming data from the server to the protocol.

        :param data: Non-empty data bytes.
        :raises Exception: Exception-based exception on error

        N)_on_data_availabler8  s     r   data_receivedz'_TwistedConnectionAdapter.data_receivedt  s     	%%%%%r   )r-   r.   r/   r0   r   r(  r,  r/  r2  r5  r:  r?  rJ  rM  r1   r2   s   @r   r  r    s         
 
 
 
 
F F F  / / /" " ") ) )$ $ $	$ 	$ 	$* * *$& & & & & & &r   r  c                       e Zd ZdZddZddZed             Zed             Zdd	Z	d
 Z
ej        fdZd Zd Zd ZddZd Zd ZdS )TwistedProtocolConnectionaw  A Pika-specific implementation of a Twisted Protocol. Allows using
    Twisted's non-blocking connectTCP/connectSSL methods for connecting to the
    server.

    TwistedProtocolConnection objects have a `ready` instance variable that's a
    Deferred which fires when the connection is ready to be used (the initial
    AMQP handshaking has been done). You *have* to wait for this Deferred to
    fire before requesting a channel.

    Once the connection is ready, you will be able to use the `closed` instance
    variable: a Deferred which fires when the connection is closed.

    Since it's Twisted handling connection establishing it does not accept
    connect callbacks, you have to implement that within Twisted. Also remember
    that the host, port and ssl values of the connection parameters are ignored
    because, yet again, it's Twisted who manages the connection.

    Nc                      t          j                     _         j                             fd           d  _        t          | j         j         j        |           _	        t                       _        d S )Nc                 ,                                     S r   )connectionReady)_r   s    r   r   z4TwistedProtocolConnection.__init__.<locals>.<lambda>  s    )=)=)?)? r   )r  r  r  r  r#  )r   rL   readyrq   r   r  _on_connection_ready_on_connection_failed_on_connection_closed_implr?   r@   )r   r  r#  s   `  r   r   z"TwistedProtocolConnection.__init__  sx    ^%%

????@@@.!!6#'#="8)
 
 

 eer   c                    t          j                    }| j                            ||j                   | j                            |           |                    | j        |           |                    t                    S )a  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.

        :param int channel_number: The channel number to use, defaults to the
                                   next available.
        :returns: a Deferred that fires with an instance of a wrapper around
            the Pika Channel class.
        :rtype: Deferred

        )
r   rL   rX  r5   rY   r@   rp   rq   rr   r:   )r   r   rZ   s      r   r5   z!TwistedProtocolConnection.channel  sh     N
>1:666	d&***}}^,,,r   c                     | j         j        S r   )rX  r   r#   s    r   r   z!TwistedProtocolConnection.is_open  s     z!!r   c                     | j         j        S r   )rX  r   r#   s    r   r   z#TwistedProtocolConnection.is_closed  s     z##r      r   c                 ^    | j         j        s| j                             ||           | j        S r   )rX  r   r+   r   r   s      r   r+   zTwistedProtocolConnection.close  s/    z# 	5JZ444{r   c                 :    | j                             |           d S r   )rX  rM  r8  s     r   dataReceivedz&TwistedProtocolConnection.dataReceived  s    
  &&&&&r   c                     | j                             |           | j        d c}| _        |r|                    |           d S d S r   )rX  rJ  rT  r(   )r   r*   rZ   s      r   connectionLostz(TwistedProtocolConnection.connectionLost  sQ    
""6***
D4: 	IIf	 	r   c                 z    | j                             |           t          j                            | |           d S r   )rX  r?  r   ProtocolmakeConnectionr=  s     r   rd  z(TwistedProtocolConnection.makeConnection  s7    
""9---((y99999r   c                     | S )zLThis method will be called when the underlying connection is ready.
        r   r#   s    r   rR  z)TwistedProtocolConnection.connectionReady  s	     r   c                     | j         d c}| _         |r/t          j                    | _        |                    d            d S d S r   )rT  r   rL   r   rY   )r   _connectionrZ   s      r   rU  z.TwistedProtocolConnection._on_connection_ready  sJ    
D4: 	.**DKJJt	 	r   c                     | j         d c}| _         |r<| j        j        j        }t	          j        |          }|                    |           d S d S r   )rT  rX  paramsconnection_attemptsr	   AMQPConnectionErrorr(   )r   rg  _error_messagerZ   attemptsexcs         r   rV  z/TwistedProtocolConnection._on_connection_failed  sS    
D4: 	z(<H0::CIIcNNNNN	 	r   c                     | j         D ]}|                    |           t                      | _         | j        d c}| _        |r3t	          |t
                    r|j        }|                    |           d S d S r   )r@   r(   r?   r   r   r   rA  rY   )r   rg  	exceptionrZ   s       r   rW  z/TwistedProtocolConnection._on_connection_closed  s     	! 	!AIIi    eed4; 	")W-- , &O	JJy!!!!!	" 	"r   c                 :    | j                             |           |S r   r|   r~   s      r   rr   z%TwistedProtocolConnection._clear_call  r   r   r,   r   )r\  r   )r-   r.   r/   r0   r   r5   r  r   r   r+   r_  r   connectionDonera  rd  rR  rU  rV  rW  rr   r   r   r   rO  rO  ~  s        &   - - - -& " " X" $ $ X$   ' ' ' %-$;    : : :  
     " " "    r   rO  c                       e Zd ZdZd Zd ZdS )r%  zJThis module's adaptation of `nbio_interface.AbstractTimerReference`.

    c                     || _         dS )zC

        :param twisted.internet.base.DelayedCall handle:
        N)_handle)r   handles     r   r   z_TimerHandle.__init__  s    
 r   c                     | j         E	 | j                                          n!# t          j        t          j        f$ r Y nw xY wd | _         d S d S r   )ru  r*  rB  AlreadyCalledAlreadyCancelledr#   s    r   r*  z_TimerHandle.cancel  si    <###%%%%!/!24     DLLL $#s   # A AN)r-   r.   r/   r0   r   r*  r   r   r   r%  r%    s<                    r   r%  )&r0   rw   rF  collectionsr   twisted.internetr   r   rB  r   r   twisted.python.failurer   pika.connectionr   r	   r
   pika.adapters.utilsr   %pika.adapters.utils.io_services_utilsr   pika.exchange_typer   	getLoggerr-   r   r   r   r3   objectr:   r   
Connectionr  rc  rO  AbstractTimerReferencer%  r   r   r   <module>r     s  	 	      " " " " " " O O O O O O O O O O O O * * * * * *     ! ! ! ! ! ! ! ! . . . . . . D D D D D D + + + + + + 
	8	$	$2 2 2 2 2E/ 2 2 2j *.HHHJ Jt8 t8 t8 t8 t8V t8 t8 t8nj& j& j& j& j& : j& j& j&Zx x x x x 1 x x xv         >8          r   