
    Ke1                         d Z 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 ddlmZmZ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 d	dlmZ ddlmZ  G d de          ZdS )zGateway connection classes.    N)Anycast)Future)json_decode
url_escapeutf8)HTTPRequest)IOLoop)BoolInstanceInt   )BaseKernelWebsocketConnection)url_path_join   )GatewayClientc                       e Zd ZdZ eej        d          Z eed          Z	 e
d          Z ed          Zd Zd Zd Zd	 Zd
ededdfdZdeddfdZd Zed             ZdS )GatewayWebSocketConnectionzBWeb socket connection that proxies to a kernel/enterprise gateway.T)klass
allow_noneFr   c                 J   K   d _         t          t          j                    j        pdt          j                    j        t           j                  d          } j        	                    d|            i } t          j                    j
        di |}t          |fi |}t          t          t          j        |                     _         j                             j                   t'          j                    }|                     j         fd           dS )zConnect to the socket.N channelszConnecting to c                 ,                                     S N)_read_messages)futureselfs    Blib/python3.11/site-packages/jupyter_server/gateway/connections.py<lambda>z4GatewayWebSocketConnection.connect.<locals>.<lambda>4   s    t7J7J7L7L      )wsr   r   instancews_urlkernels_endpointr   	kernel_idloginfoload_connection_argsr	   r   r   tornado_websocketwebsocket_connect	ws_futureadd_done_callback_connection_doner
   current
add_future)r   r%   kwargsrequestloops   `    r   connectz"GatewayWebSocketConnection.connect!   s      "$$+1r"$$5t~&&	
 
 	/v//000>'))>HHHHf////f&7&I'&R&RSS(()>???~(L(L(L(LMMMMMr!   c                 V   | j         sX|                                D|                                | _        d| _        | j                            d| j                    dS | j                            d                    | j	        t          j                    j                             dS )zHandle a finished connection.Nr   zConnection is ready: ws: zWebsocket connection has been closed via client disconnect or due to error.  Kernel with ID '{}' may not be terminated on GatewayClient: {})disconnected	exceptionresultr#   retryr(   debugwarningformatr'   r   r$   url)r   futs     r   r/   z+GatewayWebSocketConnection._connection_done6   s     !	&)mmoo&=jjllDGDJHNN@tw@@AAAAAHQQWQWNM$:$<$<$@R R    r!   c                    d| _         | j        | j                                         dS | j        rV| j                                        s?| j                                         | j                            d| j                     dS dS dS )zHandle a disconnect.TNz-_disconnect: future cancelled, disconnected: )r7   r#   closer-   donecancelr(   r;   )r   s    r   
disconnectz%GatewayWebSocketConnection.disconnectF   s     7GMMOOOOO^ 	`DN$7$7$9$9 	`N!!###HNN^4K\^^_____	` 	` 	` 	`r!   c                   K   | j         d}| j        s	 | j                                          d{V }n4# t          $ r'}| j                            d|            Y d}~nd}~ww xY w|*| j        s"| j                            d| j                    nHt          |t                    r|
                    d          }|                     |           nn| j         | j        s| j        t          j                    j        k     rt!          j        dd          dz  }t%          t          j                    j        d| j        z  z  t          j                    j                  |z   }| xj        d	z  c_        | j                            d
|| j        t          j                    j        | j                   t-          j        |           d{V  t1          j                    }|                    | j                   dS dS dS )z"Read messages from gateway server.Nz*Exception reading message from websocket: zLost connection to Gateway: r   
   d   g{Gz?r   r   zKAttempting to re-establish the connection to Gateway in %s secs (%s/%s): %s)r#   r7   read_message	Exceptionr(   errorr<   r'   
isinstancebytesdecodehandle_outgoing_messager:   r   r$   gateway_retry_maxrandomrandintmingateway_retry_intervalgateway_retry_interval_maxr)   asynciosleepr
   r0   spawn_callbackr5   )r   messageejitterretry_intervalr4   s         r   r   z)GatewayWebSocketConnection._read_messagesQ   sS     g!G$ $(G$8$8$:$:::::::GG    HNNHQHH        ?, Z(()X)X)XYYYgu-- 5%nnV44G,,    ' g!,   	.TZ-2H2J2J2\%\%\^B,,t3F!*,,Cq$*}U!*,,G  	  JJ!OJJHMM]
&((:   -/////////>##D-----'	. 	.%\%\s   4 
A%A  A%incoming_msgargsreturnNc                 X   	 | j                             |           dS # t          j        $ r| | j                            t          j                  rTt          	                    t          t          |                              }| j                            d|            Y dS Y dS w xY w)z$Send message to the notebook client.z?Notebook client closed websocket connection - message dropped: N)websocket_handlerwrite_messager+   WebSocketClosedErrorr(   isEnabledForloggingDEBUGr   _get_message_summaryr   r   r;   )r   r\   r]   msg_summarys       r   rN   z2GatewayWebSocketConnection.handle_outgoing_message~   s    		"00>>>>> 5 	 	 	x$$W]33 8MM\ 2 233  cVacc     	  	s    BB)(B)rX   c                       j         ; j        4t          j                    }|                     j         fd           dS                                 dS )Send message to gateway server.Nc                 .                                   S r   )handle_incoming_message)r   rX   r   s    r   r    zDGatewayWebSocketConnection.handle_incoming_message.<locals>.<lambda>   s    4;W;WX_;`;` r!   )r#   r-   r
   r0   r1   _write_message)r   rX   r4   s   `` r   rk   z2GatewayWebSocketConnection.handle_incoming_message   sb    7?t~9>##DOODN,`,`,`,`,`aaaaa(((((r!   c                     	 | j         s#| j        | j                            |           dS dS dS # t          $ r(}| j                            d|            Y d}~dS d}~ww xY w)ri   Nz(Exception writing message to websocket: )r7   r#   ra   rI   r(   rJ   )r   rX   rY   s      r   rl   z)GatewayWebSocketConnection._write_message   s    	K$ /)<%%g...../ /)<)< 	K 	K 	KHNNIaIIJJJJJJJJJ	Ks   (0 
A"AA"c                    g }| d         }|                     d|            |dk    r6|                     d                    | d         d                              dS |dk    rP|                     d                    | d         d	         | d         d
         | d         d                              dS |                     d           d                    |          S )zGet a summary of a message.msg_typeztype: statusz, state: {}contentexecution_staterJ   z
, {}:{}:{}enameevalue	tracebackz, ...r   N)appendr=   join)rX   summarymessage_types      r   rf   z/GatewayWebSocketConnection._get_message_summary   s     z*...///8##NN=//	0BCT0UVVWWWWWW$$NN##I&w/I&x0I&{3      NN7###777###r!   )__name__
__module____qualname____doc__r   r+   WebSocketClientConnectionr#   r   r-   r   r7   r   r:   r5   r/   rD   r   strr   rN   rk   rl   staticmethodrf   r"   r!   r   r   r      s       LL	)CPT	U	U	UBv$777I4;;LCFFEN N N*   	` 	` 	`+. +. +.ZC      )s )t ) ) ) )K K K $ $ \$ $ $r!   r   )r}   rU   rd   rP   typingr   r   tornado.websocket	websocketr+   tornado.concurrentr   tornado.escaper   r   r   tornado.httpclientr	   tornado.ioloopr
   	traitletsr   r   r    services.kernels.connection.baser   utilsr   gateway_clientr   r   r"   r!   r   <module>r      s9   ! !            - - - - - - % % % % % % 8 8 8 8 8 8 8 8 8 8 * * * * * * ! ! ! ! ! ! ) ) ) ) ) ) ) ) ) ) L L L L L L ! ! ! ! ! ! ) ) ) ) ) )Y$ Y$ Y$ Y$ Y$!> Y$ Y$ Y$ Y$ Y$r!   