
    Mh                        d Z ddlm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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.    )annotationsN)Anycast)Future)json_decode
url_escapeutf8)HTTPRequest)IOLoop)BoolInstanceIntUnicode   )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 eddd          Zd Zd	 Zd
 Zd ZddZddZd Zed             ZdS )GatewayWebSocketConnectionzBWeb socket connection that proxies to a kernel/enterprise gateway.T)klass
allow_noneFr    )r   configc                   K   d _         t          t          j                    j        pdt          j                    j        t           j                  d          } j        r|dt           j                   z  } j	        
                    d|            i } t          j                    j        di |}t          |fi |}t          dt          j        |                     _         j                             j                   t'          j                    }|                     j         fd           dS )	zConnect to the socket.Nr   channelsz?session_id=zConnecting to zFuture[Any]c                ,                                     S N)_read_messages)futureselfs    b/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/jupyter_server/gateway/connections.py<lambda>z4GatewayWebSocketConnection.connect.<locals>.<lambda>=   s    t7J7J7L7L      )wsr   r   instancews_urlkernels_endpointr   	kernel_id
session_idloginfoload_connection_argsr
   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~&&	
 
 ? 	CBZ%@%@BBBF/v//000!#>'))>HHHHf////m->-PQX-Y-YZZ(()>???~(L(L(L(LMMMMMr$   c                :   | j         sX|                                D|                                | _        d| _        | j                            d| j                    dS | j                            d| j         dt          j
                    j                    dS )zHandle a finished connection.Nr   zConnection is ready: ws: z]Websocket connection has been closed via client disconnect or due to error.  Kernel with ID 'z*' may not be terminated on GatewayClient: )disconnected	exceptionresultr&   retryr,   debugwarningr*   r   r'   url)r!   futs     r"   r3   z+GatewayWebSocketConnection._connection_done?   s     !
	&)mmoo&=jjllDGDJHNN@tw@@AAAAAH|#'>| |]j]s]u]u]y| |    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: )r;   r&   closer1   donecancelr,   r?   )r!   s    r"   
disconnectz%GatewayWebSocketConnection.disconnectM   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&   r;   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   r4   spawn_callbackr9   )r!   messageejitterretry_intervalr8   s         r"   r   z)GatewayWebSocketConnection._read_messagesX   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strargsr   returnNonec                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_   ra   msg_summarys       r"   rQ   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)r[   c                      j         ; j        4t          j                    }|                     j         fd           dS                                 dS )Send message to gateway server.Nc                .                                   S r   )handle_incoming_message)r    r[   r!   s    r"   r#   zDGatewayWebSocketConnection.handle_incoming_message.<locals>.<lambda>   s    4;W;WX_;`;` r$   )r&   r1   r   r4   r5   _write_message)r!   r[   r8   s   `` r"   rp   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)rn   Nz(Exception writing message to websocket: )r;   r&   rf   rL   r,   rM   )r!   r[   r\   s      r"   rq   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_staterM   z
, {}:{}:{}enameevalue	tracebackz, ...r   N)appendformatjoin)r[   summarymessage_types      r"   rk   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$   N)r_   r`   ra   r   rb   rc   )r[   r`   rb   rc   )__name__
__module____qualname____doc__r   r/   WebSocketClientConnectionr&   r   r1   r   r;   r   r>   r   kernel_ws_protocolr9   r3   rG   r   rQ   rp   rq   staticmethodrk   r%   r$   r"   r   r      s       LL	)CPT	U	U	UBv$777I4;;LCFFE
 !TBBBN N N.  	` 	` 	`+. +. +.Z   ) ) ) )K K K $ $ \$ $ $r$   r   )"r   
__future__r   rX   ri   rS   typingr   r   tornado.websocket	websocketr/   tornado.concurrentr   tornado.escaper   r   r	   tornado.httpclientr
   tornado.ioloopr   	traitletsr   r   r   r    services.kernels.connection.baser   utilsr   gateway_clientr   r   r%   r$   r"   <module>r      sQ   ! ! # " " " " "            - - - - - - % % % % % % 8 8 8 8 8 8 8 8 8 8 * * * * * * ! ! ! ! ! ! 2 2 2 2 2 2 2 2 2 2 2 2 L L L L L L ! ! ! ! ! ! ) ) ) ) ) )^$ ^$ ^$ ^$ ^$!> ^$ ^$ ^$ ^$ ^$r$   