messaging.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  1. # Copyright (c) Microsoft Corporation. All rights reserved.
  2. # Licensed under the MIT License. See LICENSE in the project root
  3. # for license information.
  4. """An implementation of the session and presentation layers as used in the Debug
  5. Adapter Protocol (DAP): channels and their lifetime, JSON messages, requests,
  6. responses, and events.
  7. https://microsoft.github.io/debug-adapter-protocol/overview#base-protocol
  8. """
  9. from __future__ import annotations
  10. import collections
  11. import contextlib
  12. import functools
  13. import itertools
  14. import os
  15. import socket
  16. import sys
  17. import threading
  18. from debugpy.common import json, log, util
  19. from debugpy.common.util import hide_thread_from_debugger
  20. class JsonIOError(IOError):
  21. """Indicates that a read or write operation on JsonIOStream has failed."""
  22. def __init__(self, *args, **kwargs):
  23. stream = kwargs.pop("stream")
  24. cause = kwargs.pop("cause", None)
  25. if not len(args) and cause is not None:
  26. args = [str(cause)]
  27. super().__init__(*args, **kwargs)
  28. self.stream = stream
  29. """The stream that couldn't be read or written.
  30. Set by JsonIOStream.read_json() and JsonIOStream.write_json().
  31. JsonMessageChannel relies on this value to decide whether a NoMoreMessages
  32. instance that bubbles up to the message loop is related to that loop.
  33. """
  34. self.cause = cause
  35. """The underlying exception, if any."""
  36. class NoMoreMessages(JsonIOError, EOFError):
  37. """Indicates that there are no more messages that can be read from or written
  38. to a stream.
  39. """
  40. def __init__(self, *args, **kwargs):
  41. args = args if len(args) else ["No more messages"]
  42. super().__init__(*args, **kwargs)
  43. class JsonIOStream(object):
  44. """Implements a JSON value stream over two byte streams (input and output).
  45. Each value is encoded as a DAP packet, with metadata headers and a JSON payload.
  46. """
  47. MAX_BODY_SIZE = 0xFFFFFF
  48. json_decoder_factory = json.JsonDecoder
  49. """Used by read_json() when decoder is None."""
  50. json_encoder_factory = json.JsonEncoder
  51. """Used by write_json() when encoder is None."""
  52. @classmethod
  53. def from_stdio(cls, name="stdio"):
  54. """Creates a new instance that receives messages from sys.stdin, and sends
  55. them to sys.stdout.
  56. """
  57. return cls(sys.stdin.buffer, sys.stdout.buffer, name)
  58. @classmethod
  59. def from_process(cls, process, name="stdio"):
  60. """Creates a new instance that receives messages from process.stdin, and sends
  61. them to process.stdout.
  62. """
  63. return cls(process.stdout, process.stdin, name)
  64. @classmethod
  65. def from_socket(cls, sock, name=None):
  66. """Creates a new instance that sends and receives messages over a socket."""
  67. sock.settimeout(None) # make socket blocking
  68. if name is None:
  69. name = repr(sock)
  70. # TODO: investigate switching to buffered sockets; readline() on unbuffered
  71. # sockets is very slow! Although the implementation of readline() itself is
  72. # native code, it calls read(1) in a loop - and that then ultimately calls
  73. # SocketIO.readinto(), which is implemented in Python.
  74. socket_io = sock.makefile("rwb", 0)
  75. # SocketIO.close() doesn't close the underlying socket.
  76. def cleanup():
  77. try:
  78. sock.shutdown(socket.SHUT_RDWR)
  79. except Exception: # pragma: no cover
  80. pass
  81. sock.close()
  82. return cls(socket_io, socket_io, name, cleanup)
  83. def __init__(self, reader, writer, name=None, cleanup=lambda: None):
  84. """Creates a new JsonIOStream.
  85. reader must be a BytesIO-like object, from which incoming messages will be
  86. read by read_json().
  87. writer must be a BytesIO-like object, into which outgoing messages will be
  88. written by write_json().
  89. cleanup must be a callable; it will be invoked without arguments when the
  90. stream is closed.
  91. reader.readline() must treat "\n" as the line terminator, and must leave "\r"
  92. as is - it must not replace "\r\n" with "\n" automatically, as TextIO does.
  93. """
  94. if name is None:
  95. name = f"reader={reader!r}, writer={writer!r}"
  96. self.name = name
  97. self._reader = reader
  98. self._writer = writer
  99. self._cleanup = cleanup
  100. self._closed = False
  101. def close(self):
  102. """Closes the stream, the reader, and the writer."""
  103. if self._closed:
  104. return
  105. self._closed = True
  106. log.debug("Closing {0} message stream", self.name)
  107. try:
  108. try:
  109. # Close the writer first, so that the other end of the connection has
  110. # its message loop waiting on read() unblocked. If there is an exception
  111. # while closing the writer, we still want to try to close the reader -
  112. # only one exception can bubble up, so if both fail, it'll be the one
  113. # from reader.
  114. try:
  115. self._writer.close()
  116. finally:
  117. if self._reader is not self._writer:
  118. self._reader.close()
  119. finally:
  120. self._cleanup()
  121. except Exception: # pragma: no cover
  122. log.reraise_exception("Error while closing {0} message stream", self.name)
  123. def _log_message(self, dir, data, logger=log.debug):
  124. return logger("{0} {1} {2}", self.name, dir, data)
  125. def _read_line(self, reader):
  126. line = b""
  127. while True:
  128. try:
  129. line += reader.readline()
  130. except Exception as exc:
  131. raise NoMoreMessages(str(exc), stream=self)
  132. if not line:
  133. raise NoMoreMessages(stream=self)
  134. if line.endswith(b"\r\n"):
  135. line = line[0:-2]
  136. return line
  137. def read_json(self, decoder=None):
  138. """Read a single JSON value from reader.
  139. Returns JSON value as parsed by decoder.decode(), or raises NoMoreMessages
  140. if there are no more values to be read.
  141. """
  142. decoder = decoder if decoder is not None else self.json_decoder_factory()
  143. reader = self._reader
  144. read_line = functools.partial(self._read_line, reader)
  145. # If any error occurs while reading and parsing the message, log the original
  146. # raw message data as is, so that it's possible to diagnose missing or invalid
  147. # headers, encoding issues, JSON syntax errors etc.
  148. def log_message_and_reraise_exception(format_string="", *args, **kwargs):
  149. if format_string:
  150. format_string += "\n\n"
  151. format_string += "{name} -->\n{raw_lines}"
  152. raw_lines = b"".join(raw_chunks).split(b"\n")
  153. raw_lines = "\n".join(repr(line) for line in raw_lines)
  154. log.reraise_exception(
  155. format_string, *args, name=self.name, raw_lines=raw_lines, **kwargs
  156. )
  157. raw_chunks = []
  158. headers = {}
  159. while True:
  160. try:
  161. line = read_line()
  162. except Exception: # pragma: no cover
  163. # Only log it if we have already read some headers, and are looking
  164. # for a blank line terminating them. If this is the very first read,
  165. # there's no message data to log in any case, and the caller might
  166. # be anticipating the error - e.g. NoMoreMessages on disconnect.
  167. if headers:
  168. log_message_and_reraise_exception(
  169. "Error while reading message headers:"
  170. )
  171. else:
  172. raise
  173. raw_chunks += [line, b"\n"]
  174. if line == b"":
  175. break
  176. key, _, value = line.partition(b":")
  177. headers[key] = value
  178. try:
  179. length = int(headers[b"Content-Length"])
  180. if not (0 <= length <= self.MAX_BODY_SIZE):
  181. raise ValueError
  182. except (KeyError, ValueError): # pragma: no cover
  183. try:
  184. raise IOError("Content-Length is missing or invalid:")
  185. except Exception:
  186. log_message_and_reraise_exception()
  187. body_start = len(raw_chunks)
  188. body_remaining = length
  189. while body_remaining > 0:
  190. try:
  191. chunk = reader.read(body_remaining)
  192. if not chunk:
  193. raise EOFError
  194. except Exception as exc:
  195. # Not logged due to https://github.com/microsoft/ptvsd/issues/1699
  196. raise NoMoreMessages(str(exc), stream=self)
  197. raw_chunks.append(chunk)
  198. body_remaining -= len(chunk)
  199. assert body_remaining == 0
  200. body = b"".join(raw_chunks[body_start:])
  201. try:
  202. body = body.decode("utf-8")
  203. except Exception: # pragma: no cover
  204. log_message_and_reraise_exception()
  205. try:
  206. body = decoder.decode(body)
  207. except Exception: # pragma: no cover
  208. log_message_and_reraise_exception()
  209. # If parsed successfully, log as JSON for readability.
  210. self._log_message("-->", body)
  211. return body
  212. def write_json(self, value, encoder=None):
  213. """Write a single JSON value into writer.
  214. Value is written as encoded by encoder.encode().
  215. """
  216. if self._closed:
  217. # Don't log this - it's a common pattern to write to a stream while
  218. # anticipating EOFError from it in case it got closed concurrently.
  219. raise NoMoreMessages(stream=self)
  220. encoder = encoder if encoder is not None else self.json_encoder_factory()
  221. writer = self._writer
  222. # Format the value as a message, and try to log any failures using as much
  223. # information as we already have at the point of the failure. For example,
  224. # if it fails after it is serialized to JSON, log that JSON.
  225. try:
  226. body = encoder.encode(value)
  227. except Exception: # pragma: no cover
  228. self._log_message("<--", repr(value), logger=log.reraise_exception)
  229. body = body.encode("utf-8")
  230. header = f"Content-Length: {len(body)}\r\n\r\n".encode("ascii")
  231. data = header + body
  232. data_written = 0
  233. try:
  234. while data_written < len(data):
  235. written = writer.write(data[data_written:])
  236. if written is not None:
  237. data_written += written
  238. writer.flush()
  239. except Exception as exc: # pragma: no cover
  240. self._log_message("<--", value, logger=log.swallow_exception)
  241. raise JsonIOError(stream=self, cause=exc)
  242. self._log_message("<--", value)
  243. def __repr__(self):
  244. return f"{type(self).__name__}({self.name!r})"
  245. class MessageDict(collections.OrderedDict):
  246. """A specialized dict that is used for JSON message payloads - Request.arguments,
  247. Response.body, and Event.body.
  248. For all members that normally throw KeyError when a requested key is missing, this
  249. dict raises InvalidMessageError instead. Thus, a message handler can skip checks
  250. for missing properties, and just work directly with the payload on the assumption
  251. that it is valid according to the protocol specification; if anything is missing,
  252. it will be reported automatically in the proper manner.
  253. If the value for the requested key is itself a dict, it is returned as is, and not
  254. automatically converted to MessageDict. Thus, to enable convenient chaining - e.g.
  255. d["a"]["b"]["c"] - the dict must consistently use MessageDict instances rather than
  256. vanilla dicts for all its values, recursively. This is guaranteed for the payload
  257. of all freshly received messages (unless and until it is mutated), but there is no
  258. such guarantee for outgoing messages.
  259. """
  260. def __init__(self, message, items=None):
  261. assert message is None or isinstance(message, Message)
  262. if items is None:
  263. super().__init__()
  264. else:
  265. super().__init__(items)
  266. self.message = message
  267. """The Message object that owns this dict.
  268. For any instance exposed via a Message object corresponding to some incoming
  269. message, it is guaranteed to reference that Message object. There is no similar
  270. guarantee for outgoing messages.
  271. """
  272. def __repr__(self):
  273. try:
  274. return format(json.repr(self))
  275. except Exception: # pragma: no cover
  276. return super().__repr__()
  277. def __call__(self, key, validate, optional=False):
  278. """Like get(), but with validation.
  279. The item is first retrieved as if with self.get(key, default=()) - the default
  280. value is () rather than None, so that JSON nulls are distinguishable from
  281. missing properties.
  282. If optional=True, and the value is (), it's returned as is. Otherwise, the
  283. item is validated by invoking validate(item) on it.
  284. If validate=False, it's treated as if it were (lambda x: x) - i.e. any value
  285. is considered valid, and is returned unchanged. If validate is a type or a
  286. tuple, it's treated as json.of_type(validate). Otherwise, if validate is not
  287. callable(), it's treated as json.default(validate).
  288. If validate() returns successfully, the item is substituted with the value
  289. it returns - thus, the validator can e.g. replace () with a suitable default
  290. value for the property.
  291. If validate() raises TypeError or ValueError, raises InvalidMessageError with
  292. the same text that applies_to(self.messages).
  293. See debugpy.common.json for reusable validators.
  294. """
  295. if not validate:
  296. validate = lambda x: x
  297. elif isinstance(validate, type) or isinstance(validate, tuple):
  298. validate = json.of_type(validate, optional=optional)
  299. elif not callable(validate):
  300. validate = json.default(validate)
  301. value = self.get(key, ())
  302. try:
  303. value = validate(value)
  304. except (TypeError, ValueError) as exc:
  305. message = Message if self.message is None else self.message
  306. err = str(exc)
  307. if not err.startswith("["):
  308. err = " " + err
  309. raise message.isnt_valid("{0}{1}", json.repr(key), err)
  310. return value
  311. def _invalid_if_no_key(func):
  312. def wrap(self, key, *args, **kwargs):
  313. try:
  314. return func(self, key, *args, **kwargs)
  315. except KeyError:
  316. message = Message if self.message is None else self.message
  317. raise message.isnt_valid("missing property {0!r}", key)
  318. return wrap
  319. __getitem__ = _invalid_if_no_key(collections.OrderedDict.__getitem__)
  320. __delitem__ = _invalid_if_no_key(collections.OrderedDict.__delitem__)
  321. pop = _invalid_if_no_key(collections.OrderedDict.pop)
  322. del _invalid_if_no_key
  323. def _payload(value):
  324. """JSON validator for message payload.
  325. If that value is missing or null, it is treated as if it were {}.
  326. """
  327. if value is not None and value != ():
  328. if isinstance(value, dict): # can be int, str, list...
  329. assert isinstance(value, MessageDict)
  330. return value
  331. # Missing payload. Construct a dummy MessageDict, and make it look like it was
  332. # deserialized. See JsonMessageChannel._parse_incoming_message for why it needs
  333. # to have associate_with().
  334. def associate_with(message):
  335. value.message = message
  336. value = MessageDict(None)
  337. value.associate_with = associate_with
  338. return value
  339. class Message(object):
  340. """Represents a fully parsed incoming or outgoing message.
  341. https://microsoft.github.io/debug-adapter-protocol/specification#protocolmessage
  342. """
  343. def __init__(self, channel, seq, json=None):
  344. self.channel = channel
  345. self.seq = seq
  346. """Sequence number of the message in its channel.
  347. This can be None for synthesized Responses.
  348. """
  349. self.json = json
  350. """For incoming messages, the MessageDict containing raw JSON from which
  351. this message was originally parsed.
  352. """
  353. def __str__(self):
  354. return json.repr(self.json) if self.json is not None else repr(self)
  355. def describe(self):
  356. """A brief description of the message that is enough to identify it.
  357. Examples:
  358. '#1 request "launch" from IDE'
  359. '#2 response to #1 request "launch" from IDE'.
  360. """
  361. raise NotImplementedError
  362. @property
  363. def payload(self) -> MessageDict:
  364. """Payload of the message - self.body or self.arguments, depending on the
  365. message type.
  366. """
  367. raise NotImplementedError
  368. def __call__(self, *args, **kwargs):
  369. """Same as self.payload(...)."""
  370. return self.payload(*args, **kwargs)
  371. def __contains__(self, key):
  372. """Same as (key in self.payload)."""
  373. return key in self.payload
  374. def is_event(self, *event):
  375. """Returns True if this message is an Event of one of the specified types."""
  376. if not isinstance(self, Event):
  377. return False
  378. return event == () or self.event in event
  379. def is_request(self, *command):
  380. """Returns True if this message is a Request of one of the specified types."""
  381. if not isinstance(self, Request):
  382. return False
  383. return command == () or self.command in command
  384. def is_response(self, *command):
  385. """Returns True if this message is a Response to a request of one of the
  386. specified types.
  387. """
  388. if not isinstance(self, Response):
  389. return False
  390. return command == () or self.request.command in command
  391. def error(self, exc_type, format_string, *args, **kwargs):
  392. """Returns a new exception of the specified type from the point at which it is
  393. invoked, with the specified formatted message as the reason.
  394. The resulting exception will have its cause set to the Message object on which
  395. error() was called. Additionally, if that message is a Request, a failure
  396. response is immediately sent.
  397. """
  398. assert issubclass(exc_type, MessageHandlingError)
  399. silent = kwargs.pop("silent", False)
  400. reason = format_string.format(*args, **kwargs)
  401. exc = exc_type(reason, self, silent) # will log it
  402. if isinstance(self, Request):
  403. self.respond(exc)
  404. return exc
  405. def isnt_valid(self, *args, **kwargs):
  406. """Same as self.error(InvalidMessageError, ...)."""
  407. return self.error(InvalidMessageError, *args, **kwargs)
  408. def cant_handle(self, *args, **kwargs):
  409. """Same as self.error(MessageHandlingError, ...)."""
  410. return self.error(MessageHandlingError, *args, **kwargs)
  411. class Event(Message):
  412. """Represents an incoming event.
  413. https://microsoft.github.io/debug-adapter-protocol/specification#event
  414. It is guaranteed that body is a MessageDict associated with this Event, and so
  415. are all the nested dicts in it. If "body" was missing or null in JSON, body is
  416. an empty dict.
  417. To handle the event, JsonMessageChannel tries to find a handler for this event in
  418. JsonMessageChannel.handlers. Given event="X", if handlers.X_event exists, then it
  419. is the specific handler for this event. Otherwise, handlers.event must exist, and
  420. it is the generic handler for this event. A missing handler is a fatal error.
  421. No further incoming messages are processed until the handler returns, except for
  422. responses to requests that have wait_for_response() invoked on them.
  423. To report failure to handle the event, the handler must raise an instance of
  424. MessageHandlingError that applies_to() the Event object it was handling. Any such
  425. failure is logged, after which the message loop moves on to the next message.
  426. Helper methods Message.isnt_valid() and Message.cant_handle() can be used to raise
  427. the appropriate exception type that applies_to() the Event object.
  428. """
  429. def __init__(self, channel, seq, event, body, json=None):
  430. super().__init__(channel, seq, json)
  431. self.event = event
  432. if isinstance(body, MessageDict) and hasattr(body, "associate_with"):
  433. body.associate_with(self)
  434. self.body = body
  435. def describe(self):
  436. return f"#{self.seq} event {json.repr(self.event)} from {self.channel}"
  437. @property
  438. def payload(self):
  439. return self.body
  440. @staticmethod
  441. def _parse(channel, message_dict):
  442. seq = message_dict("seq", int)
  443. event = message_dict("event", str)
  444. body = message_dict("body", _payload)
  445. message = Event(channel, seq, event, body, json=message_dict)
  446. channel._enqueue_handlers(message, message._handle)
  447. def _handle(self):
  448. channel = self.channel
  449. handler = channel._get_handler_for("event", self.event)
  450. try:
  451. try:
  452. result = handler(self)
  453. assert (
  454. result is None
  455. ), f"Handler {util.srcnameof(handler)} tried to respond to {self.describe()}."
  456. except MessageHandlingError as exc:
  457. if not exc.applies_to(self):
  458. raise
  459. log.error(
  460. "Handler {0}\ncouldn't handle {1}:\n{2}",
  461. util.srcnameof(handler),
  462. self.describe(),
  463. str(exc),
  464. )
  465. except Exception:
  466. log.reraise_exception(
  467. "Handler {0}\ncouldn't handle {1}:",
  468. util.srcnameof(handler),
  469. self.describe(),
  470. )
  471. NO_RESPONSE = object()
  472. """Can be returned from a request handler in lieu of the response body, to indicate
  473. that no response is to be sent.
  474. Request.respond() must be invoked explicitly at some later point to provide a response.
  475. """
  476. class Request(Message):
  477. """Represents an incoming or an outgoing request.
  478. Incoming requests are represented directly by instances of this class.
  479. Outgoing requests are represented by instances of OutgoingRequest, which provides
  480. additional functionality to handle responses.
  481. For incoming requests, it is guaranteed that arguments is a MessageDict associated
  482. with this Request, and so are all the nested dicts in it. If "arguments" was missing
  483. or null in JSON, arguments is an empty dict.
  484. To handle the request, JsonMessageChannel tries to find a handler for this request
  485. in JsonMessageChannel.handlers. Given command="X", if handlers.X_request exists,
  486. then it is the specific handler for this request. Otherwise, handlers.request must
  487. exist, and it is the generic handler for this request. A missing handler is a fatal
  488. error.
  489. The handler is then invoked with the Request object as its sole argument.
  490. If the handler itself invokes respond() on the Request at any point, then it must
  491. not return any value.
  492. Otherwise, if the handler returns NO_RESPONSE, no response to the request is sent.
  493. It must be sent manually at some later point via respond().
  494. Otherwise, a response to the request is sent with the returned value as the body.
  495. To fail the request, the handler can return an instance of MessageHandlingError,
  496. or respond() with one, or raise one such that it applies_to() the Request object
  497. being handled.
  498. Helper methods Message.isnt_valid() and Message.cant_handle() can be used to raise
  499. the appropriate exception type that applies_to() the Request object.
  500. """
  501. def __init__(self, channel, seq, command, arguments, json=None):
  502. super().__init__(channel, seq, json)
  503. self.command = command
  504. if isinstance(arguments, MessageDict) and hasattr(arguments, "associate_with"):
  505. arguments.associate_with(self)
  506. self.arguments = arguments
  507. self.response = None
  508. """Response to this request.
  509. For incoming requests, it is set as soon as the request handler returns.
  510. For outgoing requests, it is set as soon as the response is received, and
  511. before self._handle_response is invoked.
  512. """
  513. def describe(self):
  514. return f"#{self.seq} request {json.repr(self.command)} from {self.channel}"
  515. @property
  516. def payload(self):
  517. return self.arguments
  518. def respond(self, body):
  519. assert self.response is None
  520. d = {"type": "response", "request_seq": self.seq, "command": self.command}
  521. if isinstance(body, Exception):
  522. d["success"] = False
  523. d["message"] = str(body)
  524. else:
  525. d["success"] = True
  526. if body is not None and body != {}:
  527. d["body"] = body
  528. with self.channel._send_message(d) as seq:
  529. pass
  530. self.response = Response(self.channel, seq, self, body)
  531. @staticmethod
  532. def _parse(channel, message_dict):
  533. seq = message_dict("seq", int)
  534. command = message_dict("command", str)
  535. arguments = message_dict("arguments", _payload)
  536. message = Request(channel, seq, command, arguments, json=message_dict)
  537. channel._enqueue_handlers(message, message._handle)
  538. def _handle(self):
  539. channel = self.channel
  540. handler = channel._get_handler_for("request", self.command)
  541. try:
  542. try:
  543. result = handler(self)
  544. except MessageHandlingError as exc:
  545. if not exc.applies_to(self):
  546. raise
  547. result = exc
  548. log.error(
  549. "Handler {0}\ncouldn't handle {1}:\n{2}",
  550. util.srcnameof(handler),
  551. self.describe(),
  552. str(exc),
  553. )
  554. if result is NO_RESPONSE:
  555. assert self.response is None, (
  556. "Handler {0} for {1} must not return NO_RESPONSE if it has already "
  557. "invoked request.respond().".format(
  558. util.srcnameof(handler), self.describe()
  559. )
  560. )
  561. elif self.response is not None:
  562. assert result is None or result is self.response.body, (
  563. "Handler {0} for {1} must not return a response body if it has "
  564. "already invoked request.respond().".format(
  565. util.srcnameof(handler), self.describe()
  566. )
  567. )
  568. else:
  569. assert result is not None, (
  570. "Handler {0} for {1} must either call request.respond() before it "
  571. "returns, or return the response body, or return NO_RESPONSE.".format(
  572. util.srcnameof(handler), self.describe()
  573. )
  574. )
  575. try:
  576. self.respond(result)
  577. except NoMoreMessages:
  578. log.warning(
  579. "Channel was closed before the response from handler {0} to {1} could be sent",
  580. util.srcnameof(handler),
  581. self.describe(),
  582. )
  583. except Exception:
  584. log.reraise_exception(
  585. "Handler {0}\ncouldn't handle {1}:",
  586. util.srcnameof(handler),
  587. self.describe(),
  588. )
  589. class OutgoingRequest(Request):
  590. """Represents an outgoing request, for which it is possible to wait for a
  591. response to be received, and register a response handler.
  592. """
  593. _parse = _handle = None
  594. def __init__(self, channel, seq, command, arguments):
  595. super().__init__(channel, seq, command, arguments)
  596. self._response_handlers = []
  597. def describe(self):
  598. return f"{self.seq} request {json.repr(self.command)} to {self.channel}"
  599. def wait_for_response(self, raise_if_failed=True):
  600. """Waits until a response is received for this request, records the Response
  601. object for it in self.response, and returns response.body.
  602. If no response was received from the other party before the channel closed,
  603. self.response is a synthesized Response with body=NoMoreMessages().
  604. If raise_if_failed=True and response.success is False, raises response.body
  605. instead of returning.
  606. """
  607. with self.channel:
  608. while self.response is None:
  609. self.channel._handlers_enqueued.wait()
  610. if raise_if_failed and not self.response.success:
  611. raise self.response.body
  612. return self.response.body
  613. def on_response(self, response_handler):
  614. """Registers a handler to invoke when a response is received for this request.
  615. The handler is invoked with Response as its sole argument.
  616. If response has already been received, invokes the handler immediately.
  617. It is guaranteed that self.response is set before the handler is invoked.
  618. If no response was received from the other party before the channel closed,
  619. self.response is a dummy Response with body=NoMoreMessages().
  620. The handler is always invoked asynchronously on an unspecified background
  621. thread - thus, the caller of on_response() can never be blocked or deadlocked
  622. by the handler.
  623. No further incoming messages are processed until the handler returns, except for
  624. responses to requests that have wait_for_response() invoked on them.
  625. """
  626. with self.channel:
  627. self._response_handlers.append(response_handler)
  628. self._enqueue_response_handlers()
  629. def _enqueue_response_handlers(self):
  630. response = self.response
  631. if response is None:
  632. # Response._parse() will submit the handlers when response is received.
  633. return
  634. def run_handlers():
  635. for handler in handlers:
  636. try:
  637. try:
  638. handler(response)
  639. except MessageHandlingError as exc:
  640. if not exc.applies_to(response):
  641. raise
  642. log.error(
  643. "Handler {0}\ncouldn't handle {1}:\n{2}",
  644. util.srcnameof(handler),
  645. response.describe(),
  646. str(exc),
  647. )
  648. except Exception:
  649. log.reraise_exception(
  650. "Handler {0}\ncouldn't handle {1}:",
  651. util.srcnameof(handler),
  652. response.describe(),
  653. )
  654. handlers = self._response_handlers[:]
  655. self.channel._enqueue_handlers(response, run_handlers)
  656. del self._response_handlers[:]
  657. class Response(Message):
  658. """Represents an incoming or an outgoing response to a Request.
  659. https://microsoft.github.io/debug-adapter-protocol/specification#response
  660. error_message corresponds to "message" in JSON, and is renamed for clarity.
  661. If success is False, body is None. Otherwise, it is a MessageDict associated
  662. with this Response, and so are all the nested dicts in it. If "body" was missing
  663. or null in JSON, body is an empty dict.
  664. If this is a response to an outgoing request, it will be handled by the handler
  665. registered via self.request.on_response(), if any.
  666. Regardless of whether there is such a handler, OutgoingRequest.wait_for_response()
  667. can also be used to retrieve and handle the response. If there is a handler, it is
  668. executed before wait_for_response() returns.
  669. No further incoming messages are processed until the handler returns, except for
  670. responses to requests that have wait_for_response() invoked on them.
  671. To report failure to handle the event, the handler must raise an instance of
  672. MessageHandlingError that applies_to() the Response object it was handling. Any
  673. such failure is logged, after which the message loop moves on to the next message.
  674. Helper methods Message.isnt_valid() and Message.cant_handle() can be used to raise
  675. the appropriate exception type that applies_to() the Response object.
  676. """
  677. def __init__(self, channel, seq, request, body, json=None):
  678. super().__init__(channel, seq, json)
  679. self.request = request
  680. """The request to which this is the response."""
  681. if isinstance(body, MessageDict) and hasattr(body, "associate_with"):
  682. body.associate_with(self)
  683. self.body = body
  684. """Body of the response if the request was successful, or an instance
  685. of some class derived from Exception it it was not.
  686. If a response was received from the other side, but request failed, it is an
  687. instance of MessageHandlingError containing the received error message. If the
  688. error message starts with InvalidMessageError.PREFIX, then it's an instance of
  689. the InvalidMessageError specifically, and that prefix is stripped.
  690. If no response was received from the other party before the channel closed,
  691. it is an instance of NoMoreMessages.
  692. """
  693. def describe(self):
  694. return f"#{self.seq} response to {self.request.describe()}"
  695. @property
  696. def payload(self):
  697. return self.body
  698. @property
  699. def success(self):
  700. """Whether the request succeeded or not."""
  701. return not isinstance(self.body, Exception)
  702. @property
  703. def result(self):
  704. """Result of the request. Returns the value of response.body, unless it
  705. is an exception, in which case it is raised instead.
  706. """
  707. if self.success:
  708. return self.body
  709. else:
  710. raise self.body
  711. @staticmethod
  712. def _parse(channel, message_dict, body=None):
  713. seq = message_dict("seq", int) if (body is None) else None
  714. request_seq = message_dict("request_seq", int)
  715. command = message_dict("command", str)
  716. success = message_dict("success", bool)
  717. if body is None:
  718. if success:
  719. body = message_dict("body", _payload)
  720. else:
  721. error_message = message_dict("message", str)
  722. exc_type = MessageHandlingError
  723. if error_message.startswith(InvalidMessageError.PREFIX):
  724. error_message = error_message[len(InvalidMessageError.PREFIX) :]
  725. exc_type = InvalidMessageError
  726. body = exc_type(error_message, silent=True)
  727. try:
  728. with channel:
  729. request = channel._sent_requests.pop(request_seq)
  730. known_request = True
  731. except KeyError:
  732. # Synthetic Request that only has seq and command as specified in response
  733. # JSON, for error reporting purposes.
  734. request = OutgoingRequest(channel, request_seq, command, "<unknown>")
  735. known_request = False
  736. if not success:
  737. body.cause = request
  738. response = Response(channel, seq, request, body, json=message_dict)
  739. with channel:
  740. request.response = response
  741. request._enqueue_response_handlers()
  742. if known_request:
  743. return response
  744. else:
  745. raise response.isnt_valid(
  746. "request_seq={0} does not match any known request", request_seq
  747. )
  748. class Disconnect(Message):
  749. """A dummy message used to represent disconnect. It's always the last message
  750. received from any channel.
  751. """
  752. def __init__(self, channel):
  753. super().__init__(channel, None)
  754. def describe(self):
  755. return f"disconnect from {self.channel}"
  756. class MessageHandlingError(Exception):
  757. """Indicates that a message couldn't be handled for some reason.
  758. If the reason is a contract violation - i.e. the message that was handled did not
  759. conform to the protocol specification - InvalidMessageError, which is a subclass,
  760. should be used instead.
  761. If any message handler raises an exception not derived from this class, it will
  762. escape the message loop unhandled, and terminate the process.
  763. If any message handler raises this exception, but applies_to(message) is False, it
  764. is treated as if it was a generic exception, as desribed above. Thus, if a request
  765. handler issues another request of its own, and that one fails, the failure is not
  766. silently propagated. However, a request that is delegated via Request.delegate()
  767. will also propagate failures back automatically. For manual propagation, catch the
  768. exception, and call exc.propagate().
  769. If any event handler raises this exception, and applies_to(event) is True, the
  770. exception is silently swallowed by the message loop.
  771. If any request handler raises this exception, and applies_to(request) is True, the
  772. exception is silently swallowed by the message loop, and a failure response is sent
  773. with "message" set to str(reason).
  774. Note that, while errors are not logged when they're swallowed by the message loop,
  775. by that time they have already been logged by their __init__ (when instantiated).
  776. """
  777. def __init__(self, reason, cause=None, silent=False):
  778. """Creates a new instance of this class, and immediately logs the exception.
  779. Message handling errors are logged immediately unless silent=True, so that the
  780. precise context in which they occured can be determined from the surrounding
  781. log entries.
  782. """
  783. self.reason = reason
  784. """Why it couldn't be handled. This can be any object, but usually it's either
  785. str or Exception.
  786. """
  787. assert cause is None or isinstance(cause, Message)
  788. self.cause = cause
  789. """The Message object for the message that couldn't be handled. For responses
  790. to unknown requests, this is a synthetic Request.
  791. """
  792. if not silent:
  793. try:
  794. raise self
  795. except MessageHandlingError:
  796. log.swallow_exception()
  797. def __hash__(self):
  798. return hash((self.reason, id(self.cause)))
  799. def __eq__(self, other):
  800. if not isinstance(other, MessageHandlingError):
  801. return NotImplemented
  802. if type(self) is not type(other):
  803. return NotImplemented
  804. if self.reason != other.reason:
  805. return False
  806. if self.cause is not None and other.cause is not None:
  807. if self.cause.seq != other.cause.seq:
  808. return False
  809. return True
  810. def __ne__(self, other):
  811. return not self == other
  812. def __str__(self):
  813. return str(self.reason)
  814. def __repr__(self):
  815. s = type(self).__name__
  816. if self.cause is None:
  817. s += f"reason={self.reason!r})"
  818. else:
  819. s += f"channel={self.cause.channel.name!r}, cause={self.cause.seq!r}, reason={self.reason!r})"
  820. return s
  821. def applies_to(self, message):
  822. """Whether this MessageHandlingError can be treated as a reason why the
  823. handling of message failed.
  824. If self.cause is None, this is always true.
  825. If self.cause is not None, this is only true if cause is message.
  826. """
  827. return self.cause is None or self.cause is message
  828. def propagate(self, new_cause):
  829. """Propagates this error, raising a new instance of the same class with the
  830. same reason, but a different cause.
  831. """
  832. raise type(self)(self.reason, new_cause, silent=True)
  833. class InvalidMessageError(MessageHandlingError):
  834. """Indicates that an incoming message did not follow the protocol specification -
  835. for example, it was missing properties that are required, or the message itself
  836. is not allowed in the current state.
  837. Raised by MessageDict in lieu of KeyError for missing keys.
  838. """
  839. PREFIX = "Invalid message: "
  840. """Automatically prepended to the "message" property in JSON responses, when the
  841. handler raises InvalidMessageError.
  842. If a failed response has "message" property that starts with this prefix, it is
  843. reported as InvalidMessageError rather than MessageHandlingError.
  844. """
  845. def __str__(self):
  846. return InvalidMessageError.PREFIX + str(self.reason)
  847. class JsonMessageChannel(object):
  848. """Implements a JSON message channel on top of a raw JSON message stream, with
  849. support for DAP requests, responses, and events.
  850. The channel can be locked for exclusive use via the with-statement::
  851. with channel:
  852. channel.send_request(...)
  853. # No interleaving messages can be sent here from other threads.
  854. channel.send_event(...)
  855. """
  856. def __init__(self, stream, handlers=None, name=None):
  857. self.stream = stream
  858. self.handlers = handlers
  859. self.name = name if name is not None else stream.name
  860. self.started = False
  861. self._lock = threading.RLock()
  862. self._closed = False
  863. self._seq_iter = itertools.count(1)
  864. self._sent_requests = {} # {seq: Request}
  865. self._handler_queue = [] # [(what, handler)]
  866. self._handlers_enqueued = threading.Condition(self._lock)
  867. self._handler_thread = None
  868. self._parser_thread = None
  869. def __str__(self):
  870. return self.name
  871. def __repr__(self):
  872. return f"{type(self).__name__}({self.name!r})"
  873. def __enter__(self):
  874. self._lock.acquire()
  875. return self
  876. def __exit__(self, exc_type, exc_value, exc_tb):
  877. self._lock.release()
  878. def close(self):
  879. """Closes the underlying stream.
  880. This does not immediately terminate any handlers that are already executing,
  881. but they will be unable to respond. No new request or event handlers will
  882. execute after this method is called, even for messages that have already been
  883. received. However, response handlers will continue to executed for any request
  884. that is still pending, as will any handlers registered via on_response().
  885. """
  886. with self:
  887. if not self._closed:
  888. self._closed = True
  889. self.stream.close()
  890. def start(self):
  891. """Starts a message loop which parses incoming messages and invokes handlers
  892. for them on a background thread, until the channel is closed.
  893. Incoming messages, including responses to requests, will not be processed at
  894. all until this is invoked.
  895. """
  896. assert not self.started
  897. self.started = True
  898. self._parser_thread = threading.Thread(
  899. target=self._parse_incoming_messages, name=f"{self} message parser"
  900. )
  901. hide_thread_from_debugger(self._parser_thread)
  902. self._parser_thread.daemon = True
  903. self._parser_thread.start()
  904. def wait(self):
  905. """Waits for the message loop to terminate, and for all enqueued Response
  906. message handlers to finish executing.
  907. """
  908. parser_thread = self._parser_thread
  909. try:
  910. if parser_thread is not None:
  911. parser_thread.join()
  912. except AssertionError:
  913. log.debug("Handled error joining parser thread.")
  914. try:
  915. handler_thread = self._handler_thread
  916. if handler_thread is not None:
  917. handler_thread.join()
  918. except AssertionError:
  919. log.debug("Handled error joining handler thread.")
  920. # Order of keys for _prettify() - follows the order of properties in
  921. # https://microsoft.github.io/debug-adapter-protocol/specification
  922. _prettify_order = (
  923. "seq",
  924. "type",
  925. "request_seq",
  926. "success",
  927. "command",
  928. "event",
  929. "message",
  930. "arguments",
  931. "body",
  932. "error",
  933. )
  934. def _prettify(self, message_dict):
  935. """Reorders items in a MessageDict such that it is more readable."""
  936. for key in self._prettify_order:
  937. if key not in message_dict:
  938. continue
  939. value = message_dict[key]
  940. del message_dict[key]
  941. message_dict[key] = value
  942. @contextlib.contextmanager
  943. def _send_message(self, message):
  944. """Sends a new message to the other party.
  945. Generates a new sequence number for the message, and provides it to the
  946. caller before the message is sent, using the context manager protocol::
  947. with send_message(...) as seq:
  948. # The message hasn't been sent yet.
  949. ...
  950. # Now the message has been sent.
  951. Safe to call concurrently for the same channel from different threads.
  952. """
  953. assert "seq" not in message
  954. with self:
  955. seq = next(self._seq_iter)
  956. message = MessageDict(None, message)
  957. message["seq"] = seq
  958. self._prettify(message)
  959. with self:
  960. yield seq
  961. self.stream.write_json(message)
  962. def send_request(self, command, arguments=None, on_before_send=None):
  963. """Sends a new request, and returns the OutgoingRequest object for it.
  964. If arguments is None or {}, "arguments" will be omitted in JSON.
  965. If on_before_send is not None, invokes on_before_send() with the request
  966. object as the sole argument, before the request actually gets sent.
  967. Does not wait for response - use OutgoingRequest.wait_for_response().
  968. Safe to call concurrently for the same channel from different threads.
  969. """
  970. d = {"type": "request", "command": command}
  971. if arguments is not None and arguments != {}:
  972. d["arguments"] = arguments
  973. with self._send_message(d) as seq:
  974. request = OutgoingRequest(self, seq, command, arguments)
  975. if on_before_send is not None:
  976. on_before_send(request)
  977. self._sent_requests[seq] = request
  978. return request
  979. def send_event(self, event, body=None):
  980. """Sends a new event.
  981. If body is None or {}, "body" will be omitted in JSON.
  982. Safe to call concurrently for the same channel from different threads.
  983. """
  984. d = {"type": "event", "event": event}
  985. if body is not None and body != {}:
  986. d["body"] = body
  987. with self._send_message(d):
  988. pass
  989. def request(self, *args, **kwargs):
  990. """Same as send_request(...).wait_for_response()"""
  991. return self.send_request(*args, **kwargs).wait_for_response()
  992. def propagate(self, message):
  993. """Sends a new message with the same type and payload.
  994. If it was a request, returns the new OutgoingRequest object for it.
  995. """
  996. assert message.is_request() or message.is_event()
  997. if message.is_request():
  998. return self.send_request(message.command, message.arguments)
  999. else:
  1000. self.send_event(message.event, message.body)
  1001. def delegate(self, message):
  1002. """Like propagate(message).wait_for_response(), but will also propagate
  1003. any resulting MessageHandlingError back.
  1004. """
  1005. try:
  1006. result = self.propagate(message)
  1007. if result.is_request():
  1008. result = result.wait_for_response()
  1009. return result
  1010. except MessageHandlingError as exc:
  1011. exc.propagate(message)
  1012. def _parse_incoming_messages(self):
  1013. log.debug("Starting message loop for channel {0}", self)
  1014. try:
  1015. while True:
  1016. self._parse_incoming_message()
  1017. except NoMoreMessages as exc:
  1018. log.debug("Exiting message loop for channel {0}: {1}", self, exc)
  1019. with self:
  1020. # Generate dummy responses for all outstanding requests.
  1021. err_message = str(exc)
  1022. # Response._parse() will remove items from _sent_requests, so
  1023. # make a snapshot before iterating.
  1024. sent_requests = list(self._sent_requests.values())
  1025. for request in sent_requests:
  1026. response_json = MessageDict(
  1027. None,
  1028. {
  1029. "seq": -1,
  1030. "request_seq": request.seq,
  1031. "command": request.command,
  1032. "success": False,
  1033. "message": err_message,
  1034. },
  1035. )
  1036. Response._parse(self, response_json, body=exc)
  1037. assert not len(self._sent_requests)
  1038. self._enqueue_handlers(Disconnect(self), self._handle_disconnect)
  1039. self.close()
  1040. _message_parsers = {
  1041. "event": Event._parse,
  1042. "request": Request._parse,
  1043. "response": Response._parse,
  1044. }
  1045. def _parse_incoming_message(self):
  1046. """Reads incoming messages, parses them, and puts handlers into the queue
  1047. for _run_handlers() to invoke, until the channel is closed.
  1048. """
  1049. # Set up a dedicated decoder for this message, to create MessageDict instances
  1050. # for all JSON objects, and track them so that they can be later wired up to
  1051. # the Message they belong to, once it is instantiated.
  1052. def object_hook(d):
  1053. d = MessageDict(None, d)
  1054. if "seq" in d:
  1055. self._prettify(d)
  1056. d.associate_with = associate_with
  1057. message_dicts.append(d)
  1058. return d
  1059. # A hack to work around circular dependency between messages, and instances of
  1060. # MessageDict in their payload. We need to set message for all of them, but it
  1061. # cannot be done until the actual Message is created - which happens after the
  1062. # dicts are created during deserialization.
  1063. #
  1064. # So, upon deserialization, every dict in the message payload gets a method
  1065. # that can be called to set MessageDict.message for *all* dicts belonging to
  1066. # that message. This method can then be invoked on the top-level dict by the
  1067. # parser, after it has parsed enough of the dict to create the appropriate
  1068. # instance of Event, Request, or Response for this message.
  1069. def associate_with(message):
  1070. for d in message_dicts:
  1071. d.message = message
  1072. del d.associate_with
  1073. message_dicts = []
  1074. decoder = self.stream.json_decoder_factory(object_hook=object_hook)
  1075. message_dict = self.stream.read_json(decoder)
  1076. assert isinstance(message_dict, MessageDict) # make sure stream used decoder
  1077. msg_type = message_dict("type", json.enum("event", "request", "response"))
  1078. parser = self._message_parsers[msg_type]
  1079. try:
  1080. parser(self, message_dict)
  1081. except InvalidMessageError as exc:
  1082. log.error(
  1083. "Failed to parse message in channel {0}: {1} in:\n{2}",
  1084. self,
  1085. str(exc),
  1086. json.repr(message_dict),
  1087. )
  1088. except Exception as exc:
  1089. if isinstance(exc, NoMoreMessages) and exc.stream is self.stream:
  1090. raise
  1091. log.swallow_exception(
  1092. "Fatal error in channel {0} while parsing:\n{1}",
  1093. self,
  1094. json.repr(message_dict),
  1095. )
  1096. os._exit(1)
  1097. def _enqueue_handlers(self, what, *handlers):
  1098. """Enqueues handlers for _run_handlers() to run.
  1099. `what` is the Message being handled, and is used for logging purposes.
  1100. If the background thread with _run_handlers() isn't running yet, starts it.
  1101. """
  1102. with self:
  1103. self._handler_queue.extend((what, handler) for handler in handlers)
  1104. self._handlers_enqueued.notify_all()
  1105. # If there is anything to handle, but there's no handler thread yet,
  1106. # spin it up. This will normally happen only once, on the first call
  1107. # to _enqueue_handlers(), and that thread will run all the handlers
  1108. # for parsed messages. However, this can also happen is somebody calls
  1109. # Request.on_response() - possibly concurrently from multiple threads -
  1110. # after the channel has already been closed, and the initial handler
  1111. # thread has exited. In this case, we spin up a new thread just to run
  1112. # the enqueued response handlers, and it will exit as soon as it's out
  1113. # of handlers to run.
  1114. if len(self._handler_queue) and self._handler_thread is None:
  1115. self._handler_thread = threading.Thread(
  1116. target=self._run_handlers,
  1117. name=f"{self} message handler",
  1118. )
  1119. hide_thread_from_debugger(self._handler_thread)
  1120. self._handler_thread.start()
  1121. def _run_handlers(self):
  1122. """Runs enqueued handlers until the channel is closed, or until the handler
  1123. queue is empty once the channel is closed.
  1124. """
  1125. while True:
  1126. with self:
  1127. closed = self._closed
  1128. if closed:
  1129. # Wait for the parser thread to wrap up and enqueue any remaining
  1130. # handlers, if it is still running.
  1131. self._parser_thread.join()
  1132. # From this point on, _enqueue_handlers() can only get called
  1133. # from Request.on_response().
  1134. with self:
  1135. if not closed and not len(self._handler_queue):
  1136. # Wait for something to process.
  1137. self._handlers_enqueued.wait()
  1138. # Make a snapshot before releasing the lock.
  1139. handlers = self._handler_queue[:]
  1140. del self._handler_queue[:]
  1141. if closed and not len(handlers):
  1142. # Nothing to process, channel is closed, and parser thread is
  1143. # not running anymore - time to quit! If Request.on_response()
  1144. # needs to call _enqueue_handlers() later, it will spin up
  1145. # a new handler thread.
  1146. self._handler_thread = None
  1147. return
  1148. for what, handler in handlers:
  1149. # If the channel is closed, we don't want to process any more events
  1150. # or requests - only responses and the final disconnect handler. This
  1151. # is to guarantee that if a handler calls close() on its own channel,
  1152. # the corresponding request or event is the last thing to be processed.
  1153. if closed and handler in (Event._handle, Request._handle):
  1154. continue
  1155. with log.prefixed("/handling {0}/\n", what.describe()):
  1156. try:
  1157. handler()
  1158. except Exception:
  1159. # It's already logged by the handler, so just fail fast.
  1160. self.close()
  1161. os._exit(1)
  1162. def _get_handler_for(self, type, name):
  1163. """Returns the handler for a message of a given type."""
  1164. with self:
  1165. handlers = self.handlers
  1166. for handler_name in (name + "_" + type, type):
  1167. try:
  1168. return getattr(handlers, handler_name)
  1169. except AttributeError:
  1170. continue
  1171. raise AttributeError(
  1172. "handler object {0} for channel {1} has no handler for {2} {3!r}".format(
  1173. util.srcnameof(handlers),
  1174. self,
  1175. type,
  1176. name,
  1177. )
  1178. )
  1179. def _handle_disconnect(self):
  1180. handler = getattr(self.handlers, "disconnect", lambda: None)
  1181. try:
  1182. handler()
  1183. except Exception:
  1184. log.reraise_exception(
  1185. "Handler {0}\ncouldn't handle disconnect from {1}:",
  1186. util.srcnameof(handler),
  1187. self,
  1188. )
  1189. class MessageHandlers(object):
  1190. """A simple delegating message handlers object for use with JsonMessageChannel.
  1191. For every argument provided, the object gets an attribute with the corresponding
  1192. name and value.
  1193. """
  1194. def __init__(self, **kwargs):
  1195. for name, func in kwargs.items():
  1196. setattr(self, name, func)