a
    ø£Bev  ã                   @   sØ   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„ deƒZG dd„ deƒZG d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                       sN   e Zd ZdZdZeejdd�Zee	dd�Z
dd„ Z‡ fdd	„Zd
d„ Z‡  ZS )ÚLspStdIoBasezGNon-blocking, queued base for communicating with stdio Language ServersNzthe stream to read/write©Úhelpzqueue to get/putc                 C   s   d  | jj| j¡S )Nz<{}(parent={})>)ÚformatÚ	__class__Ú__name__Úparent©Úself© r   úT/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/jupyter_lsp/stdio.pyÚ__repr__&   s    zLspStdIoBase.__repr__c                    s0   t ƒ jf i |¤Ž | j d| ¡ tdd�| _d S )Nz%s initializedr   )Úmax_workers)ÚsuperÚ__init__ÚlogÚdebugr   Úexecutor)r   Úkwargs©r   r   r   r   )   s    zLspStdIoBase.__init__c                 C   s   | j  ¡  | j d| ¡ d S )Nz	%s closed)ÚstreamÚcloser    r!   r   r   r   r   r&   .   s    
zLspStdIoBase.close)r   Ú
__module__Ú__qualname__Ú__doc__r"   r   ÚioÚ	RawIOBaser%   r
   Úqueuer   r   r&   Ú__classcell__r   r   r$   r   r      s   ÿr   c                   @   s®   e Zd ZdZedd�jdd�Zeddd�jdd�Zeddd�jdd�Ze	d	ƒd
d„ ƒZ
dd„ Zdd„ Zddœdd„Zdeee dœdd„Zedœdd„Zeedœdd„ƒZdS )ÚLspStdIoReaderzŒLanguage 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                 C   s   t jdkrdS | jd S )NÚntgš™™™™™¹?é   )ÚosÚnameÚmin_waitr   r   r   r   Ú_default_max_wait>   s    z LspStdIoReader._default_max_waitc                 Ã   sN   | j jrdS t| jd | jƒ| _zt | j¡I dH  W n tyH   Y n0 dS )z'Simple exponential backoff for sleepingNr2   )r%   ÚclosedÚminÚ	next_waitr0   ÚasyncioÚsleepÚ	Exceptionr   r   r   r   r;   B   s    zLspStdIoReader.sleepc                 C   s   | j | _dS )zReset the wait timeN)r5   Úwaitr   r   r   r   ÚwakeL   s    zLspStdIoReader.wakeN©Úreturnc              
   Ã   s¨   t | jƒ | jjs¤d}zF|  ¡ I dH }|s>|  ¡ I dH  W q
n|  ¡  t ¡  | j	j
|¡ W q
 ty  } z,| j d| ||¡ |  ¡ I dH  W Y d}~q
d}~0 0 q
dS )z.Read from a Language Server until it is closedNz$%s couldn't enqueue message: %s (%s))r   r%   r7   Úread_oner;   r>   r	   ÚcurrentZadd_callbackr,   Ú
put_nowaitr<   r    Ú	exception)r   ÚmessageÚer   r   r   ÚreadP   s    
ÿzLspStdIoReader.readéè  éÈ   )Úlengthr@   c              
   Ã   sÒ   d}g }d}||k rŒt |ƒ|k rŒ|dkrŒd}z| j || ¡}W n tyR   Y n0 |du rt|d8 }|  ¡ I dH  q|t |ƒ7 }| |¡ q|rÎd |¡}t |ƒ|krÎ| 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   ó    z%Readout and content-length mismatch: z vs z;remaining empties: z; remaining parts: )	Úlenr%   rG   ÚOSErrorr;   ÚappendÚjoinr    Úwarning)r   rJ   Z	max_partsZmax_emptiesÚrawZ	raw_partsZreceived_sizeÚpartr   r   r   Ú_read_contentf   s4    
ÿÿÿzLspStdIoReader._read_contentc                 Ã   sœ   d}t ƒ }t|  ¡ ƒI dH }|r˜|rJ| ¡ rJ| |¡ t|  ¡ ƒI dH }q t| dd¡ƒ}|r˜| j|d�I dH }|durˆ| d¡ ¡ }n| j	 
d| |¡ |S )zRead a single messageÚ Nzcontent-lengthÚ0)rJ   úutf-8z&%s failed to read message of length %s)r   r   Ú	_readlineÚstripÚ
parse_lineÚintÚgetrS   Údecoder    rP   )r   rE   ÚheadersÚlineÚcontent_lengthrQ   r   r   r   rA   “   s$    
ýzLspStdIoReader.read_onec                 C   s0   z| j  ¡  d¡ ¡ W S  ty*   Y dS 0 dS )z(Read a line (or immediately return None)rV   rT   N)r%   Úreadliner\   rX   rM   r   r   r   r   rW   ®   s    zLspStdIoReader._readline)rH   rI   )r   r'   r(   r)   r   Útagr0   r5   r9   r   r6   r;   r>   rG   rZ   r   ÚbytesrS   r   rA   r   rW   r   r   r   r   r.   3   s"   

 ÿþ-r.   c                   @   s0   e Zd ZdZddœdd„Zeddœdd„ƒZdS )ÚLspStdIoWriterzLanguage Server stdio WriterNr?   c                 Ã   s–   | j js’| j ¡ I dH }zjz8| d¡}d t|ƒ|¡}t|  | d¡¡ƒI dH  W n" t	yt   | j
 d| |¡ Y n0 W | j ¡  q | j ¡  0 q dS )z*Write to a Language Server until it closesNrV   zContent-Length: {}

{}z%s couldn't write message: %s)r%   r7   r,   r[   Úencoder   rL   r   Ú
_write_oner<   r    rD   Ú	task_done)r   rE   ÚbodyÚresponser   r   r   Úwriteº   s    
zLspStdIoWriter.writec                 C   s   | j  |¡ | j  ¡  d S )N)r%   ri   Úflush)r   rE   r   r   r   re   Ç   s    zLspStdIoWriter._write_one)r   r'   r(   r)   ri   r   re   r   r   r   r   rc   ·   s   rc   )r)   r:   r*   r3   Úconcurrent.futuresr   Útypingr   r   r   Ztornado.concurrentr   Ztornado.genr   Ztornado.httputilr   Ztornado.ioloopr	   Ztornado.queuesr
   Z	traitletsr   r   r   Ztraitlets.configr   Znon_blockingr   r   r.   rc   r   r   r   r   Ú<module>   s"   
 