manager.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """Base class to manage comms"""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import logging
  5. import comm.base_comm
  6. import traitlets
  7. import traitlets.config
  8. from .comm import Comm
  9. logger = logging.getLogger("ipykernel.comm")
  10. class CommManager(comm.base_comm.CommManager, traitlets.config.LoggingConfigurable): # type:ignore[misc]
  11. """A comm manager."""
  12. kernel = traitlets.Instance("ipykernel.kernelbase.Kernel")
  13. comms = traitlets.Dict()
  14. targets = traitlets.Dict()
  15. def __init__(self, **kwargs):
  16. """Initialize the manager."""
  17. # CommManager doesn't take arguments, so we explicitly forward arguments
  18. comm.base_comm.CommManager.__init__(self)
  19. traitlets.config.LoggingConfigurable.__init__(self, **kwargs)
  20. def comm_open(self, stream, ident, msg):
  21. """Handler for comm_open messages"""
  22. # This is for backward compatibility, the comm_open creates a a new ipykernel.comm.Comm
  23. # but we should let the base class create the comm with comm.create_comm in a major release
  24. content = msg["content"]
  25. comm_id = content["comm_id"]
  26. target_name = content["target_name"]
  27. f = self.targets.get(target_name, None)
  28. comm = Comm(
  29. comm_id=comm_id,
  30. primary=False,
  31. target_name=target_name,
  32. show_warning=False,
  33. )
  34. self.register_comm(comm)
  35. if f is None:
  36. logger.error("No such comm target registered: %s", target_name)
  37. else:
  38. try:
  39. f(comm, msg)
  40. return
  41. except Exception:
  42. logger.error("Exception opening comm with target: %s", target_name, exc_info=True) # noqa: G201
  43. # Failure.
  44. try:
  45. comm.close()
  46. except Exception:
  47. logger.error( # noqa: G201
  48. """Could not close comm during `comm_open` failure
  49. clean-up. The comm may not have been opened yet.""",
  50. exc_info=True,
  51. )