
    9j                        U 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	m
Z
mZmZmZmZmZ  ej        e          ZdZdZ ej                    Z ej                    Zdaded	<   d&dZd'dZd(dZe
ddd)dZd*d Zeee
dd!d+d"Z d,d-d%Z!dS ).z9Background keepalive for long-lived Nous Portal sessions.    )annotationsN)Optional)!ACCESS_TOKEN_REFRESH_SKEW_SECONDSNOUS_INVOKE_JWT_MIN_TTL_SECONDS	AuthError_agent_key_is_usable_is_expiringget_provider_auth_state resolve_nous_runtime_credentialsi`T  <   Optional[threading.Thread]_keepalive_threadvalueOptional[float]returnfloatc                    | t          |           S 	 t          t          j        dd                    S # t          t          f$ r Y dS w xY w)NHERMES_NOUS_TIMEOUT_SECONDS15g      .@)r   osgetenv	TypeError
ValueError)r   s    D/home/rurouni/.hermes/hermes-agent/hermes_cli/nous_auth_keepalive.py_timeout_secondsr      s[    U||RY<dCCDDDz"   tts   !5 A
	A
entryobjectdictc                h    t          | dd           t          | dd           t          | dd           dS )N	agent_keyagent_key_expires_atscope)r    r!   r"   )getattr)r   s    r   _entry_stater$   '   s?    UK66 '/Et L L..      min_key_ttl_secondsintOptional[bool]c                N   	 ddl m}  |d          }n3# t          $ r&}t                              d|           Y d}~dS d}~ww xY w|r|                                sdS 	 |                                }n3# t          $ r&}t                              d|           Y d}~dS d}~ww xY w|dS t          t          |dd          t                    }t          t          |          |           }|s|s4|                                }|dS t                              d	           d
S d
S )zRefresh the current Nous credential pool entry when it is stale.

    Returns True when a pool entry exists and is usable/refreshed, False when a
    pool exists but no entry can be used, and None when no Nous pool exists.
    r   )	load_poolnousz4Nous auth keepalive: credential pool unavailable: %sNz9Nous auth keepalive: credential pool selection failed: %sF
expires_atz4Nous auth keepalive: refreshed credential pool entryT)agent.credential_poolr*   	Exceptionloggerdebughas_credentialsselectr	   r#   r   r   r$   try_refresh_current)r&   r*   poolexcr   access_expiring
key_usable	refresheds           r   _refresh_selected_pool_entryr9   /   sr   333333y     KSQQQttttt  t++-- t   PRUVVVuuuuu }u"|T**) O &l5&9&9;NOOJ j ,,..	5KLLLt4s*    
A?A A5 5
B%?B  B%r&   timeout_secondsr;   boolc                   t          dt          |                     } t          |           }||S t          d          }|sdS 	 t	          t          |                     t                              d           dS # t          $ rI}|j	        rt          
                    d	|           nt                              d
|           Y d}~dS d}~wt          $ r&}t                              d
|           Y d}~dS d}~ww xY w)z5Refresh Nous auth once if credentials are configured.r   )r&   Nr+   F)r;   z3Nous auth keepalive: refreshed singleton auth stateTz)Nous auth keepalive requires re-login: %szNous auth keepalive failed: %s)maxr'   r9   r
   r   r   r/   r0   r   relogin_requiredinfor.   )r&   r;   pool_resultstater5   s        r    refresh_nous_auth_keepalive_oncerC   [   s:    b#&9":":;;./  K #F++E u(,_==	
 	
 	
 	
 	JKKKt    	@KKCSIIIILL93???uuuuu   5s;;;uuuuus$   7A? ?
D 	>CD C;;D 
stop_eventthreading.Eventinterval_secondsinitial_delay_secondsNonec                   |dk    r|                      |          rd S |                                 s<t          ||           |                      |           |                                 :d S d S )Nr   r:   )waitis_setrC   )rD   rF   rG   r&   r;   s        r   _keepalive_looprL   ~   s     q  Z__5J%K%K !! *( 3+	
 	
 	
 	
 	())) !! * * * * *r%   rF   rG   r&   r;   c                8   | dk    rdS t           5  t          ,t                                          rt          cddd           S t                                           t          j        t          t          ft          |           t          dt          |                    t          dt          |                    |ddd          at          
                                 t                              d           t          cddd           S # 1 swxY w Y   dS )	z2Start the process-wide Nous auth keepalive thread.r   Nr   rM   Tznous-auth-keepalive)targetargskwargsdaemonnamezNous auth keepalive started)_keepalive_lockr   is_alive_keepalive_stopclear	threadingThreadrL   r'   r>   startr/   r0   rM   s       r   start_nous_auth_keepaliver[      so    1t 
 ! !(->-G-G-I-I($! ! ! ! ! ! ! ! 	%,"!#$'(8$9$9),Q4I0J0J)K)K'*2s3F/G/G'H'H#2	  &
 
 
 	!!!2333 '! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !s   'DB>DDD      @timeoutc                2   t           5  t          }t                                           ddd           n# 1 swxY w Y   |*|                                r|                    |            t           5  t          |u rdaddd           dS # 1 swxY w Y   dS )z@Stop the keepalive thread. Intended for graceful shutdown/tests.N)r]   )rT   r   rV   setrU   join)r]   threads     r   stop_nous_auth_keepaliverb      s    
  "               foo//G$$$	 % %&& $% % % % % % % % % % % % % % % % % %s   !5993BBB)r   r   r   r   )r   r   r   r   )r&   r'   r   r(   )r&   r'   r;   r   r   r<   )rD   rE   rF   r'   rG   r'   r&   r'   r;   r   r   rH   )
rF   r'   rG   r'   r&   r'   r;   r   r   r   )r\   )r]   r   r   rH   )"__doc__
__future__r   loggingr   rX   typingr   hermes_cli.authr   r   r   r   r	   r
   r   	getLogger__name__r/   $NOUS_AUTH_KEEPALIVE_INTERVAL_SECONDS)NOUS_AUTH_KEEPALIVE_INITIAL_DELAY_SECONDSLockrT   EventrV   r   __annotations__r   r$   r9   rC   rL   r[   rb    r%   r   <module>rp      s   ? ? ? " " " " " "  				                            
	8	$	$'2 $,. ) ).""!)/##04  4 4 4 4      ) ) ) )\  ?'+           F* * * ** A!J>'+! ! ! ! ! !D
% 
% 
% 
% 
% 
% 
%r%   