Format: application/x-python-code
⬇ Download File (45.1 KB)
   1  o
   2  
   3  ��h��@shdZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
   4  Z
   5  ddlmZm
   6  Z
   7  mZddlmZGdd�de�ZGdd	�d	ee�ZGd
   8  d�de�ZGdd
   9  �d
  10  ej�Zdd�ZGdd�de�ZGdd�de�Ze�Z	Gdd�de�ZGdd�de�ZGdd�de�ZGdd�de�Z Gdd�de!�Z"Gdd�de"�Z#Gd d!�d!e�Z$Gd"d#�d#e�Z%dS)$z�An implementation of the session and presentation layers as used in the Debug
  11  Adapter Protocol (DAP): channels and their lifetime, JSON messages, requests,
  12  responses, and events.
  13  
  14  https://microsoft.github.io/debug-adapter-protocol/overview#base-protocol
  15  �)�annotationsN)�json�log�util)�hide_thread_from_debuggerc� eZdZdZ�fdd�Z�ZS)�JsonIOErrorzDIndicates that a read or write operation on JsonIOStream has failed.csT|�d�}|�dd�}t|�s|durt|�g}t�j|i|��||_	||_dS)N�stream�cause)�pop�len�str�super�__init__r	r
  16  )�self�args�kwargsr	r
  17  ��	__class__��Nc:\Users\shubh\Videos\agent\nova\Lib\site-packages\debugpy/common/messaging.pyrs
  18  
  19  zJsonIOError.__init__��__name__�
  20  __module__�__qualname__�__doc__r�
  21  __classcell__rrrrrsrcr)�NoMoreMessagesz`Indicates that there are no more messages that can be read from or written
  22      to a stream.
  23      cs(t|�r|ndg}t�j|i|��dS)NzNo more messages)rrr�rrrrrrr7szNoMoreMessages.__init__rrrrrr2src@s�eZdZdZdZejZ	ejZ		e
  24  ddd��Ze
  25  ddd��Ze
  26  dd	d
  27  ��Z
  28  ddd�fd
  29  d�Zdd�Zejfdd�Zdd�Zddd�Zddd�Zdd�ZdS)�JsonIOStreamz�Implements a JSON value stream over two byte streams (input and output).
  30  
  31      Each value is encoded as a DAP packet, with metadata headers and a JSON payload.
  32      i����stdiocCs|tjjtjj|�S)zlCreates a new instance that receives messages from sys.stdin, and sends
  33          them to sys.stdout.
  34          )�sys�stdin�buffer�stdout)�cls�namerrr�
  35  from_stdioJszJsonIOStream.from_stdiocCs||j|j|�S)ztCreates a new instance that receives messages from process.stdin, and sends
  36          them to process.stdout.
  37          )r$r")r%�processr&rrr�from_processQszJsonIOStream.from_processNcs@��d�|dur
  38  t��}��dd�}�fdd�}|||||�S)zFCreates a new instance that sends and receives messages over a socket.N�rwbrcs0z��tj�Wn	tyYnw���dS�N)�shutdown�socket�	SHUT_RDWR�	Exception�closer��sockrr�cleanupfs�z)JsonIOStream.from_socket.<locals>.cleanup)�
  39  settimeout�repr�makefile)r%r2r&Z	socket_ior3rr1r�from_socketXs
  40  zJsonIOStream.from_socketcC�dSr+rrrrr�<lambda>o�zJsonIOStream.<lambda>cCs:|durd|�d|��}||_||_||_||_d|_dS)aCreates a new JsonIOStream.
  41  
  42          reader must be a BytesIO-like object, from which incoming messages will be
  43          read by read_json().
  44  
  45          writer must be a BytesIO-like object, into which outgoing messages will be
  46          written by write_json().
  47  
  48          cleanup must be a callable; it will be invoked without arguments when the
  49          stream is closed.
  50  
  51          reader.readline() must treat "
  52  " as the line terminator, and must leave "
  53  "
  54          as is - it must not replace "
  55  " with "
  56  " automatically, as TextIO does.
  57          Nzreader=z	, writer=F)r&�_reader�_writer�_cleanup�_closed)r�reader�writerr&r3rrrros
  58  zJsonIOStream.__init__cCs�|jrdSd|_t�d|j�z.z(z|j��W|j|jur#|j��n
  59  |j|jur0|j��wwW|��WdS|��wtyNt�	d|j�YdSw)z.Closes the stream, the reader, and the writer.NTzClosing {0} message streamz&Error while closing {0} message stream)
  60  r>r�debugr&r<r0r;r=r/�reraise_exception�rrrrr0�s&
  61  �����zJsonIOStream.closecCs|d|j||�S)Nz{0} {1} {2}�r&)r�dir�data�loggerrrr�_log_message��zJsonIOStream._log_messagec
  62  Csjd}	z||��7}Wnty}ztt|�|d��d}~ww|s't|d��|�d�r4|dd�}|Sq)N�T�r	s
  63  r�����)�readliner/rr
  64  �endswith)rr?�line�excrrr�
  65  _read_line�s��
  66  
  67  �zJsonIOStream._read_linecs�|dur|n���}�j}t��j|�}d��fdd�	}g�i}	z|�}Wnty7|r4|d�n�Ynw�|dg7�|dkrCn
  68  |�d	�\}}}	|	||<q!zt|d
  69  �}
  70  d|
  71  krc�jksft	�t	�Wnt
  72  t	fy�ztd��ty�|�YnwYnwt��}|
  73  }|dkr�z|�
  74  |�}
  75  |
  76  s�t�Wnty�}ztt|��d
  77  ��d}~ww��|
  78  �|t|
  79  �8}|dks�|dks�J�d��|d��}z|�d�}Wnty�|�Ynwz|�|�}Wnty�|�Ynw��d|�|S)z�Read a single JSON value from reader.
  80  
  81          Returns JSON value as parsed by decoder.decode(), or raises NoMoreMessages
  82          if there are no more values to be read.
  83          N�cs\|r|d7}|d7}d����d�}d�dd�|D��}tj|g|�R�j|d�|��dS)	Nz
  84  
  85  z{name} -->
  86  {raw_lines}rJ�
  87  �
  88  css�|]}t|�VqdSr+)r5)�.0rOrrr�	<genexpr>���zTJsonIOStream.read_json.<locals>.log_message_and_reraise_exception.<locals>.<genexpr>)r&�	raw_lines)�join�splitrrBr&)�
  89  format_stringrrrX�Z
  90  raw_chunksrrr�!log_message_and_reraise_exception�s���
  91  �zAJsonIOStream.read_json.<locals>.log_message_and_reraise_exceptionTz$Error while reading message headers:rSrJ�:sContent-Lengthrz%Content-Length is missing or invalid:rK�utf-8z-->)rR)�json_decoder_factoryr;�	functools�partialrQr/�	partition�int�
  92  MAX_BODY_SIZE�
  93  ValueError�KeyError�IOErrorr�read�EOFErrorrr
  94  �appendrY�decoderH)r�decoderr?Z	read_liner]�headersrO�key�_�value�lengthZ
  95  body_startZbody_remaining�chunkrP�bodyrr\r�	read_json�s�
  96  ������
  97  ��
  98  ���
  99  �
 100  �
 101  �zJsonIOStream.read_jsonc
 102  
 103  Cs|jrt|d��|dur|n|��}|j}z|�|�}Wnty0|jdt|�tj	d�Ynw|�d�}dt
 104  |��d��d�}||}d	}z#|t
 105  |�kre|�||d��}|dur_||7}|t
 106  |�ksN|��Wnty�}	z|jd|tj
 107  d�t||	d
 108  ��d}	~	ww|�d|�dS)ziWrite a single JSON value into writer.
 109  
 110          Value is written as encoded by encoder.encode().
 111          rKNz<--)rGr_zContent-Length: z
 112  
 113  �asciir)r	r
 114  )r>r�json_encoder_factoryr<�encoder/rHr5rrBr�write�flush�swallow_exceptionr)
 115  rrq�encoderr@rt�headerrFZdata_writtenZwrittenrPrrr�
 116  write_jsons4
 117  �
 118  ���zJsonIOStream.write_jsoncC�t|�j�d|j�d�S�N�(�)��typerr&rCrrr�__repr__3�zJsonIOStream.__repr__)r r+)rrrrrerZJsonDecoderr`ZJsonEncoderrw�classmethodr'r)r7rr0rrArHrQrur~r�rrrrr<s(
 119  
 120  ['rcsfeZdZdZd�fdd�	Z�fdd�Zd
 121  dd	�Zd
 122  d�Zeej	j
 123  �Z
 124  eej	j�Zeej	j�Z[�Z
 125  S)�MessageDicta�A specialized dict that is used for JSON message payloads - Request.arguments,
 126      Response.body, and Event.body.
 127  
 128      For all members that normally throw KeyError when a requested key is missing, this
 129      dict raises InvalidMessageError instead. Thus, a message handler can skip checks
 130      for missing properties, and just work directly with the payload on the assumption
 131      that it is valid according to the protocol specification; if anything is missing,
 132      it will be reported automatically in the proper manner.
 133  
 134      If the value for the requested key is itself a dict, it is returned as is, and not
 135      automatically converted to MessageDict. Thus, to enable convenient chaining - e.g.
 136      d["a"]["b"]["c"] - the dict must consistently use MessageDict instances rather than
 137      vanilla dicts for all its values, recursively. This is guaranteed for the payload
 138      of all freshly received messages (unless and until it is mutated), but there is no
 139      such guarantee for outgoing messages.
 140      Ncs@|dust|t�sJ�|durt���nt��|�||_dSr+)�
 141  isinstance�Messagerr�message)rr��itemsrrrrIszMessageDict.__init__cs.ztt�|��WStyt���YSwr+)�formatrr5r/rr�rCrrrr�Ys
 142  �zMessageDict.__repr__Fc
 143  Cs�|sdd�}nt|t�st|t�rtj||d�}n	t|�s"t�|�}|�|d�}z||�}W|Stt	fy^}z!|j
 144  dur@tn|j
 145  }t|�}|�
 146  d�sPd|}|�dt�|�|��d}~ww)	aILike get(), but with validation.
 147  
 148          The item is first retrieved as if with self.get(key, default=()) - the default
 149          value is () rather than None, so that JSON nulls are distinguishable from
 150          missing properties.
 151  
 152          If optional=True, and the value is (), it's returned as is. Otherwise, the
 153          item is validated by invoking validate(item) on it.
 154  
 155          If validate=False, it's treated as if it were (lambda x: x) - i.e. any value
 156          is considered valid, and is returned unchanged. If validate is a type or a
 157          tuple, it's treated as json.of_type(validate). Otherwise, if validate is not
 158          callable(), it's treated as json.default(validate).
 159  
 160          If validate() returns successfully, the item is substituted with the value
 161          it returns - thus, the validator can e.g. replace () with a suitable default
 162          value for the property.
 163  
 164          If validate() raises TypeError or ValueError, raises InvalidMessageError with
 165          the same text that applies_to(self.messages).
 166  
 167          See debugpy.common.json for reusable validators.
 168          cSs|Sr+r)�xrrrr9yr:z&MessageDict.__call__.<locals>.<lambda>)�optionalrN�[� z{0}{1})r�r��tuplerZof_type�callable�default�get�	TypeErrorrfr�r�r
 169  �
 170  startswith�
 171  isnt_validr5)rro�validater�rqrPr��errrrr�__call___s$
 172  
 173  
 174  �
 175  ��zMessageDict.__call__cs�fdd�}|S)NcsJz
 176  �||g|�Ri|��WSty$|jdurtn|j}|�d|��w)Nzmissing property {0!r})rgr�r�r�)rrorrr���funcrr�wrap�s�z,MessageDict._invalid_if_no_key.<locals>.wrapr)r�r�rr�r�_invalid_if_no_key�szMessageDict._invalid_if_no_keyr+)F)rrrrrr�r�r��collections�OrderedDict�__getitem__�__delitem__rrrrrrr�7s
 177  +
 178  
 179  r�csJ�dur�dkrt�t�rt�t�sJ��S�fdd�}td��|�_�S)zoJSON validator for message payload.
 180  
 181      If that value is missing or null, it is treated as if it were {}.
 182      Nrcs
 183  |�_dSr+�r�r��rqrr�associate_with��
 184  z _payload.<locals>.associate_with)r��dictr�r�)rqr�rr�r�_payload�s
 185  r�c@sxeZdZdZddd�Zdd�Zdd�Zeddd��Zd
 186  d�Z	dd�Z
 187  dd�Zdd�Zdd�Z
 188  dd�Zdd�Zdd�ZdS)r�z�Represents a fully parsed incoming or outgoing message.
 189  
 190      https://microsoft.github.io/debug-adapter-protocol/specification#protocolmessage
 191      NcCs||_||_	||_dSr+)�channel�seqr)rr�r�rrrrr�s
 192  zMessage.__init__cCs|jdurt�|j�St|�Sr+)rr5rCrrr�__str__�szMessage.__str__cC�t�)z�A brief description of the message that is enough to identify it.
 193  
 194          Examples:
 195          '#1 request "launch" from IDE'
 196          '#2 response to #1 request "launch" from IDE'.
 197          ��NotImplementedErrorrCrrr�describe�szMessage.describe�returnr�cCr�)zePayload of the message - self.body or self.arguments, depending on the
 198          message type.
 199          r�rCrrr�payload�szMessage.payloadcOs|j|i|��S)zSame as self.payload(...).�r�rrrrr��szMessage.__call__cCs
 200  ||jvS)zSame as (key in self.payload).r�)rrorrr�__contains__�s
 201  zMessage.__contains__cG� t|t�sdS|dkp|j|vS)zGReturns True if this message is an Event of one of the specified types.Fr)r��Event�event)rr�rrr�is_event��
 202  zMessage.is_eventcGr�)zHReturns True if this message is a Request of one of the specified types.Fr)r��Request�command�rr�rrr�
 203  is_request�r�zMessage.is_requestcGs"t|t�sdS|dkp|jj|vS)zgReturns True if this message is a Response to a request of one of the
 204          specified types.
 205          Fr)r��Response�requestr�r�rrr�is_response�s
 206  zMessage.is_responsecOsNt|t�sJ�|�dd�}|j|i|��}||||�}t|t�r%|�|�|S)aiReturns a new exception of the specified type from the point at which it is
 207          invoked, with the specified formatted message as the reason.
 208  
 209          The resulting exception will have its cause set to the Message object on which
 210          error() was called. Additionally, if that message is a Request, a failure
 211          response is immediately sent.
 212          �silentF)�
 213  issubclass�MessageHandlingErrorrr�r�r��respond)r�exc_typer[rrr��reasonrPrrr�error�s	
 214  
 215  z
 216  Message.errorcO�|jtg|�Ri|��S)z-Same as self.error(InvalidMessageError, ...).)r��InvalidMessageErrorrrrrr��zMessage.isnt_validcOr�)z.Same as self.error(MessageHandlingError, ...).)r�r�rrrr�cant_handler�zMessage.cant_handler+)r�r�)rrrrrr�r��propertyr�r�r�r�r�r�r�r�r�rrrrr��s
 217  	r�csJeZdZdZd
 218  �fdd�	Zdd�Zedd��Zed	d
 219  ��Z	dd�Z
 220  �ZS)r�a�Represents an incoming event.
 221  
 222      https://microsoft.github.io/debug-adapter-protocol/specification#event
 223  
 224      It is guaranteed that body is a MessageDict associated with this Event, and so
 225      are all the nested dicts in it. If "body" was missing or null in JSON, body is
 226      an empty dict.
 227  
 228      To handle the event, JsonMessageChannel tries to find a handler for this event in
 229      JsonMessageChannel.handlers. Given event="X", if handlers.X_event exists, then it
 230      is the specific handler for this event. Otherwise, handlers.event must exist, and
 231      it is the generic handler for this event. A missing handler is a fatal error.
 232  
 233      No further incoming messages are processed until the handler returns, except for
 234      responses to requests that have wait_for_response() invoked on them.
 235  
 236      To report failure to handle the event, the handler must raise an instance of
 237      MessageHandlingError that applies_to() the Event object it was handling. Any such
 238      failure is logged, after which the message loop moves on to the next message.
 239  
 240      Helper methods Message.isnt_valid() and Message.cant_handle() can be used to raise
 241      the appropriate exception type that applies_to() the Event object.
 242      Ncs>t��|||�||_t|t�rt|d�r|�|�||_dS�Nr�)rrr�r�r��hasattrr�rt)rr�r�r�rtrrrrr*s
 243  
 244  
 245  zEvent.__init__cC�"d|j�dt�|j��d|j��S)N�#z event � from )r�rr5r�r�rCrrrr�3�"zEvent.describecC�|jSr+�rtrCrrrr�6�z
 246  Event.payloadcC�B|dt�}|dt�}|dt�}t|||||d�}|�||j�dS)Nr�r�rt�r)rdr
 247  r�r��_enqueue_handlers�_handle)r��message_dictr�r�rtr�rrr�_parse:�
 248  
 249  
 250  
 251  zEvent._parsec
 252  Cs�|j}|�d|j�}zFz||�}|dus$Jdt�|��d|���d���WWdStyP}z|�|�s5�t�	dt�|�|��t
 253  |��WYd}~WdSd}~wwtyft�dt�|�|���YdSw)Nr�zHandler z tried to respond to �.�$Handler {0}
 254  couldn't handle {1}:
 255  {2}� Handler {0}
 256  couldn't handle {1}:)
 257  r��_get_handler_forr�r�	srcnameofr�r��
 258  applies_torr�r
 259  r/rB�rr��handler�resultrPrrrr�Bs4
 260  �
 261  ���	
 262  ��z
 263  Event._handler+)rrrrrr�r�r��staticmethodr�r�rrrrrr�s	
 264  
 265  r�csReZdZdZd�fdd�	Zdd�Zedd��Zd	d
 266  �Ze	dd��Z
 267  d
 268  d�Z�ZS)r�a_Represents an incoming or an outgoing request.
 269  
 270      Incoming requests are represented directly by instances of this class.
 271  
 272      Outgoing requests are represented by instances of OutgoingRequest, which provides
 273      additional functionality to handle responses.
 274  
 275      For incoming requests, it is guaranteed that arguments is a MessageDict associated
 276      with this Request, and so are all the nested dicts in it. If "arguments" was missing
 277      or null in JSON, arguments is an empty dict.
 278  
 279      To handle the request, JsonMessageChannel tries to find a handler for this request
 280      in JsonMessageChannel.handlers. Given command="X", if handlers.X_request exists,
 281      then it is the specific handler for this request. Otherwise, handlers.request must
 282      exist, and it is the generic handler for this request. A missing handler is a fatal
 283      error.
 284  
 285      The handler is then invoked with the Request object as its sole argument.
 286  
 287      If the handler itself invokes respond() on the Request at any point, then it must
 288      not return any value.
 289  
 290      Otherwise, if the handler returns NO_RESPONSE, no response to the request is sent.
 291      It must be sent manually at some later point via respond().
 292  
 293      Otherwise, a response to the request is sent with the returned value as the body.
 294  
 295      To fail the request, the handler can return an instance of MessageHandlingError,
 296      or respond() with one, or raise one such that it applies_to() the Request object
 297      being handled.
 298  
 299      Helper methods Message.isnt_valid() and Message.cant_handle() can be used to raise
 300      the appropriate exception type that applies_to() the Request object.
 301      NcsDt��|||�||_t|t�rt|d�r|�|�||_d|_dSr�)	rrr�r�r�r�r��	arguments�response)rr�r�r�r�rrrrr�s
 302  zRequest.__init__cCr�)Nr��	 request r��r�rr5r�r�rCrrrr��r�zRequest.describecCr�r+)r�rCrrrr��r�zRequest.payloadcCs�|jdusJ�d|j|jd�}t|t�rd|d<t|�|d<nd|d<|dur/|ikr/||d<|j�|��}Wd�n1s@wYt|j|||�|_dS)Nr�)r��request_seqr�F�successr�Trt)	r�r�r�r�r/r
 303  r��
 304  _send_messager�)rrt�dr�rrrr��s
 305  �zRequest.respondcCr�)Nr�r�r�r�)rdr
 306  r�r�r�r�)r�r�r�r�r�r�rrrr��r�zRequest._parsec
 307  Cs||j}|�d|j�}z�z||�}Wn)ty:}z|�|�s�|}t�dt�|�|�	�t
 308  |��WYd}~nd}~ww|turT|jdusQJd�
 309  t�|�|�	����WdS|jdurv|dusp||jjussJd�
 310  t�|�|�	����WdSWdS|dus�Jd�
 311  t�|�|�	����z	|�|�WWdSty�t�dt�|�|�	��YWdSwty�t�dt�|�|�	��YdSw)Nr�r�z\Handler {0} for {1} must not return NO_RESPONSE if it has already invoked request.respond().z`Handler {0} for {1} must not return a response body if it has already invoked request.respond().z}Handler {0} for {1} must either call request.respond() before it returns, or return the response body, or return NO_RESPONSE.zLChannel was closed before the response from handler {0} to {1} could be sentr�)r�r�r�r�r�rr�rr�r�r
 312  �NO_RESPONSEr�r�rtr�r�warningr/rBr�rrrr��sj
 313  ����
 314  �
 315  ��
 316  ����
 317  ��zRequest._handler+)
 318  rrrrrr�r�r�r�r�r�r�rrrrrr�ds#
 319  
 320  r�csJeZdZdZdZZ�fdd�Zdd�Zddd	�Zd
 321  d�Z	dd
 322  �Z
 323  �ZS)�OutgoingRequestz�Represents an outgoing request, for which it is possible to wait for a
 324      response to be received, and register a response handler.
 325      Ncst��||||�g|_dSr+)rr�_response_handlers)rr�r�r�r�rrrr�s
 326  zOutgoingRequest.__init__cCs |j�dt�|j��d|j��S)Nr�z to r�rCrrrr��s zOutgoingRequest.describeTcCsb|j�|jdur|jj��|jdus	Wd�n1swY|r-|jjs-|jj�|jjS)a�Waits until a response is received for this request, records the Response
 327          object for it in self.response, and returns response.body.
 328  
 329          If no response was received from the other party before the channel closed,
 330          self.response is a synthesized Response with body=NoMoreMessages().
 331  
 332          If raise_if_failed=True and response.success is False, raises response.body
 333          instead of returning.
 334          N)r�r��_handlers_enqueued�waitr�rt)rZraise_if_failedrrr�wait_for_response�s
 335  
 336  ���z!OutgoingRequest.wait_for_responsecCs@|j�|j�|�|��Wd�dS1swYdS)a=Registers a handler to invoke when a response is received for this request.
 337          The handler is invoked with Response as its sole argument.
 338  
 339          If response has already been received, invokes the handler immediately.
 340  
 341          It is guaranteed that self.response is set before the handler is invoked.
 342          If no response was received from the other party before the channel closed,
 343          self.response is a dummy Response with body=NoMoreMessages().
 344  
 345          The handler is always invoked asynchronously on an unspecified background
 346          thread - thus, the caller of on_response() can never be blocked or deadlocked
 347          by the handler.
 348  
 349          No further incoming messages are processed until the handler returns, except for
 350          responses to requests that have wait_for_response() invoked on them.
 351          N)r�r�rk�_enqueue_response_handlers)rZresponse_handlerrrr�on_responses
 352  "�zOutgoingRequest.on_responsecsL|j��dur	dS��fdd�}|jdd��|j��|�|jdd�=dS)Ncs��D]G}z0z|��Wn'ty2}z|���s�t�dt�|����t|��WYd}~nd}~wwWqtyIt�	dt�|�����YqwdS)Nr�r�)
 353  r�r�rr�rr�r�r
 354  r/rB)r�rP��handlersr�rr�run_handlers-s0
 355  ����	���z@OutgoingRequest._enqueue_response_handlers.<locals>.run_handlers)r�r�r�r�)rr�rr�rr�'sz*OutgoingRequest._enqueue_response_handlers)T)rrrrr�r�rr�r�r�r�rrrrrr��s
 356  r�cs\eZdZdZd�fdd�	Zdd�Zedd��Zed	d
 357  ��Zedd��Z	e
 358  dd
 359  d��Z�ZS)r�a^Represents an incoming or an outgoing response to a Request.
 360  
 361      https://microsoft.github.io/debug-adapter-protocol/specification#response
 362  
 363      error_message corresponds to "message" in JSON, and is renamed for clarity.
 364  
 365      If success is False, body is None. Otherwise, it is a MessageDict associated
 366      with this Response, and so are all the nested dicts in it. If "body" was missing
 367      or null in JSON, body is an empty dict.
 368  
 369      If this is a response to an outgoing request, it will be handled by the handler
 370      registered via self.request.on_response(), if any.
 371  
 372      Regardless of whether there is such a handler, OutgoingRequest.wait_for_response()
 373      can also be used to retrieve and handle the response. If there is a handler, it is
 374      executed before wait_for_response() returns.
 375  
 376      No further incoming messages are processed until the handler returns, except for
 377      responses to requests that have wait_for_response() invoked on them.
 378  
 379      To report failure to handle the event, the handler must raise an instance of
 380      MessageHandlingError that applies_to() the Response object it was handling. Any
 381      such failure is logged, after which the message loop moves on to the next message.
 382  
 383      Helper methods Message.isnt_valid() and Message.cant_handle() can be used to raise
 384      the appropriate exception type that applies_to() the Response object.
 385      Ncs@t��|||�||_	t|t�rt|d�r|�|�||_dSr�)rrr�r�r�r�r�rt)rr�r�r�rtrrrrrds
 386  zResponse.__init__cCsd|j�d|j����S)Nr�z
 387   response to )r�r�r�rCrrrr�yr�zResponse.describecCr�r+r�rCrrrr�|r�zResponse.payloadcCst|jt�S)z%Whether the request succeeded or not.)r�rtr/rCrrrr��szResponse.successcCs|jr|jS|j�)z�Result of the request. Returns the value of response.body, unless it
 388          is an exception, in which case it is raised instead.
 389          )r�rtrCrrrr��szResponse.resultcCsH|dur	|dt�nd}|dt�}|dt�}|dt�}|durD|r&|dt�}n|dt�}t}|�tj�r>|ttj�d�}t}||dd�}z|�|j	�
 390  |�}	d}
 391  Wd�n1sZwYWntyrt|||d	�}	d
 392  }
 393  Ynw|sx|	|_
 394  t|||	||d�}|�||	_|	��Wd�n1s�wY|
 395  r�|S|�d|��)
 396  Nr�r�r�r�rtr�T�r�z	<unknown>Fr�z0request_seq={0} does not match any known request)rdr
 397  �boolr�r�r�r��PREFIXr�_sent_requestsrrgr�r
 398  r�r�r�r�)r�r�rtr�r�r�r��
 399  error_messager�r�Z
 400  known_requestr�rrrr��sF
 401  
 402  
 403  
 404  ���
 405  ��zResponse._parser+)
 406  rrrrrr�r�r�r�r�r�r�rrrrrr�Gs
 407  
 408  
 409  	r�cs(eZdZdZ�fdd�Zdd�Z�ZS)�
 410  DisconnectznA dummy message used to represent disconnect. It's always the last message
 411      received from any channel.
 412      cst��|d�dSr+)rr)rr�rrrr�szDisconnect.__init__cCsd|j��S)Nzdisconnect from )r�rCrrrr��szDisconnect.describe)rrrrrr�rrrrrr�src@sReZdZdZddd�Zdd�Zdd	�Zd
 413  d�Zdd
 414  �Zdd�Z	dd�Z
 415  dd�ZdS)r�a�Indicates that a message couldn't be handled for some reason.
 416  
 417      If the reason is a contract violation - i.e. the message that was handled did not
 418      conform to the protocol specification - InvalidMessageError, which is a subclass,
 419      should be used instead.
 420  
 421      If any message handler raises an exception not derived from this class, it will
 422      escape the message loop unhandled, and terminate the process.
 423  
 424      If any message handler raises this exception, but applies_to(message) is False, it
 425      is treated as if it was a generic exception, as desribed above. Thus, if a request
 426      handler issues another request of its own, and that one fails, the failure is not
 427      silently propagated. However, a request that is delegated via Request.delegate()
 428      will also propagate failures back automatically. For manual propagation, catch the
 429      exception, and call exc.propagate().
 430  
 431      If any event handler raises this exception, and applies_to(event) is True, the
 432      exception is silently swallowed by the message loop.
 433  
 434      If any request handler raises this exception, and applies_to(request) is True, the
 435      exception is silently swallowed by the message loop, and a failure response is sent
 436      with "message" set to str(reason).
 437  
 438      Note that, while errors are not logged when they're swallowed by the message loop,
 439      by that time they have already been logged by their __init__ (when instantiated).
 440      NFcCsP||_	|dust|t�sJ�||_	|s&z|�ty%t��YdSwdS)aCreates a new instance of this class, and immediately logs the exception.
 441  
 442          Message handling errors are logged immediately unless silent=True, so that the
 443          precise context in which they occured can be determined from the surrounding
 444          log entries.
 445          N)r�r�r�r
 446  r�rr{)rr�r
 447  r�rrrr�s��zMessageHandlingError.__init__cCst|jt|j�f�Sr+)�hashr��idr
 448  rCrrr�__hash__�szMessageHandlingError.__hash__cCs^t|t�stSt|�t|�urtS|j|jkrdS|jdur-|jdur-|jj|jjkr-dSdS)NFT)r�r��NotImplementedr�r�r
 449  r��r�otherrrr�__eq__�s
 450  zMessageHandlingError.__eq__cCs
 451  ||kSr+rrrrr�__ne__r�zMessageHandlingError.__ne__cCs
 452  t|j�Sr+)r
 453  r�rCrrrr�r�zMessageHandlingError.__str__cCsVt|�j}|jdur|d|j�d�7}|S|d|jjj�d|jj�d|j�d�7}|S)Nzreason=r�zchannel=z, cause=z	, reason=)r�rr
 454  r�r�r&r�)r�srrrr�s
 455  
 456  (�zMessageHandlingError.__repr__cCs|jdup	|j|uS)z�Whether this MessageHandlingError can be treated as a reason why the
 457          handling of message failed.
 458  
 459          If self.cause is None, this is always true.
 460  
 461          If self.cause is not None, this is only true if cause is message.
 462          N)r
 463  �rr�rrrr�szMessageHandlingError.applies_tocCst|�|j|dd��)z}Propagates this error, raising a new instance of the same class with the
 464          same reason, but a different cause.
 465          Tr�)r�r�)rZ	new_causerrr�	propagate#szMessageHandlingError.propagate)NF)rrrrrrrrr�r�r�rrrrrr��s
 466  
 467  r�c@seZdZdZdZ	dd�ZdS)r�aIndicates that an incoming message did not follow the protocol specification -
 468      for example, it was missing properties that are required, or the message itself
 469      is not allowed in the current state.
 470  
 471      Raised by MessageDict in lieu of KeyError for missing keys.
 472      zInvalid message: cCstjt|j�Sr+)r�r�r
 473  r�rCrrrr�:rIzInvalidMessageError.__str__N)rrrrr�r�rrrrr�*s
 474  r�c@s�eZdZdZd/dd�Zdd�Zdd�Zd	d
 475  �Zdd�Zd
 476  d�Z	dd�Z
 477  dd�ZdZdd�Z
 478  ejdd��Zd/dd�Zd0dd�Zdd�Zdd�Zd d!�Zd"d#�Zejejejd$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Z dS)1�JsonMessageChannela|Implements a JSON message channel on top of a raw JSON message stream, with
 479      support for DAP requests, responses, and events.
 480  
 481      The channel can be locked for exclusive use via the with-statement::
 482  
 483          with channel:
 484              channel.send_request(...)
 485              # No interleaving messages can be sent here from other threads.
 486              channel.send_event(...)
 487      NcCsl||_||_|dur|n|j|_d|_t��|_d|_t�	d�|_
 488  i|_g|_t�
 489  |j�|_d|_d|_dS)NF�)r	r�r&�started�	threading�RLock�_lockr>�	itertools�count�	_seq_iterr��_handler_queue�	Conditionr��_handler_thread�_parser_thread)rr	r�r&rrrrJs
 490  
 491  zJsonMessageChannel.__init__cCr�r+rDrCrrrr�XszJsonMessageChannel.__str__cCrr�r�rCrrrr�[r�zJsonMessageChannel.__repr__cCs|j��|Sr+)r�acquirerCrrr�	__enter__^s
 492  zJsonMessageChannel.__enter__cCs|j��dSr+)r�release)rr��	exc_value�exc_tbrrr�__exit__bszJsonMessageChannel.__exit__cCsP|�|jsd|_|j��Wd�dSWd�dS1s!wYdS)a�Closes the underlying stream.
 493  
 494          This does not immediately terminate any handlers that are already executing,
 495          but they will be unable to respond. No new request or event handlers will
 496          execute after this method is called, even for messages that have already been
 497          received. However, response handlers will continue to executed for any request
 498          that is still pending, as will any handlers registered via on_response().
 499          TN)r>r	r0rCrrrr0es	�"�zJsonMessageChannel.closecCsH|jrJ�d|_tj|j|�d�d�|_t|j�d|j_|j��dS)aStarts a message loop which parses incoming messages and invokes handlers
 500          for them on a background thread, until the channel is closed.
 501  
 502          Incoming messages, including responses to requests, will not be processed at
 503          all until this is invoked.
 504          Tz message parser��targetr&N)rr�Thread�_parse_incoming_messagesrr�daemon�startrCrrrr$ss
 505  �
 506  zJsonMessageChannel.startcCsz|j}z
 507  |dur|��Wntyt�d�Ynwz|j}|dur+|��WdSWdSty<t�d�YdSw)z}Waits for the message loop to terminate, and for all enqueued Response
 508          message handlers to finish executing.
 509          Nz$Handled error joining parser thread.z%Handled error joining handler thread.)rrY�AssertionErrorrrAr)rZ
 510  parser_threadZhandler_threadrrrr��s ����zJsonMessageChannel.wait)
 511  r�r�r�r�r�r�r�r�rtr�cCs0|jD]}||vr
 512  q||}||=|||<qdS)z>Reorders items in a MessageDict such that it is more readable.N)�_prettify_order)rr�rorqrrr�	_prettify�s
 513  
 514  �zJsonMessageChannel._prettifyccs��d|vsJ�|�
 515  t|j�}Wd�n1swYtd|�}||d<|�|�|�|V|j�|�Wd�dS1sCwYdS)a�Sends a new message to the other party.
 516  
 517          Generates a new sequence number for the message, and provides it to the
 518          caller before the message is sent, using the context manager protocol::
 519  
 520              with send_message(...) as seq:
 521                  # The message hasn't been sent yet.
 522                  ...
 523              # Now the message has been sent.
 524  
 525          Safe to call concurrently for the same channel from different threads.
 526          r�N)�nextrr�r'r	r~)rr�r�rrrr��s��
 527  
 528  "�z JsonMessageChannel._send_messagecCszd|d�}|dur|ikr||d<|�|��}t||||�}|dur&||�||j|<Wd�|S1s6wY|S)a�Sends a new request, and returns the OutgoingRequest object for it.
 529  
 530          If arguments is None or {}, "arguments" will be omitted in JSON.
 531  
 532          If on_before_send is not None, invokes on_before_send() with the request
 533          object as the sole argument, before the request actually gets sent.
 534  
 535          Does not wait for response - use OutgoingRequest.wait_for_response().
 536  
 537          Safe to call concurrently for the same channel from different threads.
 538          r�)r�r�Nr�)r�r�r�)rr�r�Zon_before_sendr�r�r�rrr�send_request�s
 539  
 540  
 541  ��zJsonMessageChannel.send_requestcCsRd|d�}|dur|ikr||d<|�|��	Wd�dS1s"wYdS)z�Sends a new event.
 542  
 543          If body is None or {}, "body" will be omitted in JSON.
 544  
 545          Safe to call concurrently for the same channel from different threads.
 546          r�)r�r�Nrt)r�)rr�rtr�rrr�
 547  send_event�s
 548  "�zJsonMessageChannel.send_eventcOs|j|i|����S)z-Same as send_request(...).wait_for_response())r)r�rrrrr��szJsonMessageChannel.requestcCs@|��s
 549  |��s
 550  J�|��r|�|j|j�S|�|j|j�dS)z�Sends a new message with the same type and payload.
 551  
 552          If it was a request, returns the new OutgoingRequest object for it.
 553          N)r�r�r)r�r�r*r�rtr
 554  rrrr�szJsonMessageChannel.propagatec
 555  CsRz|�|�}|��r|��}|WSty(}z|�|�WYd}~dSd}~ww)z~Like propagate(message).wait_for_response(), but will also propagate
 556          any resulting MessageHandlingError back.
 557          N)rr�r�r�)rr�r�rPrrr�delegates
 558  ��zJsonMessageChannel.delegatec
 559  Cs�t�d|�z	|��qtyx}z`t�d||�|�At|�}t|j���}|D]}tdd|j	|j
 560  d|d��}tj|||d�q+t
 561  |j�rJJ�|�t|�|j�|��Wd�n1sawYWYd}~dSWYd}~dSd}~ww)Nz%Starting message loop for channel {0}Tz)Exiting message loop for channel {0}: {1}�����F)r�r�r�r�r�r�)rrA�_parse_incoming_messagerr
 562  �listr��valuesr�r�r�r�r�rr�r�_handle_disconnectr0)rrPZerr_messageZ
 563  sent_requestsr�Z
 564  response_jsonrrrr"s6���
 565  
 566  8���z+JsonMessageChannel._parse_incoming_messages)r�r�r�cs���fdd�}�fdd��g��jj|d�}�j�|�}t|t�s$J�|dt�ddd	��}�j|}z|�|�WdSty[}zt	�
 567  d
 568  �t|�t�|��WYd}~dSd}~wt
 569  y�}z"t|t�rn|j�jurn�t	�d�t�|��t�d
 570  �WYd}~dSd}~ww)z�Reads incoming messages, parses them, and puts handlers into the queue
 571          for _run_handlers() to invoke, until the channel is closed.
 572          cs0td|�}d|vr��|��|_��|�|S)Nr�)r�r'r�rk)r��r��
 573  message_dictsrrr�object_hook;s
 574  
 575  
 576  z?JsonMessageChannel._parse_incoming_message.<locals>.object_hookcs�D]}||_|`qdSr+)r�r�)r�r�)r2rrr�Ms�zBJsonMessageChannel._parse_incoming_message.<locals>.associate_with)r3r�r�r�r�z3Failed to parse message in channel {0}: {1} in:
 577  {2}Nz-Fatal error in channel {0} while parsing:
 578  {1}r
 579  )r	r`rur�r�r�enum�_message_parsersr�rr�r
 580  r5r/rr{�os�_exit)rr3rmr��msg_type�parserrPrr1rr-3s:
 581  �����z*JsonMessageChannel._parse_incoming_messagecs�|�K|j��fdd�|D��|j��t|j�r=|jdurEtj|j|�d�d�|_t	|j�|j�
 582  �Wd�dSWd�dSWd�dS1sPwYdS)z�Enqueues handlers for _run_handlers() to run.
 583  
 584          `what` is the Message being handled, and is used for logging purposes.
 585  
 586          If the background thread with _run_handlers() isn't running yet, starts it.
 587          c3s�|]}�|fVqdSr+r)rUr���whatrrrVurWz7JsonMessageChannel._enqueue_handlers.<locals>.<genexpr>Nz message handlerr)r�extendr��
 588  notify_allrrrr!�
 589  _run_handlersrr$)rr;r�rr:rr�ls
 590  �
 591  �
 592  �
 593  "�z$JsonMessageChannel._enqueue_handlersc
 594  Cs:	|�|j}Wd�n1swY|r|j��|�3|s,t|j�s,|j��|jdd�}|jdd�=|rKt|�sKd|_	Wd�dSWd�n1sUwY|D]?\}}|rk|tj	t
 595  j	fvrkq\t�d|�
 596  ��� z|�Wnty�|��t�d�YnwWd�n1s�wYq\q)z�Runs enqueued handlers until the channel is closed, or until the handler
 597          queue is empty once the channel is closed.
 598          TNz/handling {0}/
 599  r
 600  )r>rrYrrr�r�rr�r�r�r�prefixedr�r/r0r6r7)r�closedr�r;r�rrrr>�s>�
 601  
 602  ��
 603  �����z JsonMessageChannel._run_handlersc	Cs||�|j}Wd�n1swY|d||fD]}zt||�WSty0Yqwtd�t�|�|||���)z2Returns the handler for a message of a given type.Nrpz?handler object {0} for channel {1} has no handler for {2} {3!r})r��getattr�AttributeErrorr�rr�)rr�r&r��handler_namerrrr��s"����z#JsonMessageChannel._get_handler_forc	CsHt|jddd��}z|�WdSty#t�dt�|�|�YdSw)NZ
 604  disconnectcSr8r+rrrrrr9�r:z7JsonMessageChannel._handle_disconnect.<locals>.<lambda>z0Handler {0}
 605  couldn't handle disconnect from {1}:)rAr�r/rrBrr�)rr�rrrr0�s
 606  ��z%JsonMessageChannel._handle_disconnect)NNr+)!rrrrrr�r�rrr0r$r�r&r'�
 607  contextlib�contextmanagerr�r)r*r�rr+r"r�r�r�r�r5r-r�r>r�r0rrrrr>s:
 608  
 609  	
 610  
 611  
 612  "�90rc@seZdZdZdd�ZdS)�MessageHandlersz�A simple delegating message handlers object for use with JsonMessageChannel.
 613      For every argument provided, the object gets an attribute with the corresponding
 614      name and value.
 615      cKs"|��D]
 616  \}}t|||�qdSr+)r��setattr)rrr&r�rrrr�s�zMessageHandlers.__init__N)rrrrrrrrrrF�srF)&r�
 617  __future__rr�rDrarr6r-r!rZdebugpy.commonrrrZdebugpy.common.utilrrhrrjr�objectrr�r�r�r�r�r�r�r�r�rr/r�r�rrFrrrr�<module>sD
 618  |d_K
 619  Wtc