
    Mh~                       d Z ddlm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
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d	lmZ dd
lmZ ddlmZmZmZ ddlmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z,m-Z- dZ.dZ/dZ0dZ1dZ2ej3        rddlm4Z4  G d de e5e)                    Z6 G d de
e)e6          Z7 G d de7          Z8 G d de*          Z9 G d d          Z:d'd&Z;dS )(zA kernel gateway client.    )annotationsN)ABCABCMetaabstractmethod)datetimetimezone)parsedate_to_datetime)SimpleCookie)gaierror)EventLogger)web)AsyncHTTPClientHTTPClientErrorHTTPResponse)
BoolFloatInstanceInt
TraitErrorTypeUnicodedefaultobservevalidate)LoggingConfigurableSingletonConfigurable)DEFAULT_EVENTS_SCHEMA_PATHJUPYTER_SERVER_EVENTS_URIerrorsuccessstatusstatus_codemsg)Morselc                      e Zd ZdZdS )GatewayTokenRenewerMetazBThe metaclass necessary for proper ABC behavior in a Configurable.N)__name__
__module____qualname____doc__     e/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/jupyter_server/gateway/gateway_client.pyr&   r&   /   s        LLLLr,   r&   c                  *    e Zd ZdZedd
            ZdS )GatewayTokenRenewerBasea<  
    Abstract base class for refreshing tokens used between this server and a Gateway
    server.  Implementations requiring additional configuration can extend their class
    with appropriate configuration values or convey those values via appropriate
    environment variables relative to the implementation.
    auth_header_keystrauth_schemety.Union[str, None]
auth_tokenkwargsty.Anyreturnc                    dS )z
        Given the current authorization header key, scheme, and token, this method returns
        a (potentially renewed) token for use against the Gateway server.
        Nr+   selfr0   r2   r4   r5   s        r-   	get_tokenz!GatewayTokenRenewerBase.get_token=   s      r,   N
r0   r1   r2   r3   r4   r1   r5   r6   r7   r1   )r'   r(   r)   r*   r   r;   r+   r,   r-   r/   r/   3   s>          
 
 
 ^
 
 
r,   r/   )	metaclassc                      e Zd ZdZdd
ZdS )NoOpTokenRenewerzNoOpTokenRenewer is the default value to the GatewayClient trait
    `gateway_token_renewer` and merely returns the provided token.
    r0   r1   r2   r3   r4   r5   r6   r7   c                    |S )zCThis implementation simply returns the current authorization token.r+   r9   s        r-   r;   zNoOpTokenRenewer.get_tokenP   s
     r,   Nr<   )r'   r(   r)   r*   r;   r+   r,   r-   r?   r?   K   s2              r,   r?   c                      e Zd ZU dZedz   Z ee                              d          Z	 e
d          d             Zd Z edddd	
          ZdZ e
d          d             Z ed          d             Z edddd
          ZdZ e
d          d             Z ed          d             ZdZdZ eedd          Z e
d          d             ZdZdZ eedd          Z e
d          d             ZdZd Z  eedd!          Z! e
d"          d#             Z"d$Z#d%Z$ e%e#dd&          Z& e
d'          d(             Z'd)Z(d*Z) e%e(dd+          Z* e
d,          d-             Z+ edddd.
          Z,d/Z- e
d0          d1             Z. edddd2
          Z/d3Z0 e
d4          d5             Z1 edddd6
          Z2d7Z3 e
d8          d9             Z4 edddd:
          Z5d;Z6 e
d<          d=             Z7 edddd>
          Z8d?Z9 e
d@          dA             Z:dBZ;dCZ< ee;dddD
          Z= e
dE          dF             Z>dGZ? eddHI          Z@dJZA e
dK          dL             ZBdMZC eddddN
          ZDdOZE e
dP          dQ             ZFdRZG edddST          ZHdUZI e
dV          dW             ZJdZKdXZL eMeKddY          ZN e
dZ          d[             ZOdMZPd\ZQ eePdd]          ZR e
d^          d_             ZS eePdd`          ZTdaZUdbZV e%eUddc          ZW e
dd          de             ZXdfZYdgZZ e%eYddh          Z[ e
di          dj             Z\dkZ]dlZ^ e_e]ddm          Z` e
dn          do             ZadpZbdqZc edeeddrs          Zf e
dt          du             ZgdvZhdwZi e%ehddx          Zj e
dy          dz             Zkd{Zld|Zm eMeldd}          Zn e
d~          d             ZoddiZp eq erep           d             Zsetd             Zu evewjx        y                    dd                    Zzde{d<   de{d<    fdZ|d Z}d Z~ddZddZddZ xZS )GatewayClientzThis class manages the configuration.  It's its own singleton class so
    that we can share these values across all objects.  It also contains some
    options.
    helper methods to build request arguments out of the various config
    z/gateway_client/v1T)configevent_loggerc                    | j         r!t          | j         d          r| j         j        S t                      }t          dz  dz  }|                    |           | j                            d           |S )NrD   gateway_clientzv1.yamlz%Event is registered in GatewayClient.)parenthasattrrD   r   r   register_event_schemaloginfo)r:   loggerschema_paths      r-   _default_event_loggerz#GatewayClient._default_event_loggere   ss    ; 		74;?? 		;++ !]]F47GG)SK((555HMMABBBMr,   c                H    | j                             | j        |           dS )zLEmit event using the core event schema from Jupyter Server's Gateway Client.)	schema_iddataN)rD   emitevent_schema_id)r:   rQ   s     r-   rR   zGatewayClient.emitr   s'    )=DIIIIIr,   Na  The url of the Kernel or Enterprise Gateway server where
kernel specifications are defined and kernel management takes place.
If defined, this Notebook server acts as a proxy for all kernel
management and kernel specification retrieval.  (JUPYTER_GATEWAY_URL env var)
        )default_value
allow_nonerC   helpJUPYTER_GATEWAY_URLurlc                J    t           j                            | j                  S N)osenvirongeturl_envr:   s    r-   _url_defaultzGatewayClient._url_default   s    z~~dl+++r,   c                0   |d         }|t          |          dk    rxt          |                                                              d          sDd|z  }|                     t
          t          t          dt          |i           t          |          |S )Nvaluer   httpz.GatewayClient url must start with 'http': '%r'  rQ   
lenr1   lower
startswithrR   
STATUS_KEYERROR_STATUSSTATUS_CODE_KEYMESSAGE_KEYr   r:   proposalrb   messages       r-   _url_validatezGatewayClient._url_validate   s    !UaE

8H8H8J8J8U8UV\8]8]FNGIIJosKY`aIbbbW%%%r,   zThe websocket url of the Kernel or Enterprise Gateway server.  If not provided, this value
will correspond to the value of the Gateway url with 'ws' in place of 'http'.  (JUPYTER_GATEWAY_WS_URL env var)
        JUPYTER_GATEWAY_WS_URLws_urlc                    t           j                            | j                  }| j        6|4| j        r-| j                                                            dd          }|S )Nrc   ws)r[   r\   r]   
ws_url_envrX   gateway_enabledrh   replace)r:   rT   s     r-   _ws_url_defaultzGatewayClient._ws_url_default   sS    
t778M$9d>R$9 HNN,,44VTBBMr,   c                0   |d         }|t          |          dk    rxt          |                                                              d          sDd|z  }|                     t
          t          t          dt          |i           t          |          |S )Nrb   r   ru   z/GatewayClient ws_url must start with 'ws': '%r'rd   re   rf   rn   s       r-   _ws_url_validatezGatewayClient._ws_url_validate   s    !UaE

8H8H8J8J8U8UVZ8[8[G%OGIIJosKY`aIbbbW%%%r,   z/api/kernels JUPYTER_GATEWAY_KERNELS_ENDPOINTzbThe gateway API endpoint for accessing kernel resources (JUPYTER_GATEWAY_KERNELS_ENDPOINT env var))rT   rC   rV   kernels_endpointc                V    t           j                            | j        | j                  S rZ   )r[   r\   r]   kernels_endpoint_envkernels_endpoint_default_valuer_   s    r-   _kernels_endpoint_defaultz'GatewayClient._kernels_endpoint_default   s    z~~d79\]]]r,   z/api/kernelspecs$JUPYTER_GATEWAY_KERNELSPECS_ENDPOINTzaThe gateway API endpoint for accessing kernelspecs (JUPYTER_GATEWAY_KERNELSPECS_ENDPOINT env var)kernelspecs_endpointc                V    t           j                            | j        | j                  S rZ   )r[   r\   r]   kernelspecs_endpoint_env"kernelspecs_endpoint_default_valuer_   s    r-   _kernelspecs_endpoint_defaultz+GatewayClient._kernelspecs_endpoint_default   s%    z~~)4+R
 
 	
r,   z/kernelspecs-JUPYTER_GATEWAY_KERNELSPECS_RESOURCE_ENDPOINTzpThe gateway endpoint for accessing kernelspecs resources
(JUPYTER_GATEWAY_KERNELSPECS_RESOURCE_ENDPOINT env var)kernelspecs_resource_endpointc                V    t           j                            | j        | j                  S rZ   )r[   r\   r]   !kernelspecs_resource_endpoint_env+kernelspecs_resource_endpoint_default_valuer_   s    r-   &_kernelspecs_resource_endpoint_defaultz4GatewayClient._kernelspecs_resource_endpoint_default   s&    z~~2<
 
 	
r,   g      D@JUPYTER_GATEWAY_CONNECT_TIMEOUTzuThe time allowed for HTTP connection establishment with the Gateway server.
(JUPYTER_GATEWAY_CONNECT_TIMEOUT env var)connect_timeoutc                p    t          t          j                            | j        | j                            S rZ   )floatr[   r\   r]   connect_timeout_envconnect_timeout_default_valuer_   s    r-   _connect_timeout_defaultz&GatewayClient._connect_timeout_default   &    RZ^^D$<d>`aabbbr,   g      E@JUPYTER_GATEWAY_REQUEST_TIMEOUTzWThe time allowed for HTTP request completion. (JUPYTER_GATEWAY_REQUEST_TIMEOUT env var)request_timeoutc                p    t          t          j                            | j        | j                            S rZ   )r   r[   r\   r]   request_timeout_envrequest_timeout_default_valuer_   s    r-   _request_timeout_defaultz&GatewayClient._request_timeout_default   r   r,   zWThe filename for client SSL key, if any.  (JUPYTER_GATEWAY_CLIENT_KEY env var)
        JUPYTER_GATEWAY_CLIENT_KEY
client_keyc                J    t           j                            | j                  S rZ   )r[   r\   r]   client_key_envr_   s    r-   _client_key_defaultz!GatewayClient._client_key_default   s    z~~d1222r,   z`The filename for client SSL certificate, if any.  (JUPYTER_GATEWAY_CLIENT_CERT env var)
        JUPYTER_GATEWAY_CLIENT_CERTclient_certc                J    t           j                            | j                  S rZ   )r[   r\   r]   client_cert_envr_   s    r-   _client_cert_defaultz"GatewayClient._client_cert_default  s    z~~d2333r,   zeThe filename of CA certificates or None to use defaults.  (JUPYTER_GATEWAY_CA_CERTS env var)
        JUPYTER_GATEWAY_CA_CERTSca_certsc                J    t           j                            | j                  S rZ   )r[   r\   r]   ca_certs_envr_   s    r-   _ca_certs_defaultzGatewayClient._ca_certs_default      z~~d/000r,   zRThe username for HTTP authentication. (JUPYTER_GATEWAY_HTTP_USER env var)
        JUPYTER_GATEWAY_HTTP_USER	http_userc                J    t           j                            | j                  S rZ   )r[   r\   r]   http_user_envr_   s    r-   _http_user_defaultz GatewayClient._http_user_default   s    z~~d0111r,   zRThe password for HTTP authentication.  (JUPYTER_GATEWAY_HTTP_PWD env var)
        JUPYTER_GATEWAY_HTTP_PWDhttp_pwdc                J    t           j                            | j                  S rZ   )r[   r\   r]   http_pwd_envr_   s    r-   _http_pwd_defaultzGatewayClient._http_pwd_default-  r   r,   z{}JUPYTER_GATEWAY_HEADERSzAdditional HTTP headers to pass on the request.  This value will be converted to a dict.
          (JUPYTER_GATEWAY_HEADERS env var)
        headersc                V    t           j                            | j        | j                  S rZ   )r[   r\   r]   headers_envheaders_default_valuer_   s    r-   _headers_defaultzGatewayClient._headers_default<  s    z~~d.0JKKKr,   Authorizationaz  The authorization header's key name (typically 'Authorization') used in the HTTP headers. The
header will be formatted as::

{'{auth_header_key}': '{auth_scheme} {auth_token}'}

If the authorization header key takes a single value, `auth_scheme` should be set to None and
'auth_token' should be configured to use the appropriate value.

(JUPYTER_GATEWAY_AUTH_HEADER_KEY env var))rC   rV   JUPYTER_GATEWAY_AUTH_HEADER_KEYr0   c                V    t           j                            | j        | j                  S rZ   )r[   r\   r]   auth_header_key_envauth_header_key_default_valuer_   s    r-   _auth_header_key_defaultz&GatewayClient._auth_header_key_defaultO  s    z~~d68Z[[[r,    zThe authorization token used in the HTTP headers. The header will be formatted as::

{'{auth_header_key}': '{auth_scheme} {auth_token}'}

(JUPYTER_GATEWAY_AUTH_TOKEN env var)JUPYTER_GATEWAY_AUTH_TOKENr4   c                V    t           j                            | j        | j                  S rZ   )r[   r\   r]   auth_token_envauth_token_default_valuer_   s    r-   _auth_token_defaultz!GatewayClient._auth_token_default`  s    z~~d143PQQQr,   tokenz}The auth scheme, added as a prefix to the authorization token used in the HTTP headers.
(JUPYTER_GATEWAY_AUTH_SCHEME env var))rU   rC   rV   JUPYTER_GATEWAY_AUTH_SCHEMEr2   c                V    t           j                            | j        | j                  S rZ   )r[   r\   r]   auth_scheme_envauth_scheme_default_valuer_   s    r-   _auth_scheme_defaultz"GatewayClient._auth_scheme_defaultm  s    z~~d2D4RSSSr,   JUPYTER_GATEWAY_VALIDATE_CERTzzFor HTTPS requests, determines if server's certificate should be validated or not.
(JUPYTER_GATEWAY_VALIDATE_CERT env var)validate_certc                    t          t          j                            | j        t          | j                            dv          S N)nofalse)boolr[   r\   r]   validate_cert_envr1   validate_cert_default_valuer_   s    r-   _validate_cert_defaultz$GatewayClient._validate_cert_defaultz  s=    JNN413t7W3X3XYY"#
 
 	
r,   JUPYTER_GATEWAY_ALLOWED_ENVSam  A comma-separated list of environment variable names that will be included, along with
their values, in the kernel startup request.  The corresponding `client_envs` configuration
value must also be set on the Gateway server - since that configuration value indicates which
environmental values to make available to the kernel. (JUPYTER_GATEWAY_ALLOWED_ENVS env var)allowed_envsc                    t           j                            | j        t           j                            d| j                            S )NJUPYTER_GATEWAY_ENV_WHITELIST)r[   r\   r]   allowed_envs_envallowed_envs_default_valuer_   s    r-   _allowed_envs_defaultz#GatewayClient._allowed_envs_default  s7    z~~!JNN:D<[\\
 
 	
r,   z,Deprecated, use `GatewayClient.allowed_envs`g      ?JUPYTER_GATEWAY_RETRY_INTERVALa  The time allowed for HTTP reconnection with the Gateway server for the first time.
Next will be JUPYTER_GATEWAY_RETRY_INTERVAL multiplied by two in factor of numbers of retries
but less than JUPYTER_GATEWAY_RETRY_INTERVAL_MAX.
(JUPYTER_GATEWAY_RETRY_INTERVAL env var)gateway_retry_intervalc                p    t          t          j                            | j        | j                            S rZ   )r   r[   r\   r]   gateway_retry_interval_env$gateway_retry_interval_default_valuer_   s    r-   _gateway_retry_interval_defaultz-GatewayClient._gateway_retry_interval_default  s3    JNN/9 
 
 	
r,   g      >@"JUPYTER_GATEWAY_RETRY_INTERVAL_MAXzzThe maximum time allowed for HTTP reconnection retry with the Gateway server.
(JUPYTER_GATEWAY_RETRY_INTERVAL_MAX env var)gateway_retry_interval_maxc                p    t          t          j                            | j        | j                            S rZ   )r   r[   r\   r]   gateway_retry_interval_max_env(gateway_retry_interval_max_default_valuer_   s    r-   #_gateway_retry_interval_max_defaultz1GatewayClient._gateway_retry_interval_max_default  s3    JNN3= 
 
 	
r,      JUPYTER_GATEWAY_RETRY_MAXznThe maximum retries allowed for HTTP reconnection with the Gateway server.
(JUPYTER_GATEWAY_RETRY_MAX env var)gateway_retry_maxc                p    t          t          j                            | j        | j                            S rZ   )intr[   r\   r]   gateway_retry_max_envgateway_retry_max_default_valuer_   s    r-   _gateway_retry_max_defaultz(GatewayClient._gateway_retry_max_default  s&    2:>>$"<d>bccdddr,   z6jupyter_server.gateway.gateway_client.NoOpTokenRenewer#JUPYTER_GATEWAY_TOKEN_RENEWER_CLASSzYThe class to use for Gateway token renewal. (JUPYTER_GATEWAY_TOKEN_RENEWER_CLASS env var))klassrC   rV   gateway_token_renewer_classc                V    t           j                            | j        | j                  S rZ   )r[   r\   r]   gateway_token_renewer_class_env)gateway_token_renewer_class_default_valuer_   s    r-   $_gateway_token_renewer_class_defaultz2GatewayClient._gateway_token_renewer_class_default  s%    z~~0$2`
 
 	
r,   g       @"JUPYTER_GATEWAY_LAUNCH_TIMEOUT_PADzTimeout pad to be ensured between KERNEL_LAUNCH_TIMEOUT and request_timeout
such that request_timeout >= KERNEL_LAUNCH_TIMEOUT + launch_timeout_pad.
(JUPYTER_GATEWAY_LAUNCH_TIMEOUT_PAD env var)launch_timeout_padc                p    t          t          j                            | j        | j                            S rZ   )r   r[   r\   r]   launch_timeout_pad_env launch_timeout_pad_default_valuer_   s    r-   _launch_timeout_pad_defaultz)GatewayClient._launch_timeout_pad_default  s3    JNN+5 
 
 	
r,   FJUPYTER_GATEWAY_ACCEPT_COOKIESzAccept and manage cookies sent by the service side. This is often useful
        for load balancers to decide which backend node to use.
        (JUPYTER_GATEWAY_ACCEPT_COOKIES env var)accept_cookiesc                    t          t          j                            | j        t          | j                                                            dv          S r   )r   r[   r\   r]   accept_cookies_envr1   accept_cookies_valuerh   r_   s    r-   _accept_cookies_defaultz%GatewayClient._accept_cookies_default  sI    JNN42C8Q4R4R4X4X4Z4Z[["#
 
 	
r,   env_whitelist)r   z2.0c                   |j         }| j        |         \  }}t          | |          }||j        k    rU| j                            | j        j         d| d| d| j        j         d| d
           t          | ||j                   dS dS )zobserver for deprecated traits.z! is deprecated in jupyter_server z, use z insteadN)	name_deprecated_traitsgetattrnewrJ   warning	__class__r'   setattr)r:   changeold_attrnew_attrversion	new_values         r-   _deprecated_traitzGatewayClient._deprecated_trait  s     ; 3H='D(++	
"" H>* O OX O OO O"&."9O O<DO O O   D(FJ///// #"r,   c                ^    t          | j        d uot          | j                  dk              S )Nr   )r   rX   rg   r_   s    r-   rw   zGatewayClient.gateway_enabled  s)    DHD(>S]]Q->???r,   KERNEL_LAUNCH_TIMEOUT(   dict[str, ty.Any]_connection_argsr/   gateway_token_renewerc                     t                      j        di | i | _        |                     | | j                  | _        i | _        dS )zInitialize a gateway client.)rG   rJ   Nr+   )super__init__r  r   rJ   r  _cookies)r:   r5   r  s     r-   r  zGatewayClient.__init__!  sV    ""6""" "%)%E%ETW[W_%E%`%`" EGr,   c                .   t          t          j                  | j        z   }| j        |k     r|| _        n1| j        |k    r&t          | j        | j        z
            t          _        t          t          j                  t          j        d<   | j	        rlt          j        | j	                  | j        d<   | j        | j        d         vr7| j        d                             | j         | j         d| j         i           | j        | j        d<   | j        | j        d<   | j        | j        d<   | j        r4| j        | j        d<   | j        | j        d<   | j        r| j        | j        d	<   | j        r| j        | j        d
<   | j        r| j        | j        d<   dS dS )zInitialize arguments used on every request.  Since these are primarily static values,
        we'll perform this operation once.
        r  r    r   r   r   r   r   r   auth_usernameauth_passwordN)r   rB   r  r   r   r   r1   r[   r\   r   jsonloadsr  r0   updater2   r4   r   r   r   r   r   r   r   )r:   minimum_request_timeouts     r-   init_connection_argsz"GatewayClient.init_connection_args*  s    -5669PP 	  "999#:D  !$;;;25$t'>>3 3M/ /2-2U.V.V
*+< 	/3z$,/G/GD!),#4+@+KKK%i077,.43C0W0Wdo0W0WX   483G/0373G/0151Co. 	B373CD!-026/D!,/} B48M%j1> 	D59^D!/2= 	C59]D!/222	C 	Cr,   c                   t          | j                  dk    r|                                  | j        }| j        u	 | j                            | j        | j        | j                  | _        nC# t          $ r6}| j	        
                    d| j         d|            || _        Y d}~nd}~ww xY w| j                                        D ]}\  }}|dk    rm|                    |i           }t          |t                    rA|                    |           |                    | j         | j         d| j         i           x|||<   ~| j        r|                     |           |S )zMerges the static args relative to the connection, with the given keyword arguments.  If static
        args have yet to be initialized, we'll do that here.

        r   NzfAn exception occurred attempting to renew the Gateway authorization token using an instance of class 'zL'.  The request will proceed using the current token value.  Exception was: r   r!  )rg   r  r(  r4   r  r;   r0   r2   	ExceptionrJ   r   r   items
setdefault
isinstancedictr&  r  _update_cookie_header)r:   r5   prev_auth_tokenexargrb   given_values          r-   load_connection_argsz"GatewayClient.load_connection_argsP  s   
 t$%%**%%''' /?&2"&"<"F"F($*:DO# #  2 2 2S8S S OQS S   #22 /5577 
	$ 
	$JCi$//R88k400 &&u---&& 02t7G4[4[$/4[4[\   $s 	/&&v...s   0A- -
B-7,B((B-cookier
   r7   Nonec                n   | j         sdS t          j        t          j                  }|                                D ]w\  }}|                    d          rQ|                    d          s<t          |d                   |z
  }t          |	                                          |d<   ||f| j
        |<   xdS )z8Update cookies from existing requests for load balancersNtzexpiresmax-age)r  r   nowr   utcr+  r]   r	   r1   total_secondsr  )r:   r5  
store_timekeyitemexpire_timedeltas         r-   update_cookieszGatewayClient.update_cookiesy  s    " 	F\X\222
 	4 	4IC xx	"" H488I+>+> H#8i#I#IJ#V "%&6&D&D&F&F"G"GY"&
!3DM#	4 	4r,   c                x   t          j        t          j                  }g }| j                                        D ]_\  }\  }}|                    d          }|s ||z
  }|                                t          |          k    r|	                    |           `|D ]}| j        
                    |           dS )zClear expired cookies.r8  r;  N)r   r<  r   r=  r  r+  r]   r>  r   appendpop)r:   
check_timeexpired_keysr@  morselr?  cookie_max_ageexpired_timedeltas           r-   _clear_expired_cookiesz$GatewayClient._clear_expired_cookies  s    \X\222
)-)<)<)>)> 	) 	)%C%&*#ZZ	22N!  *Z 7 ..0053H3HHH##C((( 	# 	#CMc""""	# 	#r,   connection_argsc                T   |                                   d                    d | j                                        D                       }|r[|                    di           }t          d |D             d          }|                    |          }|r|dz   |z   }|||<   ||d<   dS dS )zUpdate a cookie header.z; c              3  :   K   | ]\  }\  }}| d |j          V  dS )=N)coded_value).0r	  rI  _times       r-   	<genexpr>z6GatewayClient._update_cookie_header.<locals>.<genexpr>  sL       *
 *
/Dt_fet**f(***
 *
 *
 *
 *
 *
r,   r   c              3  J   K   | ]}|                                 d k    |V  dS )r5  N)rh   )rR  
header_keys     r-   rT  z6GatewayClient._update_cookie_header.<locals>.<genexpr>  s8      XX
9I9I9K9Kx9W9W9W9W9W9WXXr,   CookieN)rL  joinr  r+  r]   next)r:   rM  gateway_cookie_valuesr   cookie_header_nameexisting_cookies         r-   r/  z#GatewayClient._update_cookie_header  s    ##%%% $		 *
 *
HLH[H[H]H]*
 *
 *
 !
 !
 ! 	1%)))R88G "&XXgXXX" " &kk*<==O  W(7$(>AV(V%*?G&')0OI&&&!	1 	1r,   )r5  r
   r7   r6  )r7   r6  )rM  r  r7   r6  )r'   r(   r)   r*   r   rS   r   r   tagrD   r   rN   rR   r   rX   r^   r`   r   rq   rs   rv   ry   r{   r   r   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r0   r   r   r   r4   r   r   r   r2   r   r   r   r   r   r   r   r   r   r   r   r  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r/   r   r   r   r   r   r   r  r  r  r  r
  r   listr  propertyrw   r   r[   r\   r]   r  __annotations__r  r(  r4  rC  rL  r/  __classcell__)r  s   @r-   rB   rB   [   s
          02FFO8K((,,D,99LW^
 
 
J J J '		 	 	C $GWU^^, , ^, Xe__  _ W	  F *JWX   Xh   &4"=w4u   W  ^ ^ ! ^ *<&E"78t   W#$$
 
 %$

 3A/(W%$+GA;% % %! W,--
 
 .-
 %)!;e3-  O Wc c  c %)!;e3j  O Wc c  c 	  J 2NW\3 3 3 '	  K 4OW]4 4 4 w	  H .LWZ1 1 1 	  I 0MW[2 2 2 w	  H .LWZ1 1 1 !+Kg+	  G WYL L L %4!g-  O <W\ \  \  "(		 	 	J 2NW\R R R !(')  K 4OW]T T T #'7D1+  M W_
 
 
 "$570`  L W^
 
 
 G0?  M ,/(!A"U:,   W%&&
 
 '&
 04,%I"!&>0" " " W)**
 
 +*
 '(#75'   W !!e e "!e 	A . 'L#"&$%l# # # W*++
 
 ,+

 (+$A60   W!""
 
 #"
 !9T*4  N W
 
 
 	0 Wdd%&&'0 0 ('0 @ @ X@  C
/F K KLL''''2222G G G G G$C $C $CL' ' 'R4 4 4 4# # # # 1 1 1 1 1 1 1 1r,   rB   c                      e Zd ZU dZdZdZ e ej        de                    Z	de
d<    ed ee	e                    Z	dd	hZd
e
d<   h dZde
d<   ehZde
d<   dZde
d<   d Zd#dZd#dZd$d!Zd"S )%RetryableHTTPClientaH  
    Inspired by urllib.util.Retry (https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html),
    this class is initialized with desired retry characteristics, uses a recursive method `fetch()` against an instance
    of `AsyncHTTPClient` which tracks the current retry count across applicable request retries.
       
   #JUPYTER_GATEWAY_MAX_REQUEST_RETRIESr   max_retriesr   GETDELETEzset[str]retried_methods>   W        zset[int]retried_errorsz	set[type]retried_exceptionsg?r   backoff_factorc                :    d| _         t                      | _        dS )z%Initialize the retryable http client.r   N)retry_countr   clientr_   s    r-   r  zRetryableHTTPClient.__init__  s     !'6'8'8r,   endpointr1   r5   r6   r7   r   c                <   K   d| _          | j        |fi | d{V S )z
        Retryable AsyncHTTPClient.fetch() method.  When the request fails, this method will
        recurse up to max_retries times if the condition deserves a retry.
        r   N)rs  _fetch)r:   ru  r5   s      r-   fetchzRetryableHTTPClient.fetch  s<      
  T[44V444444444r,   c           
     N  K   	  | j         j        |fi | d{V }n# t          $ rz}|                     |d         |           d{V }|s|t	          j        d                              d| j         d| d|d            | j        |fi | d{V }Y d}~nd}~ww xY w|S )z
        Performs the fetch against the contained AsyncHTTPClient instance and determines
        if retry is necessary on any exceptions.  If so, retry is performed recursively.
        Nmethod	ServerAppzAttempting retry (z) against endpoint 'z'.  Retried error: '')	rt  rx  r*  _is_retryablelogging	getLoggerrK   rs  rw  )r:   ru  r5   responseeis_retryables         r-   rw  zRetryableHTTPClient._fetch  s/     

	=+<4;+<X+P+P+P+P%P%P%P%P%P%PHH 	= 	= 	='+'9'9&:JA'N'N!N!N!N!N!N!NL k**//BT%5 B B%B B;<B B B   )T[<<V<<<<<<<<HHHHHH	= s    
B"A0BB"rz  	exceptionr*  r   c                N  K   || j         vrdS | j        | j        k    rdS t          t                    r}|j        | j        vrdS n"t          fd| j        D                       sdS t          j
        | j        d| j        z  z             d{V  | xj        dz  c_        dS )zODetermines if the given exception is retryable based on object's configuration.Fc              3  8   K   | ]}t          |          V  d S rZ   )r-  )rR  r   r  s     r-   rT  z4RetryableHTTPClient._is_retryable.<locals>.<genexpr>  s-      WWeZ	511WWWWWWr,   rd  N   T)rj  rs  rg  r-  r   codero  anyrp  asynciosleeprq  )r:   rz  r  hces     ` r-   r}  z!RetryableHTTPClient._is_retryable  s       ---5t///5 i11 	#,Cxt222u 3WWWWt?VWWWWW 	5 mD/1d6F3FGHHHHHHHHHAtr,   Nru  r1   r5   r6   r7   r   )rz  r1   r  r*  r7   r   )r'   r(   r)   r*   MAX_RETRIES_DEFAULTMAX_RETRIES_CAPr   r[   getenvrg  r`  maxminrj  ro  ConnectionErrorrp  rq  r  rx  rw  r}  r+   r,   r-   rc  rc    s          Os929%JL_``aaKaaaa#a[/::;;K!& 1O1111333N3333%4$55555N9 9 9
5 5 5 5   $     r,   rc  ru  r1   r5   r6   r7   r   c                  K   t                                           } |j        di |}t                      }	  |j        | fi | d{V }|                    t          t          t          dt          di           ng# t          $ r}|                    t          t          t          |j        t          t          |j                  i           d|j         d}|j        }|j        r	 t#          j        |j        j                  }|                    d          p|}|                    d          p|}n8# t"          j        j        $ r! |j        j                                        }Y nw xY wt1          j        |j        d	| d
| d          |d}~wt4          $ ra}|                    t          t          t          dt          t          |          i           t1          j        dd|j         d          |d}~wt6          $ ra}|                    t          t          t          dt          t          |          i           t1          j        dd|j         d          |d}~wt8          $ rr}|                    t          t          t          dt          t          |          i           t;          j        d                              d|j        |           |d}~ww xY w|j         rT|j!                            d          }	|	r8tE                      }
|
#                    |	           |$                    |
           |S )zDMake an async request to kernel gateway endpoint, returns a responseN   r    re   z=Exception while attempting to connect to Gateway server url 'r|  reasonrp   zError from Gateway: [z] zB. Ensure gateway url is valid and the Gateway instance is running.rn  z6ConnectionError was received from Gateway server url 'z5'.  Check to be sure the Gateway instance is running.i  z1The Gateway server specified in the gateway_url 'z_' doesn't appear to be valid.  Ensure gateway url is valid and the Gateway instance is running.i  r{  z>Exception while trying to launch kernel via Gateway URL %s: %sz
Set-Cookier+   )%rB   instancer4  rc  rx  rR   rj   SUCCESS_STATUSrl   rm   r   rk   r  r1   rp   rX   r  r$  r%  bodyr]   decoderJSONDecodeErrordecoder   	HTTPErrorr  r   r*  r~  r  r   r  r   r
   loadrC  )ru  r5   rF   rhcr  r  error_reasonerror_messageerror_payloadcookie_valuesr5  s              r-   gateway_requestr    s     "++--N0^0::6::F


C9"866v66666666nosKQZ[ 	 	
 	
 	
 	
    lOQV[RUVWV_R`R`a 	 	
 	
 	
 bNL^aaa 	 	: 	88 $
1:? ; ;,00::Jl - 1 1) < < M</ 8 8 8 z55778 mFOM O O\ O O O
 
 		
    lOS+sSTvvV 	 	
 	
 	
 m@^EW @ @ @
 
 		
    lOS+sSTvvV 	 	
 	
 	
 me@R e e e
 
 		
  	 	 	lOS+sSTvvV 	 	
 	
 	
 	+&&,,L	
 	
 	

 	 $ 2 (,,\:: 	2#/>>FKK&&&))&111Ose   AA> >K"	A F*AD76F72E,)F+E,,%FK"AG::K"AI##K"0A-KK"r  )<r*   
__future__r   r  r$  r~  r[   typingtyabcr   r   r   r   r   email.utilsr	   http.cookiesr
   socketr   jupyter_eventsr   tornador   tornado.httpclientr   r   r   	traitletsr   r   r   r   r   r   r   r   r   r   traitlets.configr   r   jupyter_serverr   r   rk   r  rj   rl   rm   TYPE_CHECKINGr$   typer&   r/   r?   rB   rc  r  r+   r,   r-   <module>r     s     # " " " " "    				     , , , , , , , , , , ' ' ' ' ' ' ' ' - - - - - - % % % % % %       & & & & & &       M M M M M M M M M M                        H G G G G G G G P P P P P P P P
 $######M M M M Mgtt,?'@'@ M M M    	(?   0    .    T	1 T	1 T	1 T	1 T	1) T	1 T	1 T	1nB B B B B B B BJG G G G G Gr,   