
    !Yw`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m	Z	  e j
        e          ZdZdZ G d d          ZdS )	    N)futures   )JsonRpcExceptionJsonRpcRequestCancelledJsonRpcInternalErrorJsonRpcMethodNotFoundz2.0z$/cancelRequestc                   t    e Zd Zd dfdZd ZddZddZd Zd	 Zd
 Z	e
d             Zd Zd Zd ZddZdS )Endpointc                  B    t          t          j                              S N)struuiduuid4     6lib/python3.11/site-packages/pylsp_jsonrpc/endpoint.py<lambda>zEndpoint.<lambda>   s    #djllBSBS r      c                     || _         || _        || _        i | _        i | _        t          j        |          | _        dS )a  A JSON RPC endpoint for managing messages sent to/from the client.

        Args:
            dispatcher (dict): A dictionary of method name to handler function.
                The handler functions should return either the result or a callable that will be used to asynchronously
                compute the result.
            consumer (fn): A function that consumes JSON RPC message dicts and sends them to the client.
            id_generator (fn, optional): A function used to generate request IDs.
                Defaults to the string value of :func:`uuid.uuid4`.
            max_workers (int, optional): The number of workers in the asynchronous executor pool.
        )max_workersN)_dispatcher	_consumer_id_generator_client_request_futures_server_request_futuresr   ThreadPoolExecutor_executor_service)self
dispatcherconsumerid_generatorr   s        r   __init__zEndpoint.__init__   sG     &!)')$')$!(!;!T!T!Tr   c                 8    | j                                          d S r   )r   shutdown)r   s    r   r$   zEndpoint.shutdown'   s    '')))))r   Nc                     t                               d||           t          |d}|||d<   |                     |           dS )zSend a JSON RPC notification to the client.

         Args:
             method (str): The method name of the notification to send
             params (any): The payload of the notification
         zSending notification: %s %s)jsonrpcmethodNparams)logdebugJSONRPC_VERSIONr   )r   r'   r(   messages       r   notifyzEndpoint.notify*   sY     			/@@@ '
 
  &GHwr   c                 @   |                                  }t                              d|||           t          ||d}|||d<   t	          j                    }|                    |                     |                     || j        |<   | 	                    |           |S )a  Send a JSON RPC request to the client.

        Args:
            method (str): The method name of the message to send
            params (any): The payload of the message

        Returns:
            Future that will resolve once a response has been received
        z!Sending request with id %s: %s %s)r&   idr'   Nr(   )
r   r)   r*   r+   r   Futureadd_done_callback_cancel_callbackr   r   )r   r'   r(   msg_idr,   request_futures         r   requestzEndpoint.request<   s     ##%%		5vvvNNN '
 

  &GH ))(()>)>v)F)FGGG/=$V,wr   c                       fd}|S )z;Construct a cancellation callback for the given request ID.c                     |                                  r@                    t          di           |                     t	                                 d S d S )Nr/   )	cancelledr-   CANCEL_METHODset_exceptionr   )future
request_idr   s    r   callbackz+Endpoint._cancel_callback.<locals>.callback[   s^    !! @MD*+=>>>$$%<%>%>?????@ @r   r   r   r<   r=   s   `` r   r2   zEndpoint._cancel_callbackY   s/    	@ 	@ 	@ 	@ 	@ 	@ r   c           	      `   d|vs|d         t           k    rt                              d|           dS d|vrLt                              d|           |                     |d         |                    d                     dS d|vr`t                              d|           |                     |d         |                    d	          |                    d
                     dS 	 t                              d|           |                     |d         |d         |                    d                     dS # t          $ rb}t          	                    d|d                    | 
                    t           |d         |                                d           Y d}~dS d}~wt          $ r~ t          	                    d|d                    | 
                    t           |d         t          j        t          j                                                              d           Y dS w xY w)zConsume a JSON RPC message from the client.

        Args:
            message (dict): The JSON RPC message sent by the client
        r&   zUnknown message type %sNr/   z$Handling notification from client %sr'   r(   z Handling response from client %sresulterrorzHandling request from client %sFailed to handle request %s)r&   r/   rA   )r+   r)   warningr*   _handle_notificationget_handle_response_handle_requestr   	exceptionr   to_dict	Exceptionr   ofsysexc_info)r   r,   es      r   consumezEndpoint.consumea   s?    G##wy'9_'L'LKK17;;;FwII<gFFF%%gh&7X9N9NOOOOOW$$II8'BBB!!'$-X1F1FT[H\H\]]]]]		;WEEE$$WT]GH4Ew{{S[G\G\]]]]]#   ;WT]KKK.!$-YY[[            
    ;WT]KKK.!$-14S\^^DDLLNN         s!   (AD; ;
H-AF""BH-,H-c                    |t           k    r|                     |d                    dS 	 | j        |         }n,# t          $ r t                              d|           Y dS w xY w	  ||          }n-# t          $ r  t                              d||           Y dS w xY wt          |          r`t          	                    d|           | j
                            |          }|                    |                     ||                     dS dS )z&Handle a notification from the client.r/   Nz+Ignoring notification for unknown method %sz$Failed to handle notification %s: %sz'Executing async notification handler %s)r9   _handle_cancel_notificationr   KeyErrorr)   rC   rJ   rH   callabler*   r   submitr1   _notification_callback)r   r'   r(   handlerhandler_resultnotification_futures         r   rD   zEndpoint._handle_notification   s8   ]"",,VD\:::F	&v.GG 	 	 	KKEvNNNFF		$WV__NN 	 	 	MM@&&QQQFF	 N## 	_II?PPP"&"8"?"?"O"O11$2M2MfV\2]2]^^^^^	_ 	_s!   8 %A! A!%A1 1&BBc                       fd}|S )z;Construct a notification callback for the given request ID.c                     	 |                                   t                              d           d S # t          $ r  t                              d           Y d S w xY w)Nz-Successfully handled async notification %s %sz)Failed to handle async notification %s %s)r@   r)   r*   rJ   rH   )r;   r'   r(   s    r   r=   z1Endpoint._notification_callback.<locals>.callback   st    [		I6SYZZZZZ [ [ [I6SYZZZZZZ[s   05 &AAr   )r'   r(   r=   s   `` r   rU   zEndpoint._notification_callback   s/    	[ 	[ 	[ 	[ 	[ 	[ r   c                     | j                             |d          }|st                              d|           dS |                                rt                              d|           dS dS )z-Handle a cancel notification from the client.Nz6Received cancel notification for unknown message id %szCancelled request with id %s)r   popr)   rC   cancelr*   )r   r3   r4   s      r   rQ   z$Endpoint._handle_cancel_notification   sx    599&$GG 	KKPRXYYYF   "" 	>II4f=====	> 	>r   c                    	 | j         |         }n'# t          $ r}t          j        |          |d}~ww xY w ||          }t	          |          rit
                              d|           | j                            |          }|| j	        |<   |
                    |                     |                     dS t          |t          j                  rOt
                              d|           || j	        |<   |
                    |                     |                     dS t
                              d|           |                     t           ||d           dS )z!Handle a request from the client.Nz"Executing async request handler %sz&Request handler is already a future %sz/Got result from synchronous request handler: %s)r&   r/   r@   )r   rR   r   rK   rS   r)   r*   r   rT   r   r1   _request_callback
isinstancer   r0   r   r+   )r   r3   r'   r(   rV   rN   rW   r4   s           r   rG   zEndpoint._handle_request   sm   	:&v.GG 	: 	: 	:'*6229	: !N## 	II:NKKK!3::>JJN3AD(0,,T-C-CF-K-KLLLLL77 
	II>OOO3AD(0,,T-C-CF-K-KLLLLLIIGXXXNN*(      s    
4/4c                       fd}|S )z6Construct a request callback for the given request ID.c                 j   j                             d            |                                 r!|                     t	                                 t
          d}	 |                                 |d<   n# t          $ r<}t          	                    d           |
                                |d<   Y d }~nhd }~wt          $ rX t          	                    d           t          j        t          j                              
                                |d<   Y nw xY w                    |           d S )N)r&   r/   r@   rB   rA   )r   r\   r8   r:   r   r+   r@   r   r)   rH   rI   rJ   r   rK   rL   rM   r   )r;   r,   rN   r<   r   s      r   r=   z,Endpoint._request_callback.<locals>.callback   sB   (,,Z>>>!! @$$%<%>%>??? +  G
U$*MMOO!!# / / /;ZHHH#$99;;       U U U;ZHHH#7#:3<>>#J#J#R#R#T#T   U NN7#####s   A5 5
D?2B66A"DDr   r>   s   `` r   r_   zEndpoint._request_callback   s)    	$ 	$ 	$ 	$ 	$ 	$. r   c                 j   | j                             |d          }|st                              d|           dS |Et                              d||           |                    t          j        |                     dS t                              d||           |                    |           dS )z"Handle a response from the client.Nz*Received response to unknown message id %sz)Received error response to message %s: %sz"Received result for message %s: %s)	r   r\   r)   rC   r*   r:   r   	from_dict
set_result)r   r3   r@   rA   r4   s        r   rF   zEndpoint._handle_response   s    599&$GG 	KKDfMMMFIIA65QQQ(()9)CE)J)JKKKF		6GGG!!&)))))r   r   )NN)__name__
__module____qualname__r"   r$   r-   r5   r2   rO   rD   staticmethodrU   rQ   rG   r_   rF   r   r   r   r
   r
      s        :S:Sab U U U U(* * *       $   :  ! ! !F_ _ _.   \
> 
> 
>  4  6* * * * * *r   r
   )loggingr   rL   
concurrentr   
exceptionsr   r   r   r   	getLoggerrf   r)   r+   r9   r
   r   r   r   <module>rn      s      



      F F F F F F F F F F F F g!!!d* d* d* d* d* d* d* d* d* d*r   