
    E0j-                        d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZ d dlmZ d dl	m
Z
mZmZmZmZ d dlmZ d dlmZ d dlmZ d dlmZ  ej        d	          Ze                    ej                    ej                    Ze                    e            ed
          ZdZdZ ee          Z  eed          Z!d Z" ej#        e"           de$de$de$de$fdZ%de$de$fdZ& G d de          Z' G d de          Z( G d dee                   Z) G d d          Z* G d d e*          Z+ G d! d"e*          Z, G d# d$ee                   Z-dS )%    N)datetime)Enum)CallableGenericTypeVar	CoroutineAny)	Semaphore)ThreadPoolExecutor)CredentialException)ICredentialscredentialsTl    d   znon-blocking-refresh)max_workersthread_name_prefixc                  <    t                               d           d S )NF)wait)EXECUTORshutdown     u/home/rurouni/.hermes/hermes-agent/venv/lib/python3.11/site-packages/alibabacloud_credentials/provider/refreshable.py_shutdown_handlerr      s    5!!!!!r   nowjitter_start
jitter_endreturnc                 6    t          j        ||          }| |z   S N)randomrandint)r   r   r   jitter_amounts       r   _jitter_timer$   #   s    N<<<Mr   num_failuresc                 8    t          dd| dz
  z  dz            }|S )Ni'     r   )max)r%   backoff_milliss     r   _max_stale_failure_jitterr*   (   s&    Q,*:%:c$ABBNr   c                   t    e Zd Zdddddddededededef
dZd	efd
Zd	efdZd	efdZd	efdZ	d	efdZ
dS )CredentialsN)access_key_idaccess_key_secretsecurity_token
expirationprovider_namer-   r.   r/   r0   r1   c                L    || _         || _        || _        || _        || _        d S r    )_access_key_id_access_key_secret_security_token_expiration_provider_name)selfr-   r.   r/   r0   r1   s         r   __init__zCredentials.__init__.   s2     ,"3-%+r   r   c                     | j         S r    )r3   r8   s    r   get_access_key_idzCredentials.get_access_key_id:       ""r   c                     | j         S r    )r4   r;   s    r   get_access_key_secretz!Credentials.get_access_key_secret=   s    &&r   c                     | j         S r    )r5   r;   s    r   get_security_tokenzCredentials.get_security_token@   s    ##r   c                     | j         S r    )r6   r;   s    r   get_expirationzCredentials.get_expirationC       r   c                     | j         S r    )r7   r;   s    r   get_provider_namezCredentials.get_provider_nameF   r=   r   )__name__
__module____qualname__strintr9   r<   r?   rA   rC   rF   r   r   r   r,   r,   -   s        &**.'+#'&*
, 
, 
, #
,$'
, "%
, !	
,
 !$
, 
, 
, 
,#3 # # # #'s ' ' ' '$C $ $ $ $         #3 # # # # # #r   r,   c                       e Zd ZdZdZ	 dZdS )StaleValueBehaviora  
    Strictly treat the stale time. Never return a stale cached value (except when the supplier returns an expired
    value, in which case the supplier will return the value but only for a very short period of time to prevent
    overloading the underlying supplier).
    r   r'   N)rG   rH   rI   __doc__STRICTALLOWr   r   r   rM   rM   J   s+         
 F EEEr   rM   c                   N    e Zd ZeeddededefdZdefdZdefdZdefd	Z	d
S )RefreshResult)
stale_timeprefetch_timevaluerS   rT   c                0    || _         || _        || _        d S r    )_value_stale_time_prefetch_time)r8   rU   rS   rT   s       r   r9   zRefreshResult.__init__Y   s!     %+r   r   c                     | j         S r    )rW   r;   s    r   rU   zRefreshResult.valuea   s
    {r   c                     | j         S r    )rX   r;   s    r   rS   zRefreshResult.stale_timed   rD   r   c                     | j         S r    )rY   r;   s    r   rT   zRefreshResult.prefetch_timeg   r=   r   N)
rG   rH   rI   	INT64_MAXr   rK   r9   rU   rS   rT   r   r   r   rR   rR   X   s         $-&/, , ,, , !$, , , ,q     C        #s # # # # # #r   rR   c                   &    e Zd ZdefdZdefdZdS )PrefetchStrategyactionc                     t           r    NotImplementedErrorr8   r`   s     r   prefetchzPrefetchStrategy.prefetchl   s    !!r   c                    K   t           r    rb   rd   s     r   prefetch_asynczPrefetchStrategy.prefetch_asynco   s      !!r   NrG   rH   rI   r   re   rg   r   r   r   r_   r_   k   sJ        "x " " " ""8 " " " " " "r   r_   c                   &    e Zd ZdefdZdefdZdS )NonBlockingr`   c                    t                               d          st                              d           d S 	 t                              |           nL# t          $ r t                       Y n2t          $ r&}t                              dd           Y d }~nd }~ww xY wt           	                                 d S # t           	                                 w xY w)NFzRSkipping a background refresh task because there are too many other tasks running.z3Exception occurred when submitting background task.T)exc_info)
CONCURRENT_REFRESH_LEASESacquirelogwarningr   submitKeyboardInterruptr   	Exceptionrelease)r8   r`   ts      r   re   zNonBlocking.prefetchu   s    (0077 	KKlmmmF	0OOF####  	  	  	  	_ 	_ 	_KKNY]K^^^^^^^^	_ &--/////%--////s;   A B: B+B: -	B6BB: BB: :Cc                 @   K   fd}|                      |           d S )Nc                      t          j                    } t          j        |            |                                             |                                  d S r    )asyncionew_event_loopset_event_looprun_until_completeclose)loopr`   s    r   run_asyncio_loopz4NonBlocking.prefetch_async.<locals>.run_asyncio_loop   sM    )++D"4(((##FFHH---JJLLLLLr   )re   )r8   r`   r~   s    ` r   rg   zNonBlocking.prefetch_async   s;      	 	 	 	 	 	&'''''r   Nrh   r   r   r   rj   rj   s   sJ        0x 0 0 0 0(8 ( ( ( ( ( (r   rj   c                   &    e Zd ZdefdZdefdZdS )OneCallerBlocksr`   c                      |             d S r    r   rd   s     r   re   zOneCallerBlocks.prefetch   s    r   c                 *   K    |             d {V  d S r    r   rd   s     r   rg   zOneCallerBlocks.prefetch_async   s!      fhhr   Nrh   r   r   r   r   r      sJ        x    8      r   r   c                   $   e Zd ZdZdZej         e            fdeg e	e
         f         deg eeee	e
         f         f         dedefdZde
fd	Zde
fd
ZdefdZdefdZd Zd Zd Zd Zde	e
         de	e
         fdZdede	e
         fdZdS )RefreshCachedSupplieri     refresh_callablerefresh_callable_asyncstale_value_behaviorprefetch_strategyc                     || _         || _        || _        || _        d| _        d | _        t          j                    | _        d S )Nr   )	_refresh_callable_refresh_callable_async_stale_value_behavior_prefetch_strategy_consecutive_refresh_failures_cached_value	threadingLock_refresh_lock)r8   r   r   r   r   s        r   r9   zRefreshCachedSupplier.__init__   sJ    
 "2'=$%9""3-.*!&^--r   r   c                 b   |                                  r/t                              d           |                                  nT|                                 r@t                              d| j        j        j                    |                                  | j	        
                                S NzRefreshing synchronouslyzPrefetching using strategy: )_cache_is_stalero   debug_refresh_cache_should_initiate_cache_prefetchr   	__class__rG   _prefetch_cacher   rU   r;   s    r   
_sync_callz RefreshCachedSupplier._sync_call   s    !! 	#II0111!!!!1133 	#IIaT5L5V5_aabbb  """!'')))r   c                 ~  K   |                                  r5t                              d           |                                  d {V  nZ|                                 rFt                              d| j        j        j                    |                                  d {V  | j	        
                                S r   )r   ro   r   _refresh_cache_asyncr   r   r   rG   _prefetch_cache_asyncr   rU   r;   s    r   _async_callz!RefreshCachedSupplier._async_call   s      !! 	/II0111++----------1133 	/IIaT5L5V5_aabbb,,.........!'')))r   c                     | j         dS t          t          j        t          j                                        | j                                         k    S NT)r   rK   timemktime	localtimerS   r;   s    r   r   z%RefreshCachedSupplier._cache_is_stale   sD    %44;t~//0011T5G5R5R5T5TTTr   c                     | j         dS t          t          j        t          j                                        | j                                         k    S r   )r   rK   r   r   r   rT   r;   s    r   r   z5RefreshCachedSupplier._should_initiate_cache_prefetch   sD    %44;t~//0011T5G5U5U5W5WWWr   c                 D    | j                             | j                   d S r    )r   re   r   r;   s    r   r   z%RefreshCachedSupplier._prefetch_cache   s"    (()<=====r   c                    | j                             t          j                  }	 |                                 s|                                 r_	 |                     |                                           | _        n1# t          $ r$}| 
                    |          | _        Y d }~nd }~ww xY w|r| j                                          d S d S # |r| j                                          w w xY wN)timeout)r   rn   r   REFRESH_BLOCKING_MAX_WAITr   r   _handle_fetched_successr   r   rs   _handle_fetched_failurert   r8   acquiredexs      r   r   z$RefreshCachedSupplier._refresh_cache   s   %--6K6e-ff	-##%% J)M)M)O)O JJ)-)E)EdF\F\F^F^)_)_D&&  J J J)-)E)Eb)I)ID&&&&&&J  -"**,,,,,- -x -"**,,,,-s5   (C ,A= <C =
B+B&!C &B++C C+c                 T   K   | j                             | j                   d {V  d S r    )r   rg   r   r;   s    r   r   z+RefreshCachedSupplier._prefetch_cache_async   s8      %44T5NOOOOOOOOOOOr   c                   K   | j                             t          j                  }	 |                                 s|                                 re	 |                     |                                  d {V           | _        n1# t          $ r$}| 
                    |          | _        Y d }~nd }~ww xY w|r| j                                          d S d S # |r| j                                          w w xY wr   )r   rn   r   r   r   r   r   r   r   rs   r   rt   r   s      r   r   z*RefreshCachedSupplier._refresh_cache_async   s-     %--6K6e-ff	-##%% J)M)M)O)O JJ)-)E)EDLhLhLjLjFjFjFjFjFjFj)k)kD&&  J J J)-)E)Eb)I)ID&&&&&&J  -"**,,,,,- -x -"**,,,,-s5   (C 2B C 
B3B.)C .B33C C3rU   c           	         t                               d| d| j                    d| _        t	          t          j        t          j                                        }||                                k     rjt                               dt          j
        |                                           dt          j
        |                                                      |S ||                                t          j        z   k     rt                               dt          j
        |                                           dt          j
        |                      t          |                                ||                                          S t                               d	t          j
        |                                t          j        z              d
           | j        t#          d          || j                                        k     ryt                               dt          j
        | j                                                   dt          j
        | j                                                              | j        S | j        t&          j        k    rt                               dt          j
        | j                                                   dt          j
        |dz                         t          | j                                        |dz   | j                                                  S |t	          dt+          j        dd          z   dz            z   }t                               dt          j
        |           dt          j
        | j                                                              t          | j                                        || j                                                  S )Nz5Refresh credentials successfully, retrieved value is z, cached value is r   zRetrieved value stale time is z. Using staleTime of z+Retrieved value stale time is in the past (z). Using staleTime of rU   rS   rT   zBRetrieved value expiration time of the credential is in the past (z). Trying use the cached value.zNo cached value was found.zCached value staleTime is z(Cached value expiration is in the past (z). Using expiration of r'   iP  i!N    -Cached value expiration has been extended to z= because the downstream service returned a time in the past: )ro   r   r   r   rK   r   r   r   rS   r   fromtimestampr   
STALE_TIMErp   rR   rU   rT   r   r   rM   rO   r!   r"   )r8   rU   r   extended_stale_times       r   r   z-RefreshCachedSupplier._handle_fetched_success   s   		w%wwcgcuwwxxx-.*$+dn..//00!!####II _1GHXHXHZHZ1[1[  _  _rz  sI  JO  JZ  JZ  J\  J\  s]  s]  _  _` ` `L!!##&;&FFFFKK ^h>TUZUeUeUgUg>h>h  ^  ^  AI  AW  X[  A\  A\  ^  ^_ _ _ u{{}}TYTgTgTiTijjjj @QYQghmhxhxhzhz  ~S  ~^  i^  R_  R_  @  @  @	A 	A 	A %%&BCCC4%002222KK uX-CDDVDaDaDcDc-d-d  u  u  |D  |R  SW  Se  Sp  Sp  Sr  Sr  |s  |s  u  uv v v%%'+=+DDDKK m8;QRVRdRoRoRqRq;r;r  m  m  LT  Lb  cf  ij  cj  Lk  Lk  m  mn n n t'9'?'?'A'AcTUg/3/A/O/O/Q/QS S S S #&Y=9Y9Y-Y]a,a(b(b"bKK d@VWj@k@k  d  d  ks  kA  BF  BT  B_  B_  Ba  Ba  kb  kb  d  de e e t'9'?'?'A'ANa/3/A/O/O/Q/QS S S Sr   	exceptionc           	         t                               d| j         d|            | j        st                               |           |t	          t          j        t          j                                        }|| j                                        k     r| j        S | xj	        dz  c_	        | j
        t          j        k    rt                               |           |t	          t          |dz  dt          | j	                            dz            }t                               dt          j        |           d| j	         d           t#          | j                                        || j                                                  S )	Nz,Refresh credentials failed, cached value is z	, error: r'   r   r   zF because calling the downstream service failed (consecutive failures: z).r   )ro   rp   r   r   rK   r   r   r   rS   r   r   rM   rO   r$   r*   r   r   rR   rU   rT   )r8   r   r   new_stale_times       r   r   z-RefreshCachedSupplier._handle_fetched_failure  s   k4CUkk`ikklll! 	MM)$$$O$+dn..//00#..0000%%**a/**%);)BBBMM)$$$O S4Z/HIk/l/lmmpttv vNKK U@VWe@f@f  U  U  os  oQ  U  U  UV V V t'9'?'?'A'An/3/A/O/O/Q/QS S S Sr   N)rG   rH   rI   r   r   rM   rO   r   r   rR   r   r   r	   r_   r9   r   r   boolr   r   r   r   r   r   r   rs   r   r   r   r   r   r      s       J ! =O<U7F7H7H. ."mA6F2F)G .)1"iS-XYJZ@Z6[2[)\.'9. %5. . . .*A * * * **1 * * * *U U U U U
X X X X X
> > >
- 
- 
-P P P
- 
- 
-"S]1-= "S-PQBR "S "S "S "SHS S}Q?O S S S S S Sr   r   ).r!   rx   r   loggingr   atexitr   enumr   typingr   r   r   r   r	   r
   concurrent.futures.threadr   #alibabacloud_credentials.exceptionsr   alibabacloud_credentials_apir   	getLoggerro   setLevelINFOStreamHandlerch
addHandlerr   r]   MAX_CONCURRENT_REFRESHESrm   r   r   registerrK   r$   r*   r,   rM   rR   r_   rj   r   r   r   r   r   <module>r      s                        = = = = = = = = = = = = = =       8 8 8 8 8 8 C C C C C C 5 5 5 5 5 5g&& W\   W r   GCLL	 %I&>?? )H^___" " " ! " " "c  # #    
C C    
# # # # #, # # #:       # # # # #GAJ # # #&" " " " " " " "( ( ( ( (" ( ( (4    &   BS BS BS BS BSGAJ BS BS BS BS BSr   