o
    —¨ÊhÙ4  ã                   @  s–  d Z ddlm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
mZ ddlmZ ddlmZmZmZmZ dd	lmZmZ d
dlmZmZ d
dlmZ d
dlmZ d
dlmZ dZdZ ee!ƒZ"da#dd„ Z$dd„ Z%d;dd„Z&G dd„ deƒZ'dd„ Z(d<dd„Z)dd „ Z*d!d"„ Z+d#d$„ Z,d=d%d&„Z-		d=d'd(„Z.d>d)d*„Z/	d?d+d,„Z0d-d.„ Z1d/d0„ Z2e	d1d2„ ƒZ3d@d3d4„Z4d@d5d6„Z5dAd7d8„Z6G d9d:„ d:ƒZ7dS )BzCommon Utilities.é    )ÚannotationsN)Údeque)Úcontextmanager)Úpartial)Úcount)ÚNAMESPACE_OIDÚuuid3Úuuid4Úuuid5)ÚChannelErrorÚRecoverableConnectionErroré   )ÚExchangeÚQueue)Ú
get_logger)Úregistry)Úuuid)	Ú	BroadcastÚmaybe_declarer   ÚitermessagesÚ
send_replyÚcollect_repliesÚinsuredÚdrain_consumerÚ	eventloopiÿÿ  c                   C  s   t d u rtƒ ja t S ©N)Ú_node_idr	   Úint© r   r   ú>/var/www/html/env/lib/python3.10/site-packages/kombu/common.pyÚget_node_id"   s   r    c                 C  sL   d  | ||t|ƒ¡}z
ttt|ƒƒ}W |S  ty%   ttt|ƒƒ}Y |S w )Nz{:x}-{:x}-{:x}-{:x})ÚformatÚidÚstrr   r   Ú
ValueErrorr
   )Únode_idÚ
process_idÚ	thread_idÚinstanceÚentÚretr   r   r   Úgenerate_oid)   s   ÿþþr+   Tc                 C  s$   t tƒ t ¡ |rt ¡ | ƒS d| ƒS ©Nr   )r+   r    ÚosÚgetpidÚ	threadingÚ	get_ident)r(   Úthreadsr   r   r   Úoid_from3   s   
üür2   c                      s8   e Zd ZdZejd Z						d‡ fdd„	Z‡  ZS )	r   a–  Broadcast queue.

    Convenience class used to define broadcast queues.

    Every queue instance will have a unique name,
    and both the queue and exchange is configured with auto deletion.

    Arguments:
    ---------
        name (str): This is used as the name of the exchange.
        queue (str): By default a unique id is used for the queue
            name for every consumer.  You can specify a custom
            queue name here.
        unique (bool): Always create a unique queue
            even if a queue name is supplied.
        **kwargs (Any): See :class:`~kombu.Queue` for a list
            of additional keyword arguments supported.
    ))ÚqueueNNFTc              
     sb   |rd  |pdtƒ ¡}n|pdtƒ › �}tƒ jd|p|||||d ur$|nt|dd�dœ|¤Ž d S )Nz{}.{}Úbcastzbcast.Úfanout)Útype)Úaliasr3   ÚnameÚauto_deleteÚexchanger   )r!   r   ÚsuperÚ__init__r   )Úselfr8   r3   Úuniquer9   r:   r7   Úkwargs©Ú	__class__r   r   r<   R   s   
ú
ùzBroadcast.__init__)NNFTNN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Úattrsr<   Ú__classcell__r   r   r@   r   r   <   s    
úr   c                 C  s   | |j jjv S r   )Ú
connectionÚclientÚdeclared_entities)ÚentityÚchannelr   r   r   Údeclaration_cachedi   s   rM   Fc                 K  s    |rt | |fi |¤ŽS t| |ƒS )zDeclare entity (cached).)Ú_imaybe_declareÚ_maybe_declare)rK   rL   ÚretryÚretry_policyr   r   r   r   m   s   
r   c                 C  s4   | j }|s|std|› d| › �ƒ‚|  |¡} | S dS )zÓMake sure the channel is bound to the entity.

    :param entity: generic kombu nomenclature, generally an exchange or queue
    :param channel: channel to bind to the entity
    :return: the updated entity
    zCannot bind channel z to entity N)Úis_boundr   Úbind)rK   rL   rR   r   r   r   Ú_ensure_channel_is_boundt   s   ÿ
ûrT   c                 C  s¨   | }t | |ƒ |d u r| jstd| › d�ƒ‚| j}d  }}|jr2| jr2|jjj}t| ƒ}||v r2dS |js9t	dƒ‚| j
|d� |d urJ|rJ| |¡ |d urR| j|_dS )Nzchannel is None and entity z not bound.Fúchannel disconnected)rL   T)rT   rR   r   rL   rH   Úcan_cache_declarationrI   rJ   Úhashr   ÚdeclareÚaddr8   )rK   rL   ÚorigÚdeclaredÚidentr   r   r   rO   „   s,   

ÿ

rO   c                 K  s:   t | |ƒ | jjstdƒ‚| jjjj| tfi |¤Ž| |ƒS )NrU   )rT   rL   rH   r   rI   ÚensurerO   )rK   rL   rQ   r   r   r   rN   ¡   s   

ÿÿÿrN   c              
   #  sŠ   � t ƒ ‰ ‡ fdd„}|g|pg  | _| �' t| jjj||dd�D ]}zˆ  ¡ V  W q  ty2   Y q w W d  ƒ dS 1 s>w   Y  dS )z&Drain messages from consumer instance.c                   s   ˆ   | |f¡ d S r   )Úappend)ÚbodyÚmessage©Úaccr   r   Ú
on_message¯   s   z"drain_consumer.<locals>.on_messageT)ÚlimitÚtimeoutÚignore_timeoutsN)r   Ú	callbacksr   rL   rH   rI   ÚpopleftÚ
IndexError)Úconsumerrd   re   rg   rc   Ú_r   ra   r   r   «   s   €

ÿÿü"ÿr   c                 K  s$   t | jd|g|dœ|¤Ž|||d�S )zIterator over messages.)ÚqueuesrL   )rd   re   rg   Nr   )r   ÚConsumer)ÚconnrL   r3   rd   re   rg   r?   r   r   r   r   ½   s   þr   c              	   c  sN   � |rt |ƒp	tƒ D ]}z	| j|d�V  W q
 tjy$   |r"|s"‚ Y q
w dS )a   Best practice generator wrapper around ``Connection.drain_events``.

    Able to drain events forever, with a limit, and optionally ignoring
    timeout errors (a timeout of 1 is often used in environments where
    the socket can get "stuck", and is a best practice for Kombu consumers).

    ``eventloop`` is a generator.

    Examples
    --------
        >>> from kombu.common import eventloop

        >>> def run(conn):
        ...     it = eventloop(conn, timeout=1, ignore_timeouts=True)
        ...     next(it)   # one event consumed, or timed out.
        ...
        ...     for _ in eventloop(conn, timeout=1, ignore_timeouts=True):
        ...         pass  # loop forever.

    It also takes an optional limit parameter, and timeout errors
    are propagated by default::

        for _ in eventloop(connection, limit=1, timeout=1):
            pass

    See Also
    --------
        :func:`itermessages`, which is an event loop bound to one or more
        consumers, that yields any messages received.
    )re   N)Úranger   Údrain_eventsÚsocketre   )rn   rd   re   rf   Úir   r   r   r   Æ   s   €€þýr   c              	   K  sH   |j |f| ||dœt|jd |j d¡tj|j |jdœfi |¤Ž¤ŽS )aÁ  Send reply for request.

    Arguments:
    ---------
        exchange (kombu.Exchange, str): Reply exchange
        req (~kombu.Message): Original request, a message with
            a ``reply_to`` property.
        producer (kombu.Producer): Producer instance
        retry (bool): If true must retry according to
            the ``reply_policy`` argument.
        retry_policy (Dict): Retry settings.
        **props (Any): Extra properties.
    )r:   rP   rQ   Úreply_toÚcorrelation_id)Úrouting_keyrt   Ú
serializerÚcontent_encoding)ÚpublishÚdictÚ
propertiesÚgetÚserializersÚtype_to_nameÚcontent_typerw   )r:   ÚreqÚmsgÚproducerrP   rQ   Úpropsr   r   r   r   í   s   ÿþ


ýýýr   c           	   	   o  s|   � |  dd¡}d}z*t| ||g|¢R i |¤ŽD ]\}}|s!| ¡  d}|V  qW |r2| |j¡ dS dS |r=| |j¡ w w )z,Generator collecting replies from ``queue``.Úno_ackTFN)Ú
setdefaultr   ÚackÚafter_reply_message_receivedr8   )	rn   rL   r3   Úargsr?   rƒ   Úreceivedr_   r`   r   r   r   r     s&   €
ÿÿûÿÿr   c                 C  s   t jd| |dd� d S )Nz#Connection error: %r. Retry in %ss
T)Úexc_info)ÚloggerÚerror)ÚexcÚintervalr   r   r   Ú_ensure_errback  s   
þrŽ   c              	   c  s,   � zd V  W d S  | j | j y   Y d S w r   )Úconnection_errorsÚchannel_errors)rn   r   r   r   Ú_ignore_errors  s   €ÿr‘   c                 O  sB   |rt | ƒ� ||i |¤ŽW  d  ƒ S 1 sw   Y  t | ƒS )aã  Ignore connection and channel errors.

    The first argument must be a connection object, or any other object
    with ``connection_error`` and ``channel_error`` attributes.

    Can be used as a function:

    .. code-block:: python

        def example(connection):
            ignore_errors(connection, consumer.channel.close)

    or as a context manager:

    .. code-block:: python

        def example(connection):
            with ignore_errors(connection):
                consumer.channel.close()


    Note:
    ----
        Connection and channel errors should be properly handled,
        and not ignored.  Using this function is only acceptable in a cleanup
        phase, like when a connection is lost or at shutdown.
    N)r‘   )rn   Úfunr‡   r?   r   r   r   Úignore_errors%  s
   
 ÿr“   c                 C  s   |r||ƒ d S d S r   r   )rH   rL   Ú	on_reviver   r   r   Úrevive_connectionG  s   ÿr•   c                 K  s�   |pt }| jdd��4}|j|d� |j}tt||d�}	|j||f||	dœ|¤Ž}
|
|i t||d�¤Ž\}}|W  d  ƒ S 1 sAw   Y  dS )z›Function wrapper to handle connection errors.

    Ensures function performing broker commands completes
    despite intermittent connection failures.
    T)Úblock)Úerrback)r”   )r—   r”   )rH   N)rŽ   ÚacquireÚensure_connectionÚdefault_channelr   r•   Ú	autoretryry   )Úpoolr’   r‡   r?   r—   r”   Úoptsrn   rL   Úreviver   Úretvalrk   r   r   r   r   L  s   ÿÿ$÷r   c                   @  s@   e Zd ZdZdZdd„ Zddd„Zddd	„Zd
d„ Zdd„ Z	dS )ÚQoSaø  Thread safe increment/decrement of a channels prefetch_count.

    Arguments:
    ---------
        callback (Callable): Function used to set new prefetch count,
            e.g. ``consumer.qos`` or ``channel.basic_qos``.  Will be called
            with a single ``prefetch_count`` keyword argument.
        initial_value (int): Initial prefetch count value..

    Example:
    -------
        >>> from kombu import Consumer, Connection
        >>> connection = Connection('amqp://')
        >>> consumer = Consumer(connection)
        >>> qos = QoS(consumer.qos, initial_prefetch_count=2)
        >>> qos.update()  # set initial

        >>> qos.value
        2

        >>> def in_some_thread():
        ...     qos.increment_eventually()

        >>> def in_some_other_thread():
        ...     qos.decrement_eventually()

        >>> while 1:
        ...    if qos.prev != qos.value:
        ...        qos.update()  # prefetch changed so update.

    It can be used with any function supporting a ``prefetch_count`` keyword
    argument::

        >>> channel = connection.channel()
        >>> QoS(channel.basic_qos, 10)


        >>> def set_qos(prefetch_count):
        ...     print('prefetch count now: %r' % (prefetch_count,))
        >>> QoS(set_qos, 10)
    Nc                 C  s   || _ t ¡ | _|pd| _d S r,   )Úcallbackr/   ÚRLockÚ_mutexÚvalue)r=   r¡   Úinitial_valuer   r   r   r<   �  s   
zQoS.__init__r   c                 C  sZ   | j � | jr| jt|dƒ | _W d  ƒ | jS W d  ƒ | jS 1 s%w   Y  | jS )zÃIncrement the value, but do not update the channels QoS.

        Note:
        ----
            The MainThread will be responsible for calling :meth:`update`
            when necessary.
        r   N)r£   r¤   Úmax©r=   Únr   r   r   Úincrement_eventually’  s   
þþ
ÿýzQoS.increment_eventuallyc                 C  sx   | j �. | jr|  j|8  _| jdk r(d| _W d  ƒ | jS W d  ƒ | jS W d  ƒ | jS 1 s4w   Y  | jS )zÃDecrement the value, but do not update the channels QoS.

        Note:
        ----
            The MainThread will be responsible for calling :meth:`update`
            when necessary.
        r   N)r£   r¤   r§   r   r   r   Údecrement_eventuallyŸ  s   

üü
ÿþ
ýûzQoS.decrement_eventuallyc                 C  sH   || j kr"|}|tkrt dt¡ d}t d|¡ | j|d� || _ |S )z#Set channel prefetch_count setting.z(QoS: Disabled: prefetch_count exceeds %rr   zbasic.qos: prefetch_count->%s)Úprefetch_count)ÚprevÚPREFETCH_COUNT_MAXrŠ   ÚwarningÚdebugr¡   )r=   ÚpcountÚ	new_valuer   r   r   Úset®  s   
ÿzQoS.setc                 C  s6   | j � |  | j¡W  d  ƒ S 1 sw   Y  dS )z)Update prefetch count with current value.N)r£   r²   r¤   )r=   r   r   r   Úupdate»  s   
$ÿz
QoS.update)r   )
rB   rC   rD   rE   r¬   r<   r©   rª   r²   r³   r   r   r   r   r    `  s    *

r    )T)NF)r   NN)NNF)NFNr   )NN)8rE   Ú
__future__r   r-   rq   r/   Úcollectionsr   Ú
contextlibr   Ú	functoolsr   Ú	itertoolsr   r   r   r   r	   r
   Úamqpr   r   rK   r   r   Úlogr   Úserializationr   r|   Ú
utils.uuidÚ__all__r­   rB   rŠ   r   r    r+   r2   r   rM   r   rT   rO   rN   r   r   r   r   r   rŽ   r‘   r“   r•   r   r    r   r   r   r   Ú<module>   sV    

	-



ÿ
	(
ÿ


"
