a
    ?Df:?                     @  s@  d Z ddlmZ ddlZe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Z5G dd dZ6e   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                   @  s  e Zd ZU dZded< ded< ded< d[d
ddddddddZeddddZeddddZeddddZ	eddddZ
edddd Zeddd!d"Zddd#d$Zd\ddd&d'd(Zddd)d*Zddd+d,Zd-dd.d/d0Zd-d1d.d2d3Zd4dd5d6Zd1dd7d8d9Zddd:d;Zddd<d=Zd>dd?d@dAZdddBdCZdDddEdFZd1dDd7dGdHZdIdJddKdLdMZd4ddNdOZdddPdQZdddRdSdTZdUddVdWdXZdddYdZZ dS )]r"   z; A low-level class used to connect to a Bokeh server.

    r   _stater   _loopzCallable[[], bool] | None_until_predicateN  @r!   strzIOLoop | Nonezdict[str, str] | NoneintNone)sessionwebsocket_urlio_loop	argumentsmax_message_sizereturnc                 C  s^   || _ || _|| _|| _t | _t| j| _d| _t	 | _
|durF|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-   r.    r9   d/nfs/NAS7/SABIOD/METHODE/ermites/ermites_venv/lib/python3.9/site-packages/bokeh/client/connection.py__init__U   s    zClientConnection.__init__boolr/   c                 C  s   t | jtS )zg Whether we've connected the Websocket and have exchanged initial
        handshake messages.

        )
isinstancer#   r   r8   r9   r9   r:   	connectedj   s    zClientConnection.connectedc                 C  s   | j S )z2 The Tornado ``IOLoop`` this connection is using. )r$   r?   r9   r9   r:   r,   r   s    zClientConnection.io_loopc                 C  s   | j S )z1 The URL of the websocket this Connection is to. )r0   r?   r9   r9   r:   urlw   s    zClientConnection.urlzErrorReason | Nonec                 C  s   t | jtsdS | jjS )zX The reason of the connection loss encoded as a ``DISCONNECTED.ErrorReason`` enum value N)r>   r#   r   error_reasonr?   r9   r9   r:   rB   |   s    zClientConnection.error_reasonz
int | Nonec                 C  s   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   )r>   r#   r   
error_coder?   r9   r9   r:   rC      s    zClientConnection.error_codec                 C  s   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.

         )r>   r#   r   error_detailr?   r9   r9   r:   rE      s    zClientConnection.error_detailc                   s    dd fdd}  | d S )Nr<   r=   c                     s   t  jttfS N)r>   r#   r   r   r9   r?   r9   r:   connected_or_closed   s    z5ClientConnection.connect.<locals>.connected_or_closed)_loop_until)r8   rG   r9   r?   r:   connect   s    zClientConnection.connectclosed)whyr/   c                 C  s   | j dur| j d| dS )z* Close the Websocket connection.

        Ni  )r6   close)r8   rK   r9   r9   r:   rL      s    
zClientConnection.closec                 C  s   |    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_infor?   r9   r9   r:   force_roundtrip   s    z ClientConnection.force_roundtripc                   s>   t  jtr   t  _ndd fd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.

        r<   r=   c                     s   t  jtS rF   )r>   r#   r   r9   r?   r9   r:   rJ      s    z2ClientConnection.loop_until_closed.<locals>.closedN)r>   r#   r   _tell_session_about_disconnectr   rH   )r8   rJ   r9   r?   r:   loop_until_closed   s
    	
z"ClientConnection.loop_until_closedr   )documentr/   c                 C  sX   | j d}| |}|du r(tdn,|jd dkrJtd|jd  n
|| 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)r4   create_send_message_wait_for_replyRuntimeErrorheadercontentZpush_to_documentr8   rQ   msgreplyr9   r9   r:   pull_doc   s    

zClientConnection.pull_docMessage[Any]c                 C  sT   | j d|}| |}|du r*tdn&|jd dkrLtd|jd  n|S d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-DOCNrR   rS   rT   zFailed to push document: rU   )r4   rV   rW   rX   rY   rZ   r[   r9   r9   r:   push_doc   s    

zClientConnection.push_docr    c                 C  s   | j du r|  | _ | j S )zq Ask for information about the server.

        Returns:
            A dictionary of server attributes.

        N)r7   rM   r?   r9   r9   r:   request_server_info   s    

z$ClientConnection.request_server_info)messager/   c              
     s~   | j d u rtd| nbz$|| j I d H }td|| W n< tyx } z$td| | jdd W Y d }~n
d }~0 0 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rK   )r6   loginfosenddebugr	   rL   )r8   rb   senter9   r9   r:   send_message   s    
"zClientConnection.send_messagec              
     s   t | j| j}t|}z,t|d| jjg| jdI d H }t|| _	W nr t
y } z,| ttj|j|jI d H  W Y d }~d S d }~0  ty } ztd| W Y d }~n
d }~0 0 | j	d u r| ttjd dI d H  n| t I d H  d S )NZbokeh)Zsubprotocolsr.   zFailed to connect to server: %rzSocket invalid.)r   r0   r2   r   r
   r1   tokenr3   r   r6   r   _transition_to_disconnectedr   r   
HTTP_ERRORcoderb   	Exceptionrd   re   ZNETWORK_ERROR_transitionr   )r8   Zformatted_urlrequestsocketri   r9   r9   r:   _connect_async  s    "
zClientConnection._connect_asyncc                   sr   |   I d H }|d u r2| ttjddI d H  n<|jdkrTtd | j	| ntd| | 
 I d H  d S )N  Internal server error.	PATCH-DOCz"Got PATCH-DOC, applying to sessionzIgnoring %r)_pop_messagerl   r   r   rm   rS   rd   rg   r1   Z_handle_patch_nextr8   rb   r9   r9   r:   _handle_messages,  s    

z!ClientConnection._handle_messageszCallable[[], bool])	predicater/   c                 C  sD   || _ z| j| j | j  W n ty>   | d Y n0 d S )Nzuser interruption)r%   r$   add_callbackrx   startKeyboardInterruptrL   )r8   r{   r9   r9   r:   rH   9  s    zClientConnection._loop_untilc                   sh   | j d ur>|   r>td| jjj| j j d | _ | j  d S td| jjj  | j| I d H  d S )Nz4Stopping client loop in state %s due to True from %szRunning state )	r%   rd   rg   r#   	__class____name__r$   stoprunr?   r9   r9   r:   rx   D  s    
zClientConnection._nextzMessage[Any] | Nonec              
     s   | j d u rd S d }z| j  I d H }W n0 tyV } ztd| W Y d }~n
d }~0 0 |d u rntd d S z2| j|I d H }|d urtd|  |W S W q  tt	t
fy } z(tjd|dd | jdd W Y d }~q d }~0 0 q d S )	NzError reading from socket %rzConnection closed by serverzReceived message %rz%rT)exc_infoz!error parsing message from serverrc   )r6   Zread_messagero   rd   rg   re   r5   consumer   r   r   errorrL   )r8   fragmentri   rb   r9   r9   r:   rw   O  s$    
"

zClientConnection._pop_messagec                   s   t |jd  _g dddd fdd} j|| dd	 fd
d} | dd	 fdd} | jS )Nmsgidr_   z
list[None]r)   )rb   send_resultr/   c                   s     | I d H }|| d S rF   )rj   append)rb   r   resultr?   r9   r:   handle_messagen  s    zEClientConnection._send_message_wait_for_reply.<locals>.handle_messager<   r=   c                     s   t dkp jkS )Nr   )lenr#   r9   r8   r   waiterr9   r:    have_send_result_or_disconnecteds  s    zWClientConnection._send_message_wait_for_reply.<locals>.have_send_result_or_disconnectedc                     s    j kpjd uS rF   )r#   r]   r9   )r8   r   r9   r:   have_reply_or_disconnectedw  s    zQClientConnection._send_message_wait_for_reply.<locals>.have_reply_or_disconnected)r   rY   r#   r$   r|   rH   r]   )r8   rb   r   r   r   r9   r   r:   rW   i  s    

z-ClientConnection._send_message_wait_for_replyr   r   )
session_ideventr/   c                 C  s$   | j d|g}| j| j| d S )Nrv   )r4   rV   r$   r|   rj   )r8   r   r   r\   r9   r9   r:   _send_patch_document}  s    z%ClientConnection._send_patch_documentc                 C  s,   | j d}| |}|d u r&td|jS )NzSERVER-INFO-REQz<Did not get a reply to server info request before disconnect)r4   rV   rW   rX   rZ   )r8   r\   r]   r9   r9   r:   rM     s
    
z*ClientConnection._send_request_server_infoc                 C  s   | j r| j   d S rF   )r1   Z_notify_disconnectedr?   r9   r9   r:   rO     s    z/ClientConnection._tell_session_about_disconnect)	new_stater/   c                   s,   t d|jj  || _|  I d H  d S )Nztransitioning to state )rd   rg   r   r   r#   rx   )r8   r   r9   r9   r:   rp     s    zClientConnection._transitionr   )	dis_stater/   c                   s   |    | |I d H  d S rF   )rO   rp   )r8   r   r9   r9   r:   rl     s    z,ClientConnection._transition_to_disconnectedc                   sx   |   I d H }|r@|jdkr@td| | t I d H  n4|d u rd| ttj	ddI d H  nt
d|dd S )NZACKz	Received rt   ru   z instead of ACK)rw   rS   rd   rg   rp   r   rl   r   r   rm   r   ry   r9   r9   r:   _wait_for_ack  s    zClientConnection._wait_for_ack)NNr&   )rJ   )!r   
__module____qualname____doc____annotations__r;   propertyr@   r,   rA   rB   rC   rE   rI   rL   rN   rP   r^   r`   ra   rj   rs   rz   rH   rx   rw   rW   r   rM   rO   rp   rl   r   r9   r9   r9   r:   r"   L   sN   
  	!r"   )7r   
__future__r   logging	getLoggerr   rd   typingr   r   r   Ztornado.httpclientr   r   Ztornado.ioloopr   Ztornado.websocketr	   r
   Z
core.typesr   protocolr   Zprotocol.exceptionsr   r   r   Zprotocol.receiverr   Zutil.stringsr   Zutil.tornador   Zstatesr   r   r   r   r   r   r   Z	websocketr   rQ   r   Zdocument.eventsr   Zprotocol.messager   Z#protocol.messages.server_info_replyr    r*   r!   __all__r"   r9   r9   r9   r:   <module>   s4   
$	  ]