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