
    keJi.                        d dl Z d dlZd dlZd dlmZ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 d dlmZ  ej        e          Z G d d	          Z G d
 d          Z G d d          Z G d d          Zd Zde j        fdZdS )    N)datetimetimezone)sleep)Any	AwaitableCallableUnion)RequestTokenErrTokenRenewalErr)IdentityProviderInterface)TokenResponsec                   ,   e Zd ZdZd Zedeeegdf         e	f         fd            Z
e
j        deeegdf         e	f         ddfd            Z
edeeegdf         e	f         fd            Zej        deeegdf         e	f         ddfd	            ZdS )
CredentialsListenerzz
    Listeners that will be notified on events related to credentials.
    Accepts callbacks and awaitable callbacks.
    c                 "    d | _         d | _        d S N)_on_next	_on_errorselfs    ^/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/redis/auth/token_manager.py__init__zCredentialsListener.__init__   s        returnNc                     | j         S r   r   r   s    r   on_nextzCredentialsListener.on_next   s
    }r   callbackc                     || _         d S r   r   r   r   s     r   r   zCredentialsListener.on_next   s     r   c                     | j         S r   r   r   s    r   on_errorzCredentialsListener.on_error!   s
    ~r   c                     || _         d S r   r!   r   s     r   r"   zCredentialsListener.on_error%   s    !r   )__name__
__module____qualname____doc__r   propertyr	   r   r   r   r   setter	Exceptionr"    r   r   r   r      s2        
   xt4i?@    X ^!hud{&;Y&F G !D ! ! ! ^! %)d): ;Y FG    X _"xT0A'BI'M!N "SW " " " _" " "r   r   c                   6    e Zd ZdedefdZdefdZdefdZdS )RetryPolicymax_attemptsdelay_in_msc                 "    || _         || _        d S r   )r.   r/   )r   r.   r/   s      r   r   zRetryPolicy.__init__+   s    (&r   r   c                     | j         S )zW
        Retry attempts before exception will be thrown.

        :return: int
        )r.   r   s    r   get_max_attemptszRetryPolicy.get_max_attempts/   s       r   c                     | j         S )zI
        Delay between retries in seconds.

        :return: int
        )r/   r   s    r   get_delay_in_mszRetryPolicy.get_delay_in_ms7   s     r   N)r$   r%   r&   intfloatr   r2   r4   r+   r   r   r-   r-   *   sl        'S 'u ' ' ' '!# ! ! ! !             r   r-   c                   V    e Zd Z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S )TokenManagerConfigexpiration_refresh_ratiolower_refresh_bound_millis%token_request_execution_timeout_in_msretry_policyc                 >    || _         || _        || _        || _        d S r   )_expiration_refresh_ratio_lower_refresh_bound_millis&_token_request_execution_timeout_in_ms_retry_policy)r   r9   r:   r;   r<   s        r   r   zTokenManagerConfig.__init__A   s0     *B&+E(1 	3 *r   r   c                     | j         S )a&  
        Represents the ratio of a token's lifetime at which a refresh should be triggered. # noqa: E501
        For example, a value of 0.75 means the token should be refreshed
        when 75% of its lifetime has elapsed (or when 25% of its lifetime remains).

        :return: float
        )r>   r   s    r   get_expiration_refresh_ratioz/TokenManagerConfig.get_expiration_refresh_ratioO   s     --r   c                     | j         S )a  
        Represents the minimum time in milliseconds before token expiration
        to trigger a refresh, in milliseconds.
        This value sets a fixed lower bound for when a token refresh should occur,
        regardless of the token's total lifetime.
        If set to 0 there will be no lower bound and the refresh will be triggered
        based on the expirationRefreshRatio only.

        :return: int
        )r?   r   s    r   get_lower_refresh_bound_millisz1TokenManagerConfig.get_lower_refresh_bound_millisZ   s     //r   c                     | j         S )z
        Represents the maximum time in milliseconds to wait
        for a token request to complete.

        :return: int
        )r@   r   s    r   )get_token_request_execution_timeout_in_msz<TokenManagerConfig.get_token_request_execution_timeout_in_msg   s     ::r   c                     | j         S )z_
        Represents the retry policy for token requests.

        :return: RetryPolicy
        )rA   r   s    r   get_retry_policyz#TokenManagerConfig.get_retry_policyp   s     !!r   N)r$   r%   r&   r6   r5   r-   r   rC   rE   rG   rI   r+   r   r   r8   r8   @   s        *"'* %(* 03	*
 "* * * *	.e 	. 	. 	. 	.0 0 0 0 0;3 ; ; ; ;"+ " " " " " "r   r8   c                      e Zd ZdedefdZd Z	 ddedede	g d	f         fd
Z
	 	 	 ddedededede	g d	f         f
dZd ZddefdZddefdZdededefdZdefdZdedefdZ	 ddedej        fdZ	 ddedej        fdZd	S )TokenManageridentity_providerconfigc                 Z    || _         || _        d | _        d | _        d | _        d| _        d S )Nr   )_idp_config_next_timer	_listener_init_timer_retries)r   rL   rM   s      r   r   zTokenManager.__init__z   s4     &	r   c                 b    t                               d           |                                  d S )NzToken manager are disposed)loggerinfostopr   s    r   __del__zTokenManager.__del__   s&    0111		r   Flistenerskip_initialr   Nc                     || _         	 t          j                    }nT# t          $ rG t          j                    }t          j        t          |fd          }|                                 Y nw xY wt          j	                    }|
                    d| j        ||          | _        t                              d           t          j        |                                |                                           | j        S )NT)targetargsdaemonr   Token manager started)rR   asyncioget_running_loopRuntimeErrornew_event_loop	threadingThread_start_event_loop_in_threadstartEvent
call_later_renew_tokenrS   rV   rW   run_coroutine_threadsafewaitresultrX   )r   rZ   r[   loopthread
init_events         r   rh   zTokenManager.start   s    
 "	+--DD 	 	 	)++D%2$  F LLNNNNN	 ]__
??t ,

 
 	+,,, 	():):DAAHHJJJys    AA.-A.r   block_for_initialinitial_delay_in_msc                 D  K   || _         t          j                    }t          j                    }t	          || j        ||          }|                    |dz  |          | _        t          	                    d           |r|
                                 d {V  | j        S )N  r`   )rR   ra   rb   ri   _async_to_sync_wrapper_renew_token_asyncrj   rS   rV   rW   rm   rX   )r   rZ   rr   rs   r[   ro   rq   wrappeds           r   start_asynczTokenManager.start_async   s       "'))]__
 )$)<
 
  ??+>+EwOO+,,, 	$//#########yr   c                     | j         | j                                          | j        | j                                         d S d S r   )rS   cancelrQ   r   s    r   rX   zTokenManager.stop   sL    '##%%%'##%%%%% ('r   c                    	 | j                             |          }n# t          $ r}| j        | j                                                                        k     re| xj        dz  c_        t          | j                                                                        dz             | 	                    |          cY d }~S |d }~ww xY wd| _        t          |          S N   ru   r   )rO   request_tokenr
   rT   rP   rI   r2   r   r4   acquire_tokenr   r   force_refreshtokenes       r   r   zTokenManager.acquire_token   s    	I++M::EE 	 	 	}t|<<>>OOQQQQ"dl3355EEGG$NOOO))-88888888	 U###s!    
CBC:C CCc                   K   	 | j                             |          }n# t          $ r}| j        | j                                                                        k     rv| xj        dz  c_        t          j        | j                                        	                                dz             d {V  | 
                    |           d {V cY d }~S |d }~ww xY wd| _        t          |          S r}   )rO   r   r
   rT   rP   rI   r2   ra   r   r4   acquire_token_asyncr   r   s       r   r   z TokenManager.acquire_token_async   s     
	I++M::EE 	 	 	}t|<<>>OOQQQQ"mL1133CCEEL         "55mDDDDDDDDDDDDDD	 U###s!    
CB$CCCCexpire_date
issue_datec                     |                      |          }|                     ||          }t          ||          }|dk     rdn|dz  S )Nr   ru   )_delay_for_lower_refresh_delay_for_ratio_refreshmin)r   r   r   delay_for_lower_refreshdelay_for_ratio_refreshdelays         r   _calculate_renewal_delayz%TokenManager._calculate_renewal_delay   sS    "&"?"?"L"L"&"?"?Z"X"X+-DEEAIIqq54</r   c                     || j                                         z
  t          j        t          j                                                  dz  z
  S Nru   )rP   rE   r   nowr   utc	timestamp)r   r   s     r   r   z%TokenManager._delay_for_lower_refresh   sE    l99;;<|HL))3355<>	
r   c                     ||z
  }||| j                                         z  z
  }||z
  t          j        t          j                                                  dz  z
  S r   )rP   rC   r   r   r   r   r   )r   r   r   	token_ttlrefresh_befores        r   r   z%TokenManager._delay_for_ratio_refresh   sc    *,	"AACCC

 |HL))3355<>	
r   rq   c                 |   	 |                      d          }|                     |                                                                |                                                                          }|                                                                rt          d          | j        j        5t          
                    d           	 |r|                                 dS dS |sO	 | j                            |                                           n!# t          $ r}t          |          d}~ww xY w|dk    r	 |r|                                 dS dS t          j                    }|                    || j                  | _        t                              d| d           ||r|                                 S S # t          $ r2}| j        j        || j                            |           Y d}~nd}~ww xY w	 |r|                                 dS dS # |r|                                 w w xY w)	zq
        Task to renew token from identity provider.
        Schedules renewal tasks based on token TTL.
        Tr   Requested token is expiredN@No registered callback for token renewal task. Renewal cancelledr    Next token renewal scheduled in  seconds)r   r   	get_tokenget_expires_at_msget_received_at_ms
is_expiredr   rR   r   rV   warningsetr*   ra   rb   rj   rk   rQ   rW   r"   )r   r[   rq   	token_resr   r   ro   s          r   rk   zTokenManager._renew_token   s   $	!***>>I11##%%7799##%%88:: E
 ""$$//11 D%&BCCC~%-V   *  !     ! !'   --N**9+>+>+@+@AAAA  - - -)!,,,- zz  !     ! ! +--D#ud6GHHDKKJ5JJJKKK  !    !  	' 	' 	'~&.N##A&&&&&&&&		' ' !     ! !z !    !s[   CG ,G /,D G 
D:&D55D::	G AG 
H(G?:H" ?HH" "H;c                   K   	 |                      d           d{V }|                     |                                                                |                                                                          }|                                                                rt          d          | j        j        5t          
                    d           	 |r|                                 dS dS |sU	 | j                            |                                           d{V  n!# t          $ r}t          |          d}~ww xY w|dk    r	 |r|                                 dS dS t          j                    }t          || j                  }t                              d| d           |                    ||           nE# t          $ r8}| j        j        || j                            |           d{V  Y d}~nd}~ww xY w|r|                                 dS dS # |r|                                 w w xY w)	zx
        Async task to renew tokens from identity provider.
        Schedules renewal tasks based on token TTL.
        Tr   Nr   r   r   r   r   )r   r   r   r   r   r   r   rR   r   rV   r   r   r*   ra   rb   rv   rw   rW   rj   r"   )r   r[   rq   r   r   r   ro   rx   s           r   rw   zTokenManager._renew_token_async(  s     $	!"66T6JJJJJJJJI11##%%7799##%%88:: E
 ""$$//11 D%&BCCC~%-V   *  !     ! !'   --.001D1D1F1FGGGGGGGGGG  - - -)!,,,- zz  !     ! ! +--D,T43JKKGKKJ5JJJKKKOOE7++++ 	- 	- 	-~&..))!,,,,,,,,,,,,,,		-  !     ! !z !    !sa   CG	 4G	 72D* )G	 *
E4EE	G	 ,AG	 H( 	
H.HH( HH( (I)F)Fr   F)FN)r$   r%   r&   r   r8   r   rY   r   boolr   rh   r6   ry   rX   r   r   r   r   r   r   ra   ri   rk   rw   r+   r   r   rK   rK   y   s       !:DV      # %  
"d(		   > #(%&" %   #	
  
"d(	   0& & &$ $M $ $ $ $$ $ $ $ $ $ 0E 0u 0QV 0 0 0 0
E 
 
 
 


E 

u 

 

 

 

 GK,! ,! ,!6=m,! ,! ,! ,!^ GK,! ,! ,!6=m,! ,! ,! ,! ,! ,!r   rK   c                       fd}|S )a  
    Wraps an asynchronous function so it can be used with loop.call_later.

    :param loop: The event loop in which the coroutine will be executed.
    :param coro_func: The coroutine function to wrap.
    :param args: Positional arguments to pass to the coroutine function.
    :param kwargs: Keyword arguments to pass to the coroutine function.
    :return: A regular function suitable for loop.call_later.
    c                  @    t          j          i            d S )N)ro   )ra   ensure_future)r^   	coro_funckwargsro   s   r   rx   z'_async_to_sync_wrapper.<locals>.wrappedb  s.    ii888tDDDDDDr   r+   )ro   r   r^   r   rx   s   ```` r   rv   rv   W  s=    E E E E E E E E Nr   
event_loopc                 V    t          j        |            |                                  dS )z
    Starts event loop in a thread.
    Used to be able to schedule tasks using loop.call_later.

    :param event_loop:
    :return:
    N)ra   set_event_looprun_forever)r   s    r   rg   rg   i  s-     :&&&r   )ra   loggingre   r   r   timer   typingr   r   r   r	   redis.auth.errr
   r   redis.auth.idpr   redis.auth.tokenr   	getLoggerr$   rV   r   r-   r8   rK   rv   AbstractEventLooprg   r+   r   r   <module>r      s         ' ' ' ' ' ' ' '       2 2 2 2 2 2 2 2 2 2 2 2 ; ; ; ; ; ; ; ; 4 4 4 4 4 4 * * * * * *		8	$	$" " " " " " " "6               ,6" 6" 6" 6" 6" 6" 6" 6"r[! [! [! [! [! [! [! [!|  $	G,E 	 	 	 	 	 	r   