
    ^fG                       d Z ddlmZ ddlZddlmZ ddlmZmZm	Z	 ddl
ZddlZddlZddlmZmZmZmZmZ ddlmZ 	 ddlmZmZ n# e$ r dZdZY nw xY wdd	lmZmZ dd
lmZmZ ddl m!Z! ddl"m#Z#  e$ej%                  h dz
  Z& e'd           e'd          id e&D             Z( G d d          Z) G d de#j*                  Z* G d de#j+                  Z+dS )aX  Azure Service Bus Message Queue transport module for kombu.

Note that the Shared Access Policy used to connect to Azure Service Bus
requires Manage, Send and Listen claims since the broker will create new
queues and delete old queues as required.


Notes when using with Celery if you are experiencing issues with programs not
terminating properly. The Azure Service Bus SDK uses the Azure uAMQP library
which in turn creates some threads. If the AzureServiceBus Channel is closed,
said threads will be closed properly, but it seems there are times when Celery
does not do this so these threads will be left running. As the uAMQP threads
are not marked as Daemon threads, they will not be killed when the main thread
exits. Setting the ``uamqp_keep_alive_interval`` transport option to 0 will
prevent the keep_alive thread from starting


More information about Azure Service Bus:
https://azure.microsoft.com/en-us/services/service-bus/

Features
========
* Type: Virtual
* Supports Direct: *Unreviewed*
* Supports Topic: *Unreviewed*
* Supports Fanout: *Unreviewed*
* Supports Priority: *Unreviewed*
* Supports TTL: *Unreviewed*

Connection String
=================

Connection string has the following formats:

.. code-block::

    azureservicebus://SAS_POLICY_NAME:SAS_KEY@SERVICE_BUSNAMESPACE
    azureservicebus://DefaultAzureCredential@SERVICE_BUSNAMESPACE
    azureservicebus://ManagedIdentityCredential@SERVICE_BUSNAMESPACE

Transport Options
=================

* ``queue_name_prefix`` - String prefix to prepend to queue names in a
  service bus namespace.
* ``wait_time_seconds`` - Number of seconds to wait to receive messages.
  Default ``5``
* ``peek_lock_seconds`` - Number of seconds the message is visible for before
  it is requeued and sent to another consumer. Default ``60``
* ``uamqp_keep_alive_interval`` - Interval in seconds the Azure uAMQP library
  should send keepalive messages. Default ``30``
* ``retry_total`` - Azure SDK retry total. Default ``3``
* ``retry_backoff_factor`` - Azure SDK exponential backoff factor.
  Default ``0.8``
* ``retry_backoff_max`` - Azure SDK retry total time. Default ``120``
    )annotationsN)Empty)AnyDictSet)ServiceBusClientServiceBusMessageServiceBusReceiveModeServiceBusReceiverServiceBusSender)ServiceBusAdministrationClient)DefaultAzureCredentialManagedIdentityCredential)bytes_to_strsafe_str)dumpsloads)cached_property   )virtual>   _-.r   r   c                H    i | ]}t          |          t          d            S )r   )ord).0cs     Q/var/www/html/env/lib/python3.11/site-packages/kombu/transport/azureservicebus.py
<dictcomp>r   Y   s&    999As1vvs3xx999    c                  (    e Zd ZdZ	 	 dddZdd
ZdS )SendReceivez"Container for Sender and Receiver.NreceiverServiceBusReceiver | NonesenderServiceBusSender | Nonec                "    || _         || _        d S N)r#   r%   )selfr#   r%   s      r   __init__zSendReceive.__init__`   s     -5(.r    returnNonec                    | j         r | j                                          d | _         | j        r"| j                                         d | _        d S d S r(   )r#   closer%   r)   s    r   r.   zSendReceive.closef   sZ    = 	!M!!! DM; 	KDKKK	 	r    NN)r#   r$   r%   r&   r+   r,   )__name__
__module____qualname____doc__r*   r.    r    r   r"   r"   ]   sO        ,, 8<37/ / / / /     r    r"   c                  ^    e Zd ZU dZdZded<   dZded<   dZded<   d	Zded
<   dZ	ded<   dZ
ded<   dZded<   i Zded<    e            Zded<    fdZdNdZ fdZ fdZ	 	 dOdPd$ZdQd&Zej        dfdRd+Z	 dSdTd.ZdUd1ZdQd2ZdVd3ZdVd4Z	 dSdWd8ZdXdY fd=ZdZd>Zd[d?Z dNd@Z!e"d\dB            Z#e"d]dD            Z$e%dE             Z&e%dF             Z'e"d^dG            Z(e"d[dH            Z)e"d[dI            Z*e"d[dJ            Z+e"d[dK            Z,e"d_dL            Z-e"d[dM            Z. xZ/S )`ChannelzAzure Service Bus channel.   intdefault_wait_time_seconds<   default_peek_lock_seconds   !default_uamqp_keep_alive_interval   default_retry_totalg?floatdefault_retry_backoff_factorx   default_retry_backoff_maxzkombu%(vhost)sstrdomain_formatzDict[str, SendReceive]_queue_cachezSet[str]_noack_queuesc                     t                      j        |i | d | _        d | _        d | _        d | _        |                                  d| j        _        d S )NF)	superr*   
_namespace_policy_sas_key_connection_string_try_parse_connection_stringqosrestore_at_shutdown)r)   argskwargs	__class__s      r   r*   zChannel.__init__   s^    $)&)))"&))+++',$$$r    r+   r,   c                   t                               | j        j                  \  | _        | _        t          t          | j        t                    s!t          t          | j        t                    rd S d| j        v r(| j        	                    dd          \  | _
        | _        d| j        z   | j
        | j        d}d                    d |                                D                       | _        d S )N:r   zsb://)EndpointSharedAccessKeyNameSharedAccessKey;c                $    g | ]\  }}|d z   |z   S )=r6   )r   keyvalues      r   
<listcomp>z8Channel._try_parse_connection_string.<locals>.<listcomp>   s%    CCC:3S3YCCCr    )	Transport	parse_uriconninfohostnamerL   _credentialr   
isinstancer   splitrM   rN   joinitemsrO   )r)   	conn_dicts     r   rP   z$Channel._try_parse_connection_string   s    ,5,?,?M"-$ -$)) #.4+-CDD / &14+-FGG 2 4$"""*.*:*@*@a*H*H'DL$-  $/1#'<#}
 
	
 #&((CC1B1BCCC#E #Er    c                x    |r| j                             |            t                      j        ||g|R i |S r(   )rI   addrK   basic_consume)r)   queueno_ackrS   rT   rU   s        r   rm   zChannel.basic_consume   s\     	*""5)))$uww$6
 
 
 
$*
 
 	
r    c                    || j         v r'| j        |         }| j                            |           t	                                          |          S r(   )
_consumers_tag_to_queuerI   discardrK   basic_cancel)r)   consumer_tagrn   rU   s      r   rt   zChannel.basic_cancel   sL    4?**&|4E&&u---ww##L111r    Nnamer#   r$   r%   r&   r"   c                    || j         v r*| j         |         }|j        p||_        |j        p||_        nt          ||          }|| j         |<   |S r(   )rH   r%   r#   r"   )r)   rv   r#   r%   objs        r   _add_queue_to_cachezChannel._add_queue_to_cache   s^    
 4$$$#D)C-vCJ<38CLLh//C&)Dd#
r    rn   c                    | j                             |d           }||j        8| j                            || j                  }|                     ||          }|S )N)
keep_alive)r%   )rH   getr%   queue_serviceget_queue_senderuamqp_keep_alive_intervalry   )r)   rn   	queue_objr%   s       r   _get_asb_senderzChannel._get_asb_sender   sm    %))%66		 0 8'88$"@ 9 B BF00v0FFIr    	recv_moder
   queue_cache_key
str | Nonec                    |p|}| j                             |d           }||j        9| j                            ||| j                  }|                     ||          }|S )N)
queue_namereceive_moder{   )r#   )rH   r|   r#   r}   get_queue_receiverr   ry   )r)   rn   r   r   	cache_keyr   r#   s          r   _get_asb_receiverzChannel._get_asb_receiver   s|     $,u	%)))T::		 2 :)<< y9 = ; ;H 00X0NNIr    tabledict[int, int] | Nonec                n    t          t          |                                        |pt                    S )z:Format AMQP queue name into a valid ServiceBus queue name.)rF   r   	translateCHARS_REPLACE_TABLE)r)   rv   r   s      r   entity_namezChannel.entity_name   s,     8D>>"",,U-I6IJJJr    messagevirtual.base.Messagec                    d S r(   r6   )r)   r   s     r   _restorezChannel._restore   s	    
 	r    c                t   |                      | j        |z             }	 | j        |         S # t          $ r t	          j        t	          j        | j                            }	 | j        	                    ||           n# t          j        j        j        $ r Y nw xY w|                     |          cY S w xY w)z$Ensure a queue exists in ServiceBus.)seconds)r   lock_duration)r   queue_name_prefixrH   KeyErrorisodateduration_isoformatDurationpeek_lock_secondsqueue_mgmt_servicecreate_queueazurecore
exceptionsResourceExistsErrorry   )r)   rn   rT   r   s       r   
_new_queuezChannel._new_queue   s      !7%!?@@	3$U++ 
	3 
	3 
	3 $6 )?@@@B BM'44$M 5 C C C C:(<   ++E22222
	3s3   , 6B7#B ?B7 BB7BB76B7c                    |                      | j        |z             }| j                            |           | j                            |d          }|r|                                 dS dS )zDelete queue by name.N)r   r   r   delete_queuerH   popr.   )r)   rn   rS   rT   send_receive_objs        r   _deletezChannel._delete   sw      !7%!?@@,,U333,00== 	%""$$$$$	% 	%r    c                    |                      | j        |z             }t          t          |                    }|                     |          }|j                            |           dS )zPut message onto queue.N)r   r   r	   r   r   r%   send_messages)r)   rn   r   rT   msgr   s         r   _putzChannel._put   s`      !7%!?@@g//((//	&&s+++++r    timeoutfloat | int | Nonedict[str, Any]c                   || j         v rt          j        nt          j        }|                     | j        |z             }|                     ||          }|j                            d|p| j	                  }|st                      |d         }t          |j        t                    sd                    |j                  }n|j        }t          t!          |                    }||d         d         d<   ||d         d         d<   |S )	z/Try to retrieve a single message off ``queue``.r   max_message_countmax_wait_timer   r    
propertiesdelivery_infoazure_messageazure_queue_name)rI   r
   RECEIVE_AND_DELETE	PEEK_LOCKr   r   r   r#   receive_messageswait_time_secondsr   rf   bodybytesrh   r   r   )	r)   rn   r   r   r   messagesr   r   r   s	            r   _getzChannel._get  s    *** *<<0E0O 	   !7%!?@@**5)<<	%66!;T%; 7 = =  	''M 1+',.. 	 88GL))DD<DL&&''>EL/*?;AFL/*+=>
r    Fdelivery_tagmultipleboolc                F   	 | j                             |          j        }|d         }|                     |          }	 |j                            |d                    t                                          |           d S # t          j	        j
        j        $ r% t                                          |           Y d S t          $ r% t                                          |           Y d S w xY w# t          $ r% t                                          |           Y d S w xY w)Nr   r   )rQ   r|   r   r   r#   complete_messagerK   	basic_ackr   
servicebusr   MessageAlreadySettled	Exceptionbasic_rejectr   )r)   r   r   r   rn   r   rU   s         r   r   zChannel.basic_ack#  s>   	0 HLL66DM ""45E..u55I0"33!/24 4 4 !!,///// #.D 0 0 0!!,////// 3 3 3$$\2222223  	, 	, 	,GGl++++++	,s)   C1   B :C. *C.-C.1+D D c                ~    |                      | j        |z             }| j                            |          }|j        S )z)Return the number of messages in a queue.)r   r   r   get_queue_runtime_propertiestotal_message_count)r)   rn   propss      r   _sizezChannel._size7  s<      !7%!?@@'DDUKK((r    c                r   d}d}|                      | j        |z             }| j                            |d          }|| j        vs	||j        $|                     |t          j        d|z             }	 |j        	                    |d          }|t          |          z  }t          |          |k     rnC|S )z'Delete all current messages in a queue.r   
   Npurge_Tg?r   )r   r   rH   r|   rI   r#   r   r
   r   r   len)r)   rn   nmax_purge_countr   r   s         r   _purgezChannel._purge>  s       !7%!?@@ %))%66	***	 2 :..%8(U:J I
	 )::"1! ;  H XA8}}..	 r    c                    | j         ssd| _         | j                                        D ]}|                                 | j                                         | j        | j                            |            d S d S d S )NT)closedrH   valuesr.   clear
connectionclose_channel)r)   r   s     r   r.   zChannel.closeZ  s    { 	4DK!.5577 " "	!!!!##%%%*--d33333	4 	4 +*r    r   c                    | j         r,t          j        | j         | j        | j        | j                  S t          | j        | j        | j        | j        | j                  S )N)retry_totalretry_backoff_factorretry_backoff_max)rO   r   from_connection_stringr   r   r   rL   re   r/   s    r   r}   zChannel.queue_servicee  su    " 	#:' ,%)%>"&"8	     O(!%!:"4
 
 
 	
r    r   c                v    | j         rt          j        | j                   S t          | j        | j                  S r(   )rO   r   r   rL   re   r/   s    r   r   zChannel.queue_mgmt_servicew  sF    " 	1H'   .OT-
 
 	
r    c                    | j         j        S r(   )r   clientr/   s    r   rc   zChannel.conninfo  s    %%r    c                $    | j         j        j        S r(   )r   r   transport_optionsr/   s    r   r   zChannel.transport_options  s    %77r    c                8    | j                             dd          S )Nr    )r   r|   r/   s    r   r   zChannel.queue_name_prefix  s    %))*=rBBBr    c                B    | j                             d| j                  S )Nr   )r   r|   r;   r/   s    r   r   zChannel.wait_time_seconds  s)    %))*=*.*HJ J 	Jr    c                ^    t          | j                            d| j                  d          S )Nr   i,  )minr   r|   r=   r/   s    r   r   zChannel.peek_lock_seconds  s7    4)--.A.2.LN N  	r    c                B    | j                             d| j                  S )Nr   )r   r|   r?   r/   s    r   r   z!Channel.uamqp_keep_alive_interval  s&    %))'2
 
 	
r    c                B    | j                             d| j                  S )Nr   )r   r|   rA   r/   s    r   r   zChannel.retry_total  s%    %))435 5 	5r    c                B    | j                             d| j                  S )Nr   )r   r|   rC   r/   s    r   r   zChannel.retry_backoff_factor  s(    %))"D$EG G 	Gr    c                B    | j                             d| j                  S )Nr   )r   r|   rE   r/   s    r   r   zChannel.retry_backoff_max  s(    %))!?A A 	Ar    r1   r0   )rv   rF   r#   r$   r%   r&   r+   r"   )rn   rF   r+   r"   )rn   rF   r   r
   r   r   r+   r"   r(   )rv   rF   r   r   r+   rF   )r   r   r+   r,   )rn   rF   r+   r,   )rn   rF   r   r   r+   r   )F)r   rF   r   r   r+   r,   )rn   rF   r+   r:   )r+   r:   )r+   r   )r+   r   )r+   rF   )r+   rB   )0r2   r3   r4   r5   r;   __annotations__r=   r?   rA   rC   rE   rG   rH   setrI   r*   rP   rm   rt   ry   r   r
   r   r   r   r   r   r   r   r   r   r   r   r.   r   r}   r   propertyrc   r   r   r   r   r   r   r   r   __classcell__)rU   s   @r   r8   r8   o   s        $$%&&&&&%'''''-/%////     *- ----%((((()M))))+-L----!ceeM####
- 
- 
- 
- 
-E E E E0
 
 
 
 
2 2 2 2 2 37.2        0E/N*.     =AK K K K K
   3 3 3 3$% % % %, , , , +/    @0 0 0 0 0 0 0() ) ) )   8	4 	4 	4 	4 
 
 
 _
" 
 
 
 _
 & & X& 8 8 X8 C C C _C J J J _J    _
 
 
 
 _
 5 5 5 _5 G G G _G A A A _A A A A Ar    r8   c                  T    e Zd ZdZeZdZdZdZedd	            Z	e
ddd            ZdS )ra   zAzure Service Bus transport.r   NTurirF   r+   Dtuple[str, str | DefaultAzureCredential | ManagedIdentityCredential]c                X   |                      dd          } |                     dd          \  }}|                    d          s|dz  }d                                |                                k    r%t          t          d          t	                      }nod	                                |                                k    r%t          t          d
          t                      }n |                    dd          \  }}| d| }t          ||g          st          d          ||fS )Nzazureservicebus://r   @r   z.netz.servicebus.windows.netr   z]Azure Service Bus transport with a DefaultAzureCredential requires the azure-identity libraryr   z`Azure Service Bus transport with a ManagedIdentityCredential requires the azure-identity libraryrW   z|Need a URI like azureservicebus://{SAS policy name}:{SAS key}@{ServiceBus Namespace} or the azure Endpoint connection string)
replacersplitendswithlowerr   ImportErrorr   rg   all
ValueError)r   
credential	namespacepolicysas_keys        r   rb   zTransport.parse_uri  sX    kk.33 #

3 2 2
I!!&)) 	322I#))++z/?/?/A/AAA%-! #; < < < 011JJ(..00J4D4D4F4FFF(0! #; < < < 344JJ )..sA66OFG"..W..J Iz*++ 	:   *$$r    F**c                   |                      |          \  }}t          |t                    r8d|v r4|                    dd          \  }}d                    ||r|n||          S d                    |j        j        |          S )NrW   r   zazureservicebus://{}:{}@{}zazureservicebus://{}@{})rb   rf   rF   rg   formatrU   r2   )clsr   include_passwordmaskr  r   r  r  s           r   as_urizTransport.as_uri  s     #c 2 2	:j#&& 	3*+<+<(..sA66OFG/66+5   )// )
 
 	
r    )r   rF   r+   r   )Fr  )r   rF   r+   rF   )r2   r3   r4   r5   r8   polling_intervaldefault_portcan_parse_urlstaticmethodrb   classmethodr
  r6   r    r   ra   ra     ss        &&GLM(% (% (% \(%T 
 
 
 
 [
 
 
r    ra   ),r5   
__future__r   stringrn   r   typingr   r   r   azure.core.exceptionsr   azure.servicebus.exceptionsr   azure.servicebusr   r	   r
   r   r   azure.servicebus.managementr   azure.identityr   r   r   kombu.utils.encodingr   r   kombu.utils.jsonr   r   kombu.utils.objectsr   r   r   r   punctuationPUNCTUATIONS_TO_REPLACEr   r   r"   r8   ra   r6   r    r   <module>r     s  7 7r # " " " " "        ! ! ! ! ! ! ! ! ! !     " " " " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 G F F F F F%; ; ; ; ; ; ; ; ; % % %! $% 8 7 7 7 7 7 7 7 ) ) ) ) ) ) ) ) / / / / / /       #f011OOOC CHHcc#hh99!8999        $~A ~A ~A ~A ~Ago ~A ~A ~AB
B
 B
 B
 B
 B
! B
 B
 B
 B
 B
s   A 	AA