a
    ø£Be«~  ã                   @   sŠ  d 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Z.dZ/dZ0ej1�rddlm2Z2 G dd„ de	e3e'ƒƒZ4G dd„ dee'e4d�Z5G dd„ de5ƒZ6G dd„ de(ƒZ7G dd„ dƒZ8e9ej:edœd d!„Z;dS )"zA kernel gateway client.é    N)Ú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                   @   s   e Zd ZdZdS )ÚGatewayTokenRenewerMetazBThe metaclass necessary for proper ABC behavior in a Configurable.N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__© r(   r(   úh/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/jupyter_server/gateway/gateway_client.pyr#   ,   s   r#   c                   @   s6   e Zd ZdZeeejedf eejedœ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.
    N©Úauth_header_keyÚauth_schemeÚ
auth_tokenÚkwargsÚreturnc                 K   s   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(   ©Úselfr,   r-   r.   r/   r(   r(   r)   Ú	get_token<   s    z!GatewayTokenRenewerBase.get_token)
r$   r%   r&   r'   r   ÚstrÚtyÚUnionÚAnyr3   r(   r(   r(   r)   r*   2   s   úr*   )Ú	metaclassc                   @   s2   e Zd ZdZeejedf eejedœdd„ZdS )ÚNoOpTokenRenewerzˆNoOpTokenRenewer is the default value to the GatewayClient trait
    `gateway_token_renewer` and merely returns the provided token.
    Nr+   c                 K   s   |S )zCThis implementation simply returns the current authorization token.r(   r1   r(   r(   r)   r3   P   s    zNoOpTokenRenewer.get_token)	r$   r%   r&   r'   r4   r5   r6   r7   r3   r(   r(   r(   r)   r9   K   s   úr9   c                       sŒ  e Zd ZU dZed Zeeƒjdd�Z	e
dƒdd„ ƒZdd	„ Zed
dddd�ZdZe
dƒdd„ ƒZedƒdd„ ƒZed
dddd�ZdZe
dƒdd„ ƒZedƒdd„ ƒZdZdZeeddd�Ze
dƒdd „ ƒZd!Zd"Zeedd#d�Ze
d$ƒd%d&„ ƒZd'Zd(Z eedd)d�Z!e
d*ƒd+d,„ ƒZ"d-Z#d.Z$e%e#dd/d�Z&e
d0ƒd1d2„ ƒZ'd3Z(d4Z)e%e(dd5d�Z*e
d6ƒd7d8„ ƒZ+ed
ddd9d�Z,d:Z-e
d;ƒd<d=„ ƒZ.ed
ddd>d�Z/d?Z0e
d@ƒdAdB„ ƒZ1ed
dddCd�Z2dDZ3e
dEƒdFdG„ ƒZ4ed
dddHd�Z5dIZ6e
dJƒdKdL„ ƒZ7ed
dddMd�Z8dNZ9e
dOƒdPdQ„ ƒZ:dRZ;dSZ<ee;dddTd�Z=e
dUƒdVdW„ ƒZ>dXZ?eddYdZ�Z@d[ZAe
d\ƒd]d^„ ƒZBd_ZCed
ddd`d�ZDdaZEe
dbƒdcdd„ ƒZFdeZGedddfdg�ZHdhZIe
diƒdjdk„ ƒZJdZKdlZLeMeKddmd�ZNe
dnƒdodp„ ƒZOd_ZPdqZQeePddrd�ZRe
dsƒdtdu„ ƒZSeePddvd�ZTdwZUdxZVe%eUddyd�ZWe
dzƒd{d|„ ƒZXd}ZYd~ZZe%eYddd�Z[e
d€ƒd�d‚„ ƒZ\dƒZ]d„Z^e_e]dd…d�Z`e
d†ƒd‡dˆ„ ƒZad‰ZbdŠZcedeedd‹dŒ�Zfe
d�ƒdŽd�„ ƒZgd�Zhd‘Zie%ehdd’d�Zje
d“ƒd”d•„ ƒZkd–Zld—ZmeMeldd˜d�Zne
d™ƒdšd›„ ƒZodœd�iZpeqerepƒŽ dždŸ„ ƒZsetd d¡„ ƒZuevewjx yd¢d£¡ƒZze{e|d¤< eee|d¥< ‡ fd¦d§„Z}d¨d©„ Z~dªd«„ Ze€d
d¬œd­d®„Z�d
d¯œd°d±„Z‚e{d
d²œd³d´„Zƒ‡  Z„S )µÚGatewayClientzîThis 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                 C   sJ   | j rt| j dƒr| j jS tƒ }td d }| |¡ | j d¡ |S d S )Nr<   Zgateway_clientzv1.yamlz%Event is registered in GatewayClient.)ÚparentÚhasattrr<   r
   r   Zregister_event_schemaÚlogÚinfo)r2   ÚloggerZschema_pathr(   r(   r)   Ú_default_event_loggere   s    
z#GatewayClient._default_event_loggerc                 C   s   | j j| j|d� dS )zLEmit event using the core event schema from Jupyter Server's Gateway Client.)Z	schema_idÚdataN)r<   ÚemitÚevent_schema_id)r2   rC   r(   r(   r)   rD   r   s    zGatewayClient.emitNa  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_noner;   ÚhelpZJUPYTER_GATEWAY_URLÚurlc                 C   s   t j | j¡S ©N)ÚosÚenvironÚgetÚurl_env©r2   r(   r(   r)   Ú_url_defaultƒ   s    zGatewayClient._url_defaultc                 C   sZ   |d }|d urVt |ƒdkrVt|ƒ ¡  d¡sVd| }| jtttdt|id� t	|ƒ‚|S )NÚvaluer   Úhttpz.GatewayClient url must start with 'http': '%r'é�  ©rC   ©
Úlenr4   ÚlowerÚ
startswithrD   Ú
STATUS_KEYÚERROR_STATUSÚSTATUS_CODE_KEYÚMESSAGE_KEYr   ©r2   ZproposalrQ   Úmessager(   r(   r)   Ú_url_validate‡   s    &zGatewayClient._url_validatezÓThe 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)
        ZJUPYTER_GATEWAY_WS_URLÚws_urlc                 C   s<   t j | j¡}| jd ur8|d u r8| jr8| j ¡  dd¡}|S )NrR   Úws)rK   rL   rM   Ú
ws_url_envrI   Úgateway_enabledrW   Úreplace)r2   rF   r(   r(   r)   Ú_ws_url_defaultœ   s    zGatewayClient._ws_url_defaultc                 C   sZ   |d }|d urVt |ƒdkrVt|ƒ ¡  d¡sVd| }| jtttdt|id� t	|ƒ‚|S )NrQ   r   ra   z/GatewayClient ws_url must start with 'ws': '%r'rS   rT   rU   r]   r(   r(   r)   Ú_ws_url_validate£   s    &zGatewayClient._ws_url_validatez/api/kernelsZ JUPYTER_GATEWAY_KERNELS_ENDPOINTzbThe gateway API endpoint for accessing kernel resources (JUPYTER_GATEWAY_KERNELS_ENDPOINT env var))rF   r;   rH   Úkernels_endpointc                 C   s   t j | j| j¡S rJ   )rK   rL   rM   Úkernels_endpoint_envÚkernels_endpoint_default_valuerO   r(   r(   r)   Ú_kernels_endpoint_defaultµ   s    z'GatewayClient._kernels_endpoint_defaultz/api/kernelspecsZ$JUPYTER_GATEWAY_KERNELSPECS_ENDPOINTzaThe gateway API endpoint for accessing kernelspecs (JUPYTER_GATEWAY_KERNELSPECS_ENDPOINT env var)Úkernelspecs_endpointc                 C   s   t j | j| j¡S rJ   )rK   rL   rM   Úkernelspecs_endpoint_envÚ"kernelspecs_endpoint_default_valuerO   r(   r(   r)   Ú_kernelspecs_endpoint_defaultÁ   s    ÿz+GatewayClient._kernelspecs_endpoint_defaultz/kernelspecsZ-JUPYTER_GATEWAY_KERNELSPECS_RESOURCE_ENDPOINTzpThe gateway endpoint for accessing kernelspecs resources
(JUPYTER_GATEWAY_KERNELSPECS_RESOURCE_ENDPOINT env var)Úkernelspecs_resource_endpointc                 C   s   t j | j| j¡S rJ   )rK   rL   rM   Ú!kernelspecs_resource_endpoint_envÚ+kernelspecs_resource_endpoint_default_valuerO   r(   r(   r)   Ú&_kernelspecs_resource_endpoint_defaultÐ   s    þz4GatewayClient._kernelspecs_resource_endpoint_defaultg      D@ZJUPYTER_GATEWAY_CONNECT_TIMEOUTzuThe time allowed for HTTP connection establishment with the Gateway server.
(JUPYTER_GATEWAY_CONNECT_TIMEOUT env var)Úconnect_timeoutc                 C   s   t tj | j| j¡ƒS rJ   )ÚfloatrK   rL   rM   Úconnect_timeout_envÚconnect_timeout_default_valuerO   r(   r(   r)   Ú_connect_timeout_defaultà   s    z&GatewayClient._connect_timeout_defaultg      E@ZJUPYTER_GATEWAY_REQUEST_TIMEOUTzWThe time allowed for HTTP request completion. (JUPYTER_GATEWAY_REQUEST_TIMEOUT env var)Úrequest_timeoutc                 C   s   t tj | j| j¡ƒS rJ   )rt   rK   rL   rM   Úrequest_timeout_envÚrequest_timeout_default_valuerO   r(   r(   r)   Ú_request_timeout_defaultì   s    z&GatewayClient._request_timeout_defaultzWThe filename for client SSL key, if any.  (JUPYTER_GATEWAY_CLIENT_KEY env var)
        ZJUPYTER_GATEWAY_CLIENT_KEYÚ
client_keyc                 C   s   t j | j¡S rJ   )rK   rL   rM   Úclient_key_envrO   r(   r(   r)   Ú_client_key_defaultù   s    z!GatewayClient._client_key_defaultz`The filename for client SSL certificate, if any.  (JUPYTER_GATEWAY_CLIENT_CERT env var)
        ZJUPYTER_GATEWAY_CLIENT_CERTÚclient_certc                 C   s   t j | j¡S rJ   )rK   rL   rM   Úclient_cert_envrO   r(   r(   r)   Ú_client_cert_default  s    z"GatewayClient._client_cert_defaultzeThe filename of CA certificates or None to use defaults.  (JUPYTER_GATEWAY_CA_CERTS env var)
        ZJUPYTER_GATEWAY_CA_CERTSÚca_certsc                 C   s   t j | j¡S rJ   )rK   rL   rM   Úca_certs_envrO   r(   r(   r)   Ú_ca_certs_default  s    zGatewayClient._ca_certs_defaultzRThe username for HTTP authentication. (JUPYTER_GATEWAY_HTTP_USER env var)
        ZJUPYTER_GATEWAY_HTTP_USERÚ	http_userc                 C   s   t j | j¡S rJ   )rK   rL   rM   Úhttp_user_envrO   r(   r(   r)   Ú_http_user_default   s    z GatewayClient._http_user_defaultzRThe password for HTTP authentication.  (JUPYTER_GATEWAY_HTTP_PWD env var)
        ZJUPYTER_GATEWAY_HTTP_PWDÚhttp_pwdc                 C   s   t j | j¡S rJ   )rK   rL   rM   Úhttp_pwd_envrO   r(   r(   r)   Ú_http_pwd_default-  s    zGatewayClient._http_pwd_defaultz{}ZJUPYTER_GATEWAY_HEADERSz�Additional HTTP headers to pass on the request.  This value will be converted to a dict.
          (JUPYTER_GATEWAY_HEADERS env var)
        Úheadersc                 C   s   t j | j| j¡S rJ   )rK   rL   rM   Úheaders_envÚheaders_default_valuerO   r(   r(   r)   Ú_headers_default<  s    zGatewayClient._headers_defaultÚ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))r;   rH   ZJUPYTER_GATEWAY_AUTH_HEADER_KEYr,   c                 C   s   t j | j| j¡S rJ   )rK   rL   rM   Úauth_header_key_envÚauth_header_key_default_valuerO   r(   r(   r)   Ú_auth_header_key_defaultO  s    z&GatewayClient._auth_header_key_defaultÚ z®The 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)ZJUPYTER_GATEWAY_AUTH_TOKENr.   c                 C   s   t j | j| j¡S rJ   )rK   rL   rM   Úauth_token_envÚauth_token_default_valuerO   r(   r(   r)   Ú_auth_token_default`  s    z!GatewayClient._auth_token_defaultÚtokenz}The auth scheme, added as a prefix to the authorization token used in the HTTP headers.
(JUPYTER_GATEWAY_AUTH_SCHEME env var))rG   r;   rH   ZJUPYTER_GATEWAY_AUTH_SCHEMEr-   c                 C   s   t j | j| j¡S rJ   )rK   rL   rM   Úauth_scheme_envÚauth_scheme_default_valuerO   r(   r(   r)   Ú_auth_scheme_defaultm  s    z"GatewayClient._auth_scheme_defaultZJUPYTER_GATEWAY_VALIDATE_CERTzzFor HTTPS requests, determines if server's certificate should be validated or not.
(JUPYTER_GATEWAY_VALIDATE_CERT env var)Úvalidate_certc                 C   s   t tj | jt| jƒ¡dvƒS ©N)ÚnoÚfalse)ÚboolrK   rL   rM   Úvalidate_cert_envr4   Úvalidate_cert_default_valuerO   r(   r(   r)   Ú_validate_cert_defaultz  s
    ÿÿz$GatewayClient._validate_cert_defaultZ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                 C   s   t j | jt j d| j¡¡S )NZJUPYTER_GATEWAY_ENV_WHITELIST)rK   rL   rM   Úallowed_envs_envÚallowed_envs_default_valuerO   r(   r(   r)   Ú_allowed_envs_defaultŒ  s    þz#GatewayClient._allowed_envs_defaultz,Deprecated, use `GatewayClient.allowed_envs`g      ð?Z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                 C   s   t tj | j| j¡ƒS rJ   )rt   rK   rL   rM   Úgateway_retry_interval_envÚ$gateway_retry_interval_default_valuerO   r(   r(   r)   Ú_gateway_retry_interval_default¤  s    þÿz-GatewayClient._gateway_retry_interval_defaultg      >@Z"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                 C   s   t tj | j| j¡ƒS rJ   )rt   rK   rL   rM   Úgateway_retry_interval_max_envÚ(gateway_retry_interval_max_default_valuerO   r(   r(   r)   Ú#_gateway_retry_interval_max_default¶  s    þÿz1GatewayClient._gateway_retry_interval_max_defaulté   ZJUPYTER_GATEWAY_RETRY_MAXznThe maximum retries allowed for HTTP reconnection with the Gateway server.
(JUPYTER_GATEWAY_RETRY_MAX env var)Úgateway_retry_maxc                 C   s   t tj | j| j¡ƒS rJ   )ÚintrK   rL   rM   Úgateway_retry_max_envÚgateway_retry_max_default_valuerO   r(   r(   r)   Ú_gateway_retry_max_defaultÈ  s    z(GatewayClient._gateway_retry_max_defaultz6jupyter_server.gateway.gateway_client.NoOpTokenRenewerZ#JUPYTER_GATEWAY_TOKEN_RENEWER_CLASSzYThe class to use for Gateway token renewal. (JUPYTER_GATEWAY_TOKEN_RENEWER_CLASS env var))Úklassr;   rH   Úgateway_token_renewer_classc                 C   s   t j | j| j¡S rJ   )rK   rL   rM   Úgateway_token_renewer_class_envÚ)gateway_token_renewer_class_default_valuerO   r(   r(   r)   Ú$_gateway_token_renewer_class_defaultÖ  s    ÿz2GatewayClient._gateway_token_renewer_class_defaultg       @Z"JUPYTER_GATEWAY_LAUNCH_TIMEOUT_PADzÁTimeout 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                 C   s   t tj | j| j¡ƒS rJ   )rt   rK   rL   rM   Úlaunch_timeout_pad_envÚ launch_timeout_pad_default_valuerO   r(   r(   r)   Ú_launch_timeout_pad_defaultæ  s    þÿz)GatewayClient._launch_timeout_pad_defaultFZJUPYTER_GATEWAY_ACCEPT_COOKIESz¹Accept 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                 C   s"   t tj | jt| jƒ ¡ ¡dvƒS rœ   )rŸ   rK   rL   rM   Úaccept_cookies_envr4   Úaccept_cookies_valuerW   rO   r(   r(   r)   Ú_accept_cookies_defaultù  s
    ÿÿz%GatewayClient._accept_cookies_defaultÚenv_whitelist)r£   z2.0c                 C   sl   |j }| j| \}}t| |ƒ}||jkrh| j | jj› d|› d|› d| jj› d|› d�
¡ t| ||jƒ dS )zobserver for deprecated traitsÚ.z! is deprecated in jupyter_server z, use z insteadN)	ÚnameÚ_deprecated_traitsÚgetattrÚnewr?   ÚwarningÚ	__class__r$   Úsetattr)r2   ZchangeÚold_attrÚnew_attrÚversionÚ	new_valuer(   r(   r)   Ú_deprecated_trait  s    

ÿÿÿÿzGatewayClient._deprecated_traitc                 C   s   t | jd uot| jƒdkƒS )Nr   )rŸ   rI   rV   rO   r(   r(   r)   rc     s    zGatewayClient.gateway_enabledÚKERNEL_LAUNCH_TIMEOUTé(   Ú_connection_argsÚgateway_token_renewerc                    s4   t ƒ jf i |¤Ž i | _| j| | jd�| _i | _dS )zInitialize a gateway client.)r=   r?   N)ÚsuperÚ__init__rÒ   r¶   r?   rÓ   Ú_cookies)r2   r/   ©rÉ   r(   r)   rÕ   !  s    ÿzGatewayClient.__init__c                 C   s  t tjƒ| j }| j|k r"|| _n| j|kr>t| j| j ƒt_ttjƒtjd< | j	rœt
 | j	¡| jd< | j| jd vrœ| jd  | j› | j› d| j› �i¡ | j| jd< | j| jd< | j| jd< | jrð| j| jd< | j| jd< | jrð| j| jd	< | j�r| j| jd
< | j�r| j| jd< dS )z‰Initialize arguments used on every request.  Since these are primarily static values,
        we'll perform this operation once.
        rÐ   r‹   ú rs   rx   r›   r   r|   r‚   Zauth_usernameZauth_passwordN)rt   r:   rÐ   rº   rx   r±   r4   rK   rL   r‹   ÚjsonÚloadsrÒ   r,   Úupdater-   r.   rs   r›   r   r|   r‚   r…   rˆ   )r2   Zminimum_request_timeoutr(   r(   r)   Úinit_connection_args,  s6    ÿ


ÿ
ÿz"GatewayClient.init_connection_argsc              
   K   s  t | jƒdkr|  ¡  | j}| jdurˆz| j | j| j| j¡| _W nD ty† } z,| j	 
d| j› d|› �¡ || _W Y d}~n
d}~0 0 | j ¡ D ]Z\}}|dkrä| |i ¡}t|tƒrì| |¡ | | j› | j› d| j› �i¡ q’|||< q’| jrþ|  |¡ |S )z¦Merges 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Ø   )rV   rÒ   rÜ   r.   rÓ   r3   r,   r-   Ú	Exceptionr?   r   r¶   ÚitemsÚ
setdefaultÚ
isinstanceÚdictrÛ   r¾   Ú_update_cookie_header)r2   r/   Zprev_auth_tokenÚexÚargrQ   Zgiven_valuer(   r(   r)   Úload_connection_argsR  s:    
ÿ
þýÿ

ÿ

z"GatewayClient.load_connection_args)Úcookier0   c                 C   sp   | j s
dS tjtjd�}| ¡ D ]J\}}| d¡r\| d¡s\t|d ƒ| }t| 	¡ ƒ|d< ||f| j
|< q dS )z8Update cookies from existing requests for load balancersN©ÚtzÚexpiresúmax-age)r¾   r   Únowr   ÚutcrÞ   rM   r   r4   Útotal_secondsrÖ   )r2   ræ   Ú
store_timeÚkeyÚitemZexpire_timedeltar(   r(   r)   Úupdate_cookies{  s    zGatewayClient.update_cookies)r0   c                 C   sv   t jtjd�}g }| j ¡ D ]>\}\}}| d¡}|s8q|| }| ¡ t|ƒkr| 	|¡ q|D ]}| j 
|¡ q`dS )zClear expired cookies.rç   rê   N)r   rë   r   rì   rÖ   rÞ   rM   rí   rt   ÚappendÚpop)r2   Z
check_timeZexpired_keysrï   Úmorselrî   Zcookie_max_ageZexpired_timedeltar(   r(   r)   Ú_clear_expired_cookiesŠ  s    
z$GatewayClient._clear_expired_cookies)Úconnection_argsr0   c                 C   st   |   ¡  d dd„ | j ¡ D ƒ¡}|rp| di ¡}tdd„ |D ƒdƒ}| |¡}|r`|d | }|||< ||d< dS )zUpdate a cookie header.z; c                 s   s&   | ]\}\}}|› d |j › �V  qdS )ú=N)Úcoded_value)Ú.0rÄ   rô   Ú_timer(   r(   r)   Ú	<genexpr>ž  s   z6GatewayClient._update_cookie_header.<locals>.<genexpr>r‹   c                 s   s   | ]}|  ¡ d kr|V  qdS )ræ   N)rW   )rù   Z
header_keyr(   r(   r)   rû   §  ó    ÚCookieN)rõ   ÚjoinrÖ   rÞ   rM   Únext)r2   rö   Zgateway_cookie_valuesr‹   Zcookie_header_nameZexisting_cookier(   r(   r)   râ   š  s    
ÿþ
z#GatewayClient._update_cookie_header)…r$   r%   r&   r'   r   rE   r   r
   Útagr<   r   rB   rD   r   rI   rN   rP   r   r_   r`   rb   re   rf   ri   rh   rg   rj   rm   rl   rk   rn   rq   rp   ro   rr   rv   ru   r   rs   rw   rz   ry   rx   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Â   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Ï   Úpropertyrc   r±   rK   rL   rM   rÐ   rá   Ú__annotations__rÕ   rÜ   rå   r   rñ   rõ   râ   Ú__classcell__r(   r(   r×   r)   r:   [   sð  

ü

	ü	

	ý
ý
ý
ý
ý
ü
ü
ü
ü
ü
ü	
þ
ü

ý
ý
ý	
ýý	
ý
ý
ÿý
ý
ý
ÿ


&)r:   c                   @   sÐ   e Zd ZU dZdZdZee de¡ƒZ	ee
d< edee	eƒƒZ	ddhZeje e
d	< h d
£Zeje e
d< ehZeje e
d< dZee
d< dd„ Zeejedœdd„Zeejedœdd„Zeeedœ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.
    é   é
   Z#JUPYTER_GATEWAY_MAX_REQUEST_RETRIESÚmax_retriesr   ÚGETÚDELETEÚretried_methods>   iø  é÷  iö  iW  Úretried_errorsÚretried_exceptionsgš™™™™™¹?Úbackoff_factorc                 C   s   d| _ tƒ | _dS )z%Initialize the retryable http client.r   N)Úretry_countr   ÚclientrO   r(   r(   r)   rÕ   Ä  s    zRetryableHTTPClient.__init__©Úendpointr/   r0   c                 Ë   s   d| _ | j|fi |¤ŽI dH 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)r  Ú_fetch)r2   r  r/   r(   r(   r)   ÚfetchÉ  s    zRetryableHTTPClient.fetchc                 Ë   s¤   z| j j|fi |¤ŽI dH }W n€ tyž } zh|  |d |¡I dH }|sL|‚t d¡ d| j› d|› d|›d�¡ | j|fi |¤ŽI dH }W Y d}~n
d}~0 0 |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: 'ú')	r  r  rÝ   Ú_is_retryableÚloggingÚ	getLoggerr@   r  r  )r2   r  r/   ÚresponseÚeZis_retryabler(   r(   r)   r  Ñ  s    

ÿÿÿ.zRetryableHTTPClient._fetch)r  Ú	exceptionr0   c                 ƒ   sˆ   || j vrdS | j| jkrdS tˆ tƒr>ˆ }|j| jvrZdS nt‡ fdd„| jD ƒƒsZdS t	 
| jd| j  ¡I dH  |  jd7  _dS )zODetermines if the given exception is retryable based on object's configuration.Fc                 3   s   | ]}t ˆ |ƒV  qd S rJ   )rà   )rù   r   ©r  r(   r)   rû   ð  rü   z4RetryableHTTPClient._is_retryable.<locals>.<genexpr>r  Né   T)r  r  r  rà   r   Úcoder  Úanyr  ÚasyncioÚsleepr  )r2   r  r  Zhcer(   r  r)   r  ã  s    

z!RetryableHTTPClient._is_retryableN)r$   r%   r&   r'   ZMAX_RETRIES_DEFAULTZMAX_RETRIES_CAPr±   rK   Úgetenvr  r  ÚmaxÚminr  r5   ÚSetr4   r  ÚConnectionErrorr  Útyper  rt   rÕ   r7   r   r  r  rÝ   rŸ   r  r(   r(   r(   r)   r  ´  s   
r  r  c           
      Ë   sœ  t  ¡ jf i |¤Ž}tƒ }z:|j| fi |¤ŽI dH }t  ¡ jtttdt	did� W �n t
�y. } zÀt  ¡ jttt|jt	t|jƒid� dt  ¡ j› d�}|j}|jrúz.t |jj¡}| d¡pÄ|}| d¡pÒ|}W n" tjjyø   |jj ¡ }Y n0 t |jd	|› d
|› d�¡|‚W Y d}~�n6d}~0  t�yŽ } zHt  ¡ jtttdt	t|ƒid� t ddt  ¡ j› d�¡|‚W Y d}~nÖd}~0  t�yî } zHt  ¡ jtttdt	t|ƒid� t ddt  ¡ j› d�¡|‚W Y d}~nvd}~0  t�yZ } zTt  ¡ jtttdt	t|ƒid� t d¡ dt  ¡ j› d|› �|¡ |‚W Y d}~n
d}~0 0 t  ¡ j �r˜|j! d¡}|�r˜t"ƒ }	|	 #|¡ t  ¡  $|	¡ |S )zDMake an async request to kernel gateway endpoint, returns a responseNéÈ   r   rT   z=Exception while attempting to connect to Gateway server url 'r  Úreasonr^   zError from Gateway: [z] zB. Ensure gateway url is valid and the Gateway instance is running.r  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  z8Exception while trying to launch kernel via Gateway URL z , z
Set-Cookie)%r:   Úinstancerå   r  r  rD   rY   ÚSUCCESS_STATUSr[   r\   r   rZ   r!  r4   r^   rI   r  rÙ   rÚ   ÚbodyrM   ÚdecoderÚJSONDecodeErrorÚdecoder   Ú	HTTPErrorr)  r	   rÝ   r  r  r   r¾   r‹   r   Úloadrñ   )
r  r/   Zrhcr  r  Zerror_reasonÚerror_messageZerror_payloadZcookie_valuesræ   r(   r(   r)   Úgateway_requestù  s|    ÿÿþüÿþüÿþüÿ
þ
r6  )<r'   r#  rÙ   r  rK   Útypingr5   Úabcr   r   r   r   r   Úemail.utilsr   Úhttp.cookiesr   Úsocketr	   Zjupyter_eventsr
   Útornador   Ztornado.httpclientr   r   r   Z	traitletsr   r   r   r   r   r   r   r   r   r   Ztraitlets.configr   r   Zjupyter_serverr   r   rZ   r.  rY   r[   r\   ÚTYPE_CHECKINGr"   r*  r#   r*   r9   r:   r  r4   r7   r6  r(   r(   r(   r)   Ú<module>   sF   0
ÿ    ]E