
    -eG?                    p   d Z ddlmZ ddlZ ej        e          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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  ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z( ddl)m*Z* erddl+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 dZ5 G d d          Z6 e              dS )z Implements a very low level facility for communicating with a Bokeh
Server.

Users will always want to use :class:`~bokeh.client.session.ClientSession`
instead for standard usage.

    )annotationsN)TYPE_CHECKINGAnyCallable)HTTPClientErrorHTTPRequest)IOLoop)WebSocketErrorwebsocket_connect   )ID)Protocol)MessageErrorProtocolErrorValidationError)Receiver)format_url_query_arguments)fixup_windows_event_loop_policy   )CONNECTED_AFTER_ACKCONNECTED_BEFORE_ACKDISCONNECTEDNOT_YET_CONNECTEDWAITING_FOR_REPLYErrorReasonState) WebSocketClientConnectionWrapper)Document)DocumentChangedEvent)Message)
ServerInfo)ClientSession)ClientConnectionc                  r   e Zd ZU dZded<   ded<   ded<   	 	 dEdFdZedGd            ZedHd            ZedId            Z	edJd            Z
edKd            ZedId            ZdLd ZdMdNd#ZdLd$ZdLd%ZdOd(ZdPd*ZdQd,ZdRd.ZdLd/ZdLd0ZdSd3ZdLd4ZdTd6ZdUd7ZdVd<ZdQd=ZdLd>ZdWd@ZdXdCZdLdDZ dS )Yr#   z; A low-level class used to connect to a Bokeh server.

    r   _stater	   _loopzCallable[[], bool] | None_until_predicateN  @sessionr"   websocket_urlstrio_loopIOLoop | None	argumentsdict[str, str] | Nonemax_message_sizeintreturnNonec                   || _         || _        || _        || _        t	                      | _        t          | j                  | _        d| _        t                      | _
        ||nt                      | _        d| _        d| _        dS )z6 Opens a websocket connection to the server.

        N)_url_session
_arguments_max_message_sizer   	_protocolr   	_receiver_socketr   r%   r	   r&   r'   _server_info)selfr)   r*   r,   r.   r0   s         7lib/python3.11/site-packages/bokeh/client/connection.py__init__zClientConnection.__init__U   s}    
 "	#!1!!$.11')) !( 3WW
 $     boolc                6    t          | j        t                    S )zg Whether we've connected the Websocket and have exchanged initial
        handshake messages.

        )
isinstancer%   r   r=   s    r>   	connectedzClientConnection.connectedj   s     $+':;;;r@   c                    | j         S )z2 The Tornado ``IOLoop`` this connection is using. )r&   rD   s    r>   r,   zClientConnection.io_loopr   s     zr@   c                    | j         S )z1 The URL of the websocket this Connection is to. )r5   rD   s    r>   urlzClientConnection.urlw   s     yr@   ErrorReason | Nonec                R    t          | j        t                    sdS | j        j        S )zX The reason of the connection loss encoded as a ``DISCONNECTED.ErrorReason`` enum value N)rC   r%   r   error_reasonrD   s    r>   rK   zClientConnection.error_reason|   s(     $+|44 	4{''r@   
int | Nonec                R    t          | j        t                    sdS | j        j        S )zv If there was an error that caused a disconnect, this property holds
        the error code. None otherwise.

        r   )rC   r%   r   
error_coderD   s    r>   rN   zClientConnection.error_code   s(     $+|44 	1{%%r@   c                R    t          | j        t                    sdS | j        j        S )z If there was an error that caused a disconnect, this property holds
        the error detail. Empty string otherwise.

         )rC   r%   r   error_detailrD   s    r>   rQ   zClientConnection.error_detail   s(     $+|44 	2{''r@   c                >     d fd}                      |           d S )Nr2   rA   c                 F    t           j        t          t          f          S N)rC   r%   r   r   rD   s   r>   connected_or_closedz5ClientConnection.connect.<locals>.connected_or_closed   s     dk,?+NOOOr@   r2   rA   )_loop_until)r=   rU   s   ` r>   connectzClientConnection.connect   sD    	P 	P 	P 	P 	P 	P 	,-----r@   closedwhyc                N    | j         | j                             d|           dS dS )z* Close the Websocket connection.

        Ni  )r;   close)r=   rZ   s     r>   r\   zClientConnection.close   s2     <#LtS))))) $#r@   c                .    |                                   dS )a   Force a round-trip request/reply to the server, sometimes needed to
        avoid race conditions. Mostly useful for testing.

        Outside of test suites, this method hurts performance and should not be
        needed.

        Returns:
           None

        N)_send_request_server_inforD   s    r>   force_roundtripz ClientConnection.force_roundtrip   s     	&&(((((r@   c                     t           j        t                    r)                                  t	                       _        dS d fd}                     |           dS )a6   Execute a blocking loop that runs and executes event callbacks
        until the connection is closed (e.g. by hitting Ctrl-C).

        While this method can be used to run Bokeh application code "outside"
        the Bokeh server, this practice is HIGHLY DISCOURAGED for any real
        use case.

        r2   rA   c                 8    t           j        t                    S rT   )rC   r%   r   rD   s   r>   rY   z2ClientConnection.loop_until_closed.<locals>.closed   s    !$+|<<<r@   NrV   )rC   r%   r   _tell_session_about_disconnectr   rW   )r=   rY   s   ` r>   loop_until_closedz"ClientConnection.loop_until_closed   su     dk#455 	% //111&..DKKK= = = = = =V$$$$$r@   documentr   c                   | j                             d          }|                     |          }|t          d          |j        d         dk    rt          d|j        d         z             |                    |           dS )z Pull a document from the server, overwriting the passed-in document

        Args:
            document : (Document)
              The document to overwrite with server content.

        Returns:
            None

        zPULL-DOC-REQNConnection to server was lostmsgtypeERRORzFailed to pull document: text)r9   create_send_message_wait_for_replyRuntimeErrorheadercontentpush_to_documentr=   rd   msgreplys       r>   pull_doczClientConnection.pull_doc   s     n##N3311#66=>???\)$//:U]6=RRSSS""8,,,,,r@   Message[Any]c                    | j                             d|          }|                     |          }|t          d          |j        d         dk    rt          d|j        d         z             |S )z Push a document to the server, overwriting any existing server-side doc.

        Args:
            document : (Document)
                A Document to push to the server

        Returns:
            The server reply

        zPUSH-DOCNrf   rg   rh   zFailed to push document: ri   )r9   rj   rk   rl   rm   rn   rp   s       r>   push_doczClientConnection.push_doc   st     n##J9911#66=>???\)$//:U]6=RRSSSLr@   r!   c                P    | j         |                                 | _         | j         S )zq Ask for information about the server.

        Returns:
            A dictionary of server attributes.

        )r<   r^   rD   s    r>   request_server_infoz$ClientConnection.request_server_info   s*     $ $ > > @ @D  r@   messagec                \  K   | j         t                              d|           n	 |                    | j                    d {V }t                              d||           nH# t
          $ r;}t                              d|           |                     d           Y d }~nd }~ww xY wd S )Nz-We're disconnected, so not sending message %rzSent %r [%d bytes]z#Error sending message to server: %rzreceived error while sendingrZ   )r;   loginfosenddebugr
   r\   )r=   ry   sentes       r>   send_messagezClientConnection.send_message   s      <HHDgNNNN?$\\$,77777777		.>>>>! ? ? ? 		?CCC 

=
>>>>>>>>#?, ts   <A$ $
B).1B$$B)c                  K   t          | j        | j                  }t          |          }	 t	          |d| j        j        g| j                   d {V }t          |          | _	        n# t          $ rI}|                     t          t          j        |j        |j                             d {V  Y d }~d S d }~wt"          $ r%}t$                              d|           Y d }~nd }~ww xY w| j	        6|                     t          t          j        d d                     d {V  d S |                     t-                                 d {V  d S )Nbokeh)subprotocolsr0   zFailed to connect to server: %rzSocket invalid.)r   r5   r7   r   r   r6   tokenr8   r   r;   r   _transition_to_disconnectedr   r   
HTTP_ERRORcodery   	Exceptionr|   r}   NETWORK_ERROR_transitionr   )r=   formatted_urlrequestsocketr   s        r>   _connect_asynczClientConnection._connect_async  s     249doNNm,,	;,WGT]M`Catx  uK  L  L  L  L  L  L  L  L  LF;FCCDLL 	 	 	22<@VXYX^`a`i3j3jkkkkkkkkkFFFFF 	; 	; 	;HH6::::::::	; <22<@Y[_ar3s3sttttttttttt""#7#9#9:::::::::::s#   =A+ +
C+5>B99C+C&&C+c                  K   |                                   d {V }|6|                     t          t          j        dd                     d {V  d S |j        dk    r5t                              d           | j        	                    |           nt                              d|           | 
                                 d {V  d S )N  Internal server error.	PATCH-DOCz"Got PATCH-DOC, applying to sessionzIgnoring %r)_pop_messager   r   r   r   rg   r|   r   r6   _handle_patch_nextr=   ry   s     r>   _handle_messagesz!ClientConnection._handle_messages,  s      ))++++++++?22<@VX[]u3v3vwwwwwwwwwww+--		>???++G4444		-111**,,r@   	predicateCallable[[], bool]c                    || _         	 | j                            | j                   | j                                         d S # t
          $ r |                     d           Y d S w xY w)Nzuser interruption)r'   r&   add_callbackr   startKeyboardInterruptr\   )r=   r   s     r>   rW   zClientConnection._loop_until9  sz     )	, J##DJ///J  	, 	, 	,JJ*++++++	,s   8A A&%A&c                  K   | j         k|                                  rWt                              d| j        j        j        | j         j                   d | _         | j                                         d S t                              d| j        j        j        z              | j                            |            d {V  d S )Nz4Stopping client loop in state %s due to True from %szRunning state )	r'   r|   r   r%   	__class____name__r&   stoprunrD   s    r>   r   zClientConnection._nextD  s       ,1F1F1H1H,IILk+4d6K6TV V V$(D!JOO4II&)>)GGHHH+//$'''''''''''r@   Message[Any] | Nonec                8  K   	 | j         d S d }	 | j                                          d {V }n2# t          $ r%}t                              d|           Y d }~nd }~ww xY w|t                              d           d S 	 | j                            |           d {V }|t                              d|z             |S nW# t          t          t          f$ r=}t                              d|d           |                     d           Y d }~nd }~ww xY w)	NTzError reading from socket %rzConnection closed by serverzReceived message %rz%r)exc_infoz!error parsing message from serverr{   )r;   read_messager   r|   r   r}   r:   consumer   r   r   errorr\   )r=   fragmentr   ry   s       r>   r   zClientConnection._pop_messageO  sr     	D|#t H=!%!:!:!<!<<<<<<< = = =		8!<<<<<<<<= 6777tD $ 6 6x @ @@@@@@@&II3g=>>>"N ' !-A D D D		$D	111

B
CCCCCCCCD+	Ds-   0 
AAAA C D3DDc                    t          |j        d                    _        g d fd} j                            ||           d fd
}                     |           d fd}                     |           j        S )Nmsgidry   rt   send_result
list[None]r2   r3   c                l   K                        |            d {V }|                    |           d S rT   )r   append)ry   r   resultr=   s      r>   handle_messagezEClientConnection._send_message_wait_for_reply.<locals>.handle_messagen  sF      ,,W55555555Fv&&&&&r@   rA   c                 @    t                    dk    p
 j        k    S )Nr   )lenr%   )r=   r   waiters   r>    have_send_result_or_disconnectedzWClientConnection._send_message_wait_for_reply.<locals>.have_send_result_or_disconnecteds  s"    {##a'@4;&+@@r@   c                 ,     j         k    pj        d uS rT   )r%   rr   )r=   r   s   r>   have_reply_or_disconnectedzQClientConnection._send_message_wait_for_reply.<locals>.have_reply_or_disconnectedw  s    ;&(DFL,DDr@   )ry   rt   r   r   r2   r3   rV   )r   rm   r%   r&   r   rW   rr   )r=   ry   r   r   r   r   r   s   `    @@r>   rk   z-ClientConnection._send_message_wait_for_replyi  s    "7>'#:;;"$	' 	' 	' 	' 	' 	' 	
EEE	A 	A 	A 	A 	A 	A 	A 	A9:::	E 	E 	E 	E 	E 	E 	E3444|r@   
session_idr   eventr   c                ~    | j                             d|g          }| j                            | j        |           d S )Nr   )r9   rj   r&   r   r   )r=   r   r   rq   s       r>   _send_patch_documentz%ClientConnection._send_patch_document}  s<    n##K%99
 1377777r@   c                    | j                             d          }|                     |          }|t          d          |j        S )NzSERVER-INFO-REQz<Did not get a reply to server info request before disconnect)r9   rj   rk   rl   rn   )r=   rq   rr   s      r>   r^   z*ClientConnection._send_request_server_info  sG    n##$56611#66=]^^^}r@   c                J    | j         r| j                                          d S d S rT   )r6   _notify_disconnectedrD   s    r>   rb   z/ClientConnection._tell_session_about_disconnect  s0    = 	1M..00000	1 	1r@   	new_statec                   K   t                               d|j        j                    || _        |                                  d {V  d S )Nztransitioning to state )r|   r   r   r   r%   r   )r=   r   s     r>   r   zClientConnection._transition  sT      		JI,?,HJJKKKjjllr@   	dis_stater   c                h   K   |                                   |                     |           d {V  d S rT   )rb   r   )r=   r   s     r>   r   z,ClientConnection._transition_to_disconnected  sD      ++---y)))))))))))r@   c                v  K   |                                   d {V }|rQ|j        dk    rFt                              d|           |                     t                                 d {V  d S |6|                     t          t          j	        dd                     d {V  d S t          d|d          )NACKz	Received r   r   z instead of ACK)r   rg   r|   r   r   r   r   r   r   r   r   r   s     r>   _wait_for_ackzClientConnection._wait_for_ack  s      ))++++++++ 	Hw%//II-'--...""#6#8#899999999999_22<@VX[]u3v3vwwwwwwwwwww FG F F FGGGr@   )NNr(   )r)   r"   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   rV   )r2   r	   )r2   r+   )r2   rI   )r2   rL   )r2   r3   )rY   )rZ   r+   r2   r3   )rd   r   r2   r3   )rd   r   r2   rt   )r2   r!   )ry   rt   r2   r3   )r   r   r2   r3   )r2   r   )ry   rt   r2   r   )r   r   r   r   r2   r3   )r   r   r2   r3   )r   r   r2   r3   )!r   
__module____qualname____doc____annotations__r?   propertyrE   r,   rH   rK   rN   rQ   rX   r\   r_   rc   rs   rv   rx   r   r   r   rW   r   r   rk   r   r^   rb   r   r   r    r@   r>   r#   r#   L   s          MMMMMM////\`MY! ! ! ! !* < < < X<    X    X ( ( ( X( & & & X& ( ( ( X(. . . .* * * * *) ) ) )% % % %&- - - -(   (	! 	! 	! 	!   B; ; ; ;"   	, 	, 	, 	,	( 	( 	( 	(D D D D4   (8 8 8 8   1 1 1 1   
* * * *H H H H H Hr@   r#   )7r   
__future__r   logging	getLoggerr   r|   typingr   r   r   tornado.httpclientr   r   tornado.ioloopr	   tornado.websocketr
   r   
core.typesr   protocolr   protocol.exceptionsr   r   r   protocol.receiverr   util.stringsr   util.tornador   statesr   r   r   r   r   r   r   	websocketr   rd   r   document.eventsr   protocol.messager    #protocol.messages.server_info_replyr!   r)   r"   __all__r#   r   r@   r>   <module>r      sC    # " " " " " g!! 0 / / / / / / / / / < ; ; ; ; ; ; ; ! ! ! ! ! ! ? ? ? ? ? ? ? ?             N N N N N N N N N N ( ( ( ( ( ( 5 5 5 5 5 5 : : : : : :                  8 7 7 7 7 7 '######666666******@@@@@@&&&&&&QH QH QH QH QH QH QH QHv
    ! ! ! ! !r@   