
    Mhw                         d Z ddlZddlZddl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 dd	lmZ dd
lmZmZmZ ddlmZ ddlmZ  G d de          Z G d de          Z G d de          ZdS )a   Language Server stdio-mode readers

Parts of this code are derived from:

> https://github.com/palantir/python-jsonrpc-server/blob/0.2.0/pyls_jsonrpc/streams.py#L83   # noqa
> https://github.com/palantir/python-jsonrpc-server/blob/45ed1931e4b2e5100cc61b3992c16d6f68af2e80/pyls_jsonrpc/streams.py  # noqa
> > MIT License   https://github.com/palantir/python-jsonrpc-server/blob/0.2.0/LICENSE
> > Copyright 2018 Palantir Technologies, Inc.
    N)ThreadPoolExecutor)ListOptionalText)run_on_executor)convert_yielded)HTTPHeaders)IOLoop)Queue)FloatInstancedefault)LoggingConfigurable   )make_non_blockingc                   p     e Zd ZdZdZ eej        d          Z ee	d          Z
d Z fdZd Z xZS )	LspStdIoBasezGNon-blocking, queued base for communicating with stdio Language ServersNzthe stream to read/writehelpzqueue to get/putc                 L    d                     | j        j        | j                  S )Nz<{}(parent={})>)format	__class____name__parentselfs    Q/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/jupyter_lsp/stdio.py__repr__zLspStdIoBase.__repr__'   s     ''(?MMM    c                      t                      j        di | | j                            d|            t	          d          | _        d S )Nz%s initializedr   )max_workers )super__init__logdebugr   executor)r   kwargsr   s     r   r$   zLspStdIoBase.__init__*   sM    ""6"""'...*q999r   c                 n    | j                                          | j                            d|            d S )Nz	%s closed)streamcloser%   r&   r   s    r   r+   zLspStdIoBase.close/   s2    {D)))))r   )r   
__module____qualname____doc__r'   r   io	RawIOBaser*   r   queuer   r$   r+   __classcell__)r   s   @r   r   r      s        QQHX
5  F HU!3444EN N N: : : : :
* * * * * * *r   r   c                   Z   e Zd ZdZ ed                              d          Z edd                              d          Z edd                              d          Z e	d	          d
             Z
d Zd ZddZ	 ddedee         fdZdefdZedefd            ZdS )LspStdIoReaderzLanguage Server stdio Reader

    Because non-blocking (but still synchronous) IO is used, rudimentary
    exponential backoff is used.
    z#maximum time to wait on idle streamr   T)configg?z#minimum time to wait on idle streamz next time to wait on idle streammax_waitc                 :    t           j        dk    rdn	| j        dz  S )Nntg?   )osnamemin_waitr   s    r   _default_max_waitz LspStdIoReader._default_max_wait?   s    gooss4=1+<<r   c                    K   | j         j        rdS t          | j        dz  | j                  | _        	 t          j        | j                   d{V  dS # t          $ r Y dS w xY w)z'Simple exponential backoff for sleepingNr9   )r*   closedmin	next_waitr6   asynciosleep	Exceptionr   s    r   rC   zLspStdIoReader.sleepC   s      ; 	FT^a/??	-/////////// 	 	 	DD	s   A 
A#"A#c                     | j         | _        dS )zReset the wait timeN)r<   waitr   s    r   wakezLspStdIoReader.wakeM   s    M			r   returnNc                   K   t          | j                   | j        j        sd}	 |                                  d{V }|s|                                  d{V  F|                                  t          j                                        | j	        j
        |           nN# t          $ rA}| j                            d| ||           |                                  d{V  Y d}~nd}~ww xY w| j        j        dS dS )z.Read from a Language Server until it is closedNz$%s couldn't enqueue message: %s (%s))r   r*   r?   read_onerC   rG   r
   currentadd_callbackr1   
put_nowaitrD   r%   	exception)r   messagees      r   readzLspStdIoReader.readQ   s@     $+&&&+$ 	#G# $//////  **,,&&&&&&&IIKKK  --dj.CWMMMM # # #"":D'1   jjll""""""""""""	# +$ 	# 	# 	# 	# 	#s   6B# AB# #
C.-7C))C.     lengthc           
      @  K   d}g }d}||k     rt          |          |k     r|dk    rd}	 | j                            ||z
            }n# t          $ r Y nw xY w| |dz  }|                                  d{V  r|t          |          z  }|                    |           ||k     rt          |          |k     r|dk    |r[d                    |          }t          |          |k    r3| j                            dt          |           d| d| d|            |S )	a  Read the full length of the message unless exceeding max_parts or
           max_empties empty reads occur.

        See https://github.com/jupyter-lsp/jupyterlab-lsp/issues/450

        Crucial docs or read():
            "If the argument is positive, and the underlying raw
             stream is not interactive, multiple raw reads may be issued
             to satisfy the byte count (unless EOF is reached first)"

        Args:
           - length: the content length
           - max_parts: prevent absurdly long messages (1000 parts is several MBs):
             1 part is usually sufficient but not enough for some long
             messages 2 or 3 parts are often needed.
        Nr   r   r   z%Readout and content-length mismatch: z vs z;remaining empties: z; remaining parts: )	lenr*   rQ   OSErrorrC   appendjoinr%   warning)r   rT   	max_partsmax_emptiesraw	raw_partsreceived_sizeparts           r   _read_contentzLspStdIoReader._read_contentg   s     & !#	f$$Y))C)CVWD{''(>??   |q jjll"""""""SYY&MT""" f$$Y))C)CVW  	((9%%C3xx6!!  VCHH V V& V V*5V VJSV V  
 
s   A	 	
AAc                 Z  K   d}t                      }t          |                                            d{V }|r|rf|                                rR|                    |           t          |                                            d{V }|r|                                Rt          |                    dd                    }|rb|                     |           d{V }|(|                    d                                          }n| j	        
                    d| |           |S )zRead a single message Nzcontent-length0)rT   utf-8z&%s failed to read message of length %s)r	   r   	_readlinestrip
parse_lineintgetra   decoder%   rZ   )r   rO   headerslinecontent_lengthr]   s         r   rJ   zLspStdIoReader.read_one   sN     --$T^^%5%566666666 	 ?4::<< ?""4(((,T^^-=-=>>>>>>>>  ?4::<< ? !-=s!C!CDDN 	 ..n.EEEEEEEE?!jj117799GGH$$@&   r   c                     	 | j                                                             d                                          S # t          $ r Y dS w xY w)z(Read a line (or immediately return None)re   rc   )r*   readlinerk   rg   rW   r   s    r   rf   zLspStdIoReader._readline   sW    	;''))0099??AAA 	 	 	22	s   =A   
AArH   N)rR   rS   )r   r,   r-   r.   r   tagr6   r<   rA   r   r=   rC   rG   rQ   ri   r   bytesra   r   rJ   r   rf   r"   r   r   r4   r4   4   s]         u?@@@DDDDQQHuT EFFFJJRVJWWHd!CDDDHHPTHUUIWZ= = =  " " "# # # #. 8;+ ++	%+ + + +Z    6 4    _  r   r4   c                   2    e Zd ZdZddZedd            ZdS )LspStdIoWriterzLanguage Server stdio WriterrH   Nc                 2  K   | j         j        s| j                                         d{V }	 |                    d          }d                    t          |          |          }t          |                     |                    d                               d{V  n,# t          $ r | j
                            d| |           Y nw xY w| j                                         n# | j                                         w xY w| j         j        dS dS )z*Write to a Language Server until it closesNre   zContent-Length: {}

{}z%s couldn't write message: %s)r*   r?   r1   rj   encoder   rV   r   
_write_onerD   r%   rN   	task_done)r   rO   bodyresponses       r   writezLspStdIoWriter.write   s8     +$ 		' JNN,,,,,,,,G'~~g..9@@TGTT%doohoog6N6N&O&OPPPPPPPPPP T T T""#BD(SSSSST 
$$&&&&
$$&&&& +$ 		' 		' 		' 		' 		's*   A3B$ #C* $&C
C* CC* *Dc                 l    | j                             |           | j                                          d S )N)r*   r|   flush)r   rO   s     r   rx   zLspStdIoWriter._write_one   s2    '"""r   rq   )r   r,   r-   r.   r|   r   rx   r"   r   r   ru   ru      sN        &&' ' ' '    _  r   ru   )r.   rB   r/   r:   concurrent.futuresr   typingr   r   r   tornado.concurrentr   tornado.genr   tornado.httputilr	   tornado.ioloopr
   tornado.queuesr   	traitletsr   r   r   traitlets.configr   non_blockingr   r   r4   ru   r"   r   r   <module>r      s     				 				 1 1 1 1 1 1 ' ' ' ' ' ' ' ' ' ' . . . . . . ' ' ' ' ' ' ( ( ( ( ( ( ! ! ! ! ! !             . . . . . . . . . . 0 0 0 0 0 0 + + + + + +* * * * *& * * *.A A A A A\ A A AH    \     r   