components.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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. import functools
  5. from debugpy.common import json, log, messaging, util
  6. ACCEPT_CONNECTIONS_TIMEOUT = 60
  7. class ComponentNotAvailable(Exception):
  8. def __init__(self, type):
  9. super().__init__(f"{type.__name__} is not available")
  10. class Component(util.Observable):
  11. """A component managed by a debug adapter: client, launcher, or debug server.
  12. Every component belongs to a Session, which is used for synchronization and
  13. shared data.
  14. Every component has its own message channel, and provides message handlers for
  15. that channel. All handlers should be decorated with @Component.message_handler,
  16. which ensures that Session is locked for the duration of the handler. Thus, only
  17. one handler is running at any given time across all components, unless the lock
  18. is released explicitly or via Session.wait_for().
  19. Components report changes to their attributes to Session, allowing one component
  20. to wait_for() a change caused by another component.
  21. """
  22. def __init__(self, session, stream=None, channel=None):
  23. assert (stream is None) ^ (channel is None)
  24. try:
  25. lock_held = session.lock.acquire(blocking=False)
  26. assert lock_held, "__init__ of a Component subclass must lock its Session"
  27. finally:
  28. session.lock.release()
  29. super().__init__()
  30. self.session = session
  31. if channel is None:
  32. stream.name = str(self)
  33. channel = messaging.JsonMessageChannel(stream, self)
  34. channel.start()
  35. else:
  36. channel.name = channel.stream.name = str(self)
  37. channel.handlers = self
  38. self.channel = channel
  39. self.is_connected = True
  40. # Do this last to avoid triggering useless notifications for assignments above.
  41. self.observers += [lambda *_: self.session.notify_changed()]
  42. def __str__(self):
  43. return f"{type(self).__name__}[{self.session.id}]"
  44. @property
  45. def client(self):
  46. return self.session.client
  47. @property
  48. def launcher(self):
  49. return self.session.launcher
  50. @property
  51. def server(self):
  52. return self.session.server
  53. def wait_for(self, *args, **kwargs):
  54. return self.session.wait_for(*args, **kwargs)
  55. @staticmethod
  56. def message_handler(f):
  57. """Applied to a message handler to automatically lock and unlock the session
  58. for its duration, and to validate the session state.
  59. If the handler raises ComponentNotAvailable or JsonIOError, converts it to
  60. Message.cant_handle().
  61. """
  62. @functools.wraps(f)
  63. def lock_and_handle(self, message):
  64. try:
  65. with self.session:
  66. return f(self, message)
  67. except ComponentNotAvailable as exc:
  68. raise message.cant_handle("{0}", exc, silent=True)
  69. except messaging.MessageHandlingError as exc:
  70. if exc.cause is message:
  71. raise
  72. else:
  73. exc.propagate(message)
  74. except messaging.JsonIOError as exc:
  75. raise message.cant_handle(
  76. "{0} disconnected unexpectedly", exc.stream.name, silent=True
  77. )
  78. return lock_and_handle
  79. def disconnect(self):
  80. with self.session:
  81. self.is_connected = False
  82. self.session.finalize("{0} has disconnected".format(self))
  83. def missing(session, type):
  84. class Missing(object):
  85. """A dummy component that raises ComponentNotAvailable whenever some
  86. attribute is accessed on it.
  87. """
  88. __getattr__ = __setattr__ = lambda self, *_: report()
  89. __bool__ = __nonzero__ = lambda self: False
  90. def report():
  91. try:
  92. raise ComponentNotAvailable(type)
  93. except Exception as exc:
  94. log.reraise_exception("{0} in {1}", exc, session)
  95. return Missing()
  96. class Capabilities(dict):
  97. """A collection of feature flags for a component. Corresponds to JSON properties
  98. in the DAP "initialize" request or response, other than those that identify the
  99. party.
  100. """
  101. PROPERTIES = {}
  102. """JSON property names and default values for the the capabilities represented
  103. by instances of this class. Keys are names, and values are either default values
  104. or validators.
  105. If the value is callable, it must be a JSON validator; see debugpy.common.json for
  106. details. If the value is not callable, it is as if json.default(value) validator
  107. was used instead.
  108. """
  109. def __init__(self, component, message):
  110. """Parses an "initialize" request or response and extracts the feature flags.
  111. For every "X" in self.PROPERTIES, sets self["X"] to the corresponding value
  112. from message.payload if it's present there, or to the default value otherwise.
  113. """
  114. assert message.is_request("initialize") or message.is_response("initialize")
  115. self.component = component
  116. payload = message.payload
  117. for name, validate in self.PROPERTIES.items():
  118. value = payload.get(name, ())
  119. if not callable(validate):
  120. validate = json.default(validate)
  121. try:
  122. value = validate(value)
  123. except Exception as exc:
  124. raise message.isnt_valid("{0} {1}", json.repr(name), exc)
  125. assert (
  126. value != ()
  127. ), f"{validate} must provide a default value for missing properties."
  128. self[name] = value
  129. log.debug("{0}", self)
  130. def __repr__(self):
  131. return f"{type(self).__name__}: {json.repr(dict(self))}"
  132. def require(self, *keys):
  133. for key in keys:
  134. if not self[key]:
  135. raise messaging.MessageHandlingError(
  136. f"{self.component} does not have capability {json.repr(key)}",
  137. )