2024-01-01 14:58:21 -05:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2023-09-15 20:42:09 -04:00
|
|
|
|
|
|
|
// This file is forked/ported from <https://github.com/evcxr/evcxr>
|
|
|
|
// Copyright 2020 The Evcxr Authors. MIT license.
|
|
|
|
|
2024-07-04 18:12:14 -04:00
|
|
|
// NOTE(bartlomieju): unfortunately it appears that clippy is broken
|
|
|
|
// and can't allow a single line ignore for `await_holding_lock`.
|
|
|
|
#![allow(clippy::await_holding_lock)]
|
|
|
|
|
2023-09-15 20:42:09 -04:00
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::rc::Rc;
|
|
|
|
use std::sync::Arc;
|
|
|
|
|
2023-11-05 17:58:59 -05:00
|
|
|
use crate::cdp;
|
2023-09-15 20:42:09 -04:00
|
|
|
use crate::tools::repl;
|
2024-07-02 18:37:54 -04:00
|
|
|
use deno_core::anyhow::bail;
|
2023-09-15 20:42:09 -04:00
|
|
|
use deno_core::error::AnyError;
|
|
|
|
use deno_core::futures;
|
2024-07-04 18:12:14 -04:00
|
|
|
use deno_core::parking_lot::Mutex;
|
2023-09-15 20:42:09 -04:00
|
|
|
use deno_core::serde_json;
|
|
|
|
use deno_core::CancelFuture;
|
|
|
|
use deno_core::CancelHandle;
|
2024-07-27 04:39:08 -04:00
|
|
|
use jupyter_runtime::ExecutionCount;
|
2023-09-26 20:21:06 -04:00
|
|
|
use tokio::sync::mpsc;
|
2024-07-02 18:37:54 -04:00
|
|
|
use tokio::sync::oneshot;
|
2023-09-15 20:42:09 -04:00
|
|
|
|
2024-05-29 18:46:47 -04:00
|
|
|
use jupyter_runtime::messaging;
|
|
|
|
use jupyter_runtime::ConnectionInfo;
|
|
|
|
use jupyter_runtime::JupyterMessage;
|
|
|
|
use jupyter_runtime::JupyterMessageContent;
|
|
|
|
use jupyter_runtime::KernelControlConnection;
|
|
|
|
use jupyter_runtime::KernelIoPubConnection;
|
|
|
|
use jupyter_runtime::KernelShellConnection;
|
|
|
|
use jupyter_runtime::ReplyError;
|
|
|
|
use jupyter_runtime::ReplyStatus;
|
|
|
|
use jupyter_runtime::StreamContent;
|
2024-07-27 04:39:08 -04:00
|
|
|
use uuid::Uuid;
|
2023-09-15 20:42:09 -04:00
|
|
|
|
2024-07-02 18:37:54 -04:00
|
|
|
use super::JupyterReplProxy;
|
|
|
|
|
2023-09-15 20:42:09 -04:00
|
|
|
pub struct JupyterServer {
|
2024-07-27 04:39:08 -04:00
|
|
|
execution_count: ExecutionCount,
|
2024-07-02 18:37:54 -04:00
|
|
|
last_execution_request: Arc<Mutex<Option<JupyterMessage>>>,
|
2024-05-21 16:35:21 -04:00
|
|
|
iopub_connection: Arc<Mutex<KernelIoPubConnection>>,
|
2024-07-02 18:37:54 -04:00
|
|
|
repl_session_proxy: JupyterReplProxy,
|
|
|
|
}
|
|
|
|
|
2024-07-04 18:12:14 -04:00
|
|
|
pub struct StdinConnectionProxy {
|
|
|
|
pub tx: mpsc::UnboundedSender<JupyterMessage>,
|
|
|
|
pub rx: mpsc::UnboundedReceiver<JupyterMessage>,
|
|
|
|
}
|
|
|
|
|
2024-07-02 18:37:54 -04:00
|
|
|
pub struct StartupData {
|
|
|
|
pub iopub_connection: Arc<Mutex<KernelIoPubConnection>>,
|
2024-07-04 18:12:14 -04:00
|
|
|
pub stdin_connection_proxy: Arc<Mutex<StdinConnectionProxy>>,
|
2024-07-02 18:37:54 -04:00
|
|
|
pub last_execution_request: Arc<Mutex<Option<JupyterMessage>>>,
|
2023-09-15 20:42:09 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
impl JupyterServer {
|
|
|
|
pub async fn start(
|
2024-05-21 16:35:21 -04:00
|
|
|
connection_info: ConnectionInfo,
|
|
|
|
mut stdio_rx: mpsc::UnboundedReceiver<StreamContent>,
|
2024-07-02 18:37:54 -04:00
|
|
|
repl_session_proxy: JupyterReplProxy,
|
|
|
|
setup_tx: oneshot::Sender<StartupData>,
|
2023-09-15 20:42:09 -04:00
|
|
|
) -> Result<(), AnyError> {
|
2024-07-27 04:39:08 -04:00
|
|
|
let session_id = Uuid::new_v4().to_string();
|
|
|
|
|
2023-09-15 20:42:09 -04:00
|
|
|
let mut heartbeat =
|
2024-05-21 16:35:21 -04:00
|
|
|
connection_info.create_kernel_heartbeat_connection().await?;
|
2024-07-27 04:39:08 -04:00
|
|
|
let shell_connection = connection_info
|
|
|
|
.create_kernel_shell_connection(&session_id)
|
|
|
|
.await?;
|
|
|
|
let control_connection = connection_info
|
|
|
|
.create_kernel_control_connection(&session_id)
|
|
|
|
.await?;
|
|
|
|
let mut stdin_connection = connection_info
|
|
|
|
.create_kernel_stdin_connection(&session_id)
|
|
|
|
.await?;
|
|
|
|
let iopub_connection = connection_info
|
|
|
|
.create_kernel_iopub_connection(&session_id)
|
|
|
|
.await?;
|
2024-05-21 16:35:21 -04:00
|
|
|
|
|
|
|
let iopub_connection = Arc::new(Mutex::new(iopub_connection));
|
2024-07-02 18:37:54 -04:00
|
|
|
let last_execution_request = Arc::new(Mutex::new(None));
|
|
|
|
|
2024-07-04 18:12:14 -04:00
|
|
|
let (stdin_tx1, mut stdin_rx1) =
|
|
|
|
mpsc::unbounded_channel::<JupyterMessage>();
|
|
|
|
let (stdin_tx2, stdin_rx2) = mpsc::unbounded_channel::<JupyterMessage>();
|
|
|
|
|
|
|
|
let stdin_connection_proxy = Arc::new(Mutex::new(StdinConnectionProxy {
|
|
|
|
tx: stdin_tx1,
|
|
|
|
rx: stdin_rx2,
|
|
|
|
}));
|
|
|
|
|
2024-07-02 18:37:54 -04:00
|
|
|
let Ok(()) = setup_tx.send(StartupData {
|
|
|
|
iopub_connection: iopub_connection.clone(),
|
|
|
|
last_execution_request: last_execution_request.clone(),
|
2024-07-04 18:12:14 -04:00
|
|
|
stdin_connection_proxy,
|
2024-07-02 18:37:54 -04:00
|
|
|
}) else {
|
|
|
|
bail!("Failed to send startup data");
|
|
|
|
};
|
2023-09-26 20:21:06 -04:00
|
|
|
|
2023-09-15 20:42:09 -04:00
|
|
|
let cancel_handle = CancelHandle::new_rc();
|
|
|
|
|
|
|
|
let mut server = Self {
|
2024-07-27 04:39:08 -04:00
|
|
|
execution_count: ExecutionCount::new(0),
|
2024-05-21 16:35:21 -04:00
|
|
|
iopub_connection: iopub_connection.clone(),
|
2023-09-15 20:42:09 -04:00
|
|
|
last_execution_request: last_execution_request.clone(),
|
2024-07-02 18:37:54 -04:00
|
|
|
repl_session_proxy,
|
2023-09-15 20:42:09 -04:00
|
|
|
};
|
|
|
|
|
2024-07-04 18:12:14 -04:00
|
|
|
let stdin_fut = deno_core::unsync::spawn(async move {
|
|
|
|
loop {
|
|
|
|
let Some(msg) = stdin_rx1.recv().await else {
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
let Ok(()) = stdin_connection.send(msg).await else {
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
|
|
|
|
let Ok(msg) = stdin_connection.read().await else {
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
let Ok(()) = stdin_tx2.send(msg) else {
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2024-07-02 18:37:54 -04:00
|
|
|
let hearbeat_fut = deno_core::unsync::spawn(async move {
|
|
|
|
loop {
|
|
|
|
if let Err(err) = heartbeat.single_heartbeat().await {
|
|
|
|
log::error!(
|
|
|
|
"Heartbeat error: {}\nBacktrace:\n{}",
|
|
|
|
err,
|
|
|
|
err.backtrace()
|
|
|
|
);
|
|
|
|
}
|
2023-09-15 20:42:09 -04:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2024-07-02 18:37:54 -04:00
|
|
|
let control_fut = deno_core::unsync::spawn({
|
2024-04-30 22:30:40 -04:00
|
|
|
let cancel_handle = cancel_handle.clone();
|
|
|
|
async move {
|
|
|
|
if let Err(err) =
|
2024-05-21 16:35:21 -04:00
|
|
|
Self::handle_control(control_connection, cancel_handle).await
|
2024-04-30 22:30:40 -04:00
|
|
|
{
|
2024-05-21 16:35:21 -04:00
|
|
|
log::error!(
|
|
|
|
"Control error: {}\nBacktrace:\n{}",
|
|
|
|
err,
|
|
|
|
err.backtrace()
|
|
|
|
);
|
2024-04-30 22:30:40 -04:00
|
|
|
}
|
2023-09-15 20:42:09 -04:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2024-07-02 18:37:54 -04:00
|
|
|
let shell_fut = deno_core::unsync::spawn(async move {
|
2024-05-21 16:35:21 -04:00
|
|
|
if let Err(err) = server.handle_shell(shell_connection).await {
|
|
|
|
log::error!("Shell error: {}\nBacktrace:\n{}", err, err.backtrace());
|
2023-09-15 20:42:09 -04:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2024-07-02 18:37:54 -04:00
|
|
|
let stdio_fut = deno_core::unsync::spawn(async move {
|
2023-09-26 20:21:06 -04:00
|
|
|
while let Some(stdio_msg) = stdio_rx.recv().await {
|
2023-09-15 20:42:09 -04:00
|
|
|
Self::handle_stdio_msg(
|
2024-05-21 16:35:21 -04:00
|
|
|
iopub_connection.clone(),
|
2023-09-15 20:42:09 -04:00
|
|
|
last_execution_request.clone(),
|
|
|
|
stdio_msg,
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2024-07-02 18:37:54 -04:00
|
|
|
let repl_session_fut = deno_core::unsync::spawn(async move {});
|
|
|
|
|
|
|
|
let join_fut = futures::future::try_join_all(vec![
|
|
|
|
hearbeat_fut,
|
|
|
|
control_fut,
|
|
|
|
shell_fut,
|
|
|
|
stdio_fut,
|
|
|
|
repl_session_fut,
|
2024-07-04 18:12:14 -04:00
|
|
|
stdin_fut,
|
2024-07-02 18:37:54 -04:00
|
|
|
]);
|
2023-09-15 20:42:09 -04:00
|
|
|
|
|
|
|
if let Ok(result) = join_fut.or_cancel(cancel_handle).await {
|
|
|
|
result?;
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2024-05-21 16:35:21 -04:00
|
|
|
async fn handle_stdio_msg(
|
|
|
|
iopub_connection: Arc<Mutex<KernelIoPubConnection>>,
|
2024-07-02 18:37:54 -04:00
|
|
|
last_execution_request: Arc<Mutex<Option<JupyterMessage>>>,
|
2024-05-21 16:35:21 -04:00
|
|
|
stdio_msg: StreamContent,
|
2023-09-15 20:42:09 -04:00
|
|
|
) {
|
2024-07-04 18:12:14 -04:00
|
|
|
let maybe_exec_result = last_execution_request.lock().clone();
|
2024-07-02 18:37:54 -04:00
|
|
|
let Some(exec_request) = maybe_exec_result else {
|
|
|
|
return;
|
|
|
|
};
|
2023-09-15 20:42:09 -04:00
|
|
|
|
2024-07-04 18:12:14 -04:00
|
|
|
let result = iopub_connection
|
|
|
|
.lock()
|
|
|
|
.send(stdio_msg.as_child_of(&exec_request))
|
|
|
|
.await;
|
2023-09-15 20:42:09 -04:00
|
|
|
|
2024-07-02 18:37:54 -04:00
|
|
|
if let Err(err) = result {
|
|
|
|
log::error!("Output error: {}", err);
|
2023-09-15 20:42:09 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn handle_control(
|
2024-05-21 16:35:21 -04:00
|
|
|
mut connection: KernelControlConnection,
|
2023-09-15 20:42:09 -04:00
|
|
|
cancel_handle: Rc<CancelHandle>,
|
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
loop {
|
2024-04-30 22:30:40 -04:00
|
|
|
let msg = connection.read().await?;
|
2024-05-21 16:35:21 -04:00
|
|
|
|
|
|
|
match msg.content {
|
|
|
|
JupyterMessageContent::KernelInfoRequest(_) => {
|
|
|
|
// normally kernel info is sent from the shell channel
|
|
|
|
// however, some frontends will send it on the control channel
|
|
|
|
// and it's no harm to send a kernel info reply on control
|
|
|
|
connection.send(kernel_info().as_child_of(&msg)).await?;
|
2023-09-15 20:42:09 -04:00
|
|
|
}
|
2024-05-21 16:35:21 -04:00
|
|
|
JupyterMessageContent::ShutdownRequest(_) => {
|
2023-09-15 20:42:09 -04:00
|
|
|
cancel_handle.cancel();
|
|
|
|
}
|
2024-05-21 16:35:21 -04:00
|
|
|
JupyterMessageContent::InterruptRequest(_) => {
|
2024-05-08 22:45:06 -04:00
|
|
|
log::error!("Interrupt request currently not supported");
|
2023-09-15 20:42:09 -04:00
|
|
|
}
|
2024-05-21 16:35:21 -04:00
|
|
|
JupyterMessageContent::DebugRequest(_) => {
|
|
|
|
log::error!("Debug request currently not supported");
|
|
|
|
// See https://jupyter-client.readthedocs.io/en/latest/messaging.html#debug-request
|
|
|
|
// and https://microsoft.github.io/debug-adapter-protocol/
|
|
|
|
}
|
2023-09-15 20:42:09 -04:00
|
|
|
_ => {
|
2024-05-08 22:45:06 -04:00
|
|
|
log::error!(
|
2023-09-15 20:42:09 -04:00
|
|
|
"Unrecognized control message type: {}",
|
|
|
|
msg.message_type()
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn handle_shell(
|
|
|
|
&mut self,
|
2024-05-21 16:35:21 -04:00
|
|
|
mut connection: KernelShellConnection,
|
2023-09-15 20:42:09 -04:00
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
loop {
|
2024-04-30 22:30:40 -04:00
|
|
|
let msg = connection.read().await?;
|
2023-09-15 20:42:09 -04:00
|
|
|
self.handle_shell_message(msg, &mut connection).await?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn handle_shell_message(
|
|
|
|
&mut self,
|
|
|
|
msg: JupyterMessage,
|
2024-05-21 16:35:21 -04:00
|
|
|
connection: &mut KernelShellConnection,
|
2023-09-15 20:42:09 -04:00
|
|
|
) -> Result<(), AnyError> {
|
2024-05-21 16:35:21 -04:00
|
|
|
let parent = &msg.clone();
|
|
|
|
|
2024-04-30 22:30:40 -04:00
|
|
|
self
|
2024-05-21 16:35:21 -04:00
|
|
|
.send_iopub(messaging::Status::busy().as_child_of(parent))
|
2023-09-15 20:42:09 -04:00
|
|
|
.await?;
|
|
|
|
|
2024-05-21 16:35:21 -04:00
|
|
|
match msg.content {
|
|
|
|
JupyterMessageContent::ExecuteRequest(execute_request) => {
|
2023-09-15 20:42:09 -04:00
|
|
|
self
|
2024-05-21 16:35:21 -04:00
|
|
|
.handle_execution_request(execute_request, parent, connection)
|
2023-09-15 20:42:09 -04:00
|
|
|
.await?;
|
|
|
|
}
|
2024-05-21 16:35:21 -04:00
|
|
|
JupyterMessageContent::CompleteRequest(req) => {
|
|
|
|
let user_code = req.code;
|
|
|
|
let cursor_pos = req.cursor_pos;
|
2023-09-15 20:42:09 -04:00
|
|
|
|
|
|
|
let lsp_completions = self
|
2024-07-02 18:37:54 -04:00
|
|
|
.repl_session_proxy
|
|
|
|
.lsp_completions(user_code.clone(), cursor_pos)
|
2023-09-15 20:42:09 -04:00
|
|
|
.await;
|
|
|
|
|
|
|
|
if !lsp_completions.is_empty() {
|
|
|
|
let matches: Vec<String> = lsp_completions
|
|
|
|
.iter()
|
|
|
|
.map(|item| item.new_text.clone())
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
let cursor_start = lsp_completions
|
|
|
|
.first()
|
|
|
|
.map(|item| item.range.start)
|
|
|
|
.unwrap_or(cursor_pos);
|
|
|
|
|
|
|
|
let cursor_end = lsp_completions
|
|
|
|
.last()
|
|
|
|
.map(|item| item.range.end)
|
|
|
|
.unwrap_or(cursor_pos);
|
|
|
|
|
2024-04-30 22:30:40 -04:00
|
|
|
connection
|
2024-05-21 16:35:21 -04:00
|
|
|
.send(
|
|
|
|
messaging::CompleteReply {
|
|
|
|
matches,
|
|
|
|
cursor_start,
|
|
|
|
cursor_end,
|
|
|
|
metadata: Default::default(),
|
|
|
|
status: ReplyStatus::Ok,
|
|
|
|
error: None,
|
|
|
|
}
|
|
|
|
.as_child_of(parent),
|
|
|
|
)
|
2023-09-15 20:42:09 -04:00
|
|
|
.await?;
|
|
|
|
} else {
|
2024-05-21 16:35:21 -04:00
|
|
|
let expr = get_expr_from_line_at_pos(&user_code, cursor_pos);
|
2023-09-15 20:42:09 -04:00
|
|
|
// check if the expression is in the form `obj.prop`
|
|
|
|
let (completions, cursor_start) = if let Some(index) = expr.rfind('.')
|
|
|
|
{
|
|
|
|
let sub_expr = &expr[..index];
|
|
|
|
let prop_name = &expr[index + 1..];
|
2024-07-02 18:37:54 -04:00
|
|
|
let candidates = get_expression_property_names(
|
|
|
|
&mut self.repl_session_proxy,
|
|
|
|
sub_expr,
|
|
|
|
)
|
|
|
|
.await
|
|
|
|
.into_iter()
|
|
|
|
.filter(|n| {
|
|
|
|
!n.starts_with("Symbol(")
|
|
|
|
&& n.starts_with(prop_name)
|
|
|
|
&& n != &*repl::REPL_INTERNALS_NAME
|
|
|
|
})
|
|
|
|
.collect();
|
2023-09-15 20:42:09 -04:00
|
|
|
|
|
|
|
(candidates, cursor_pos - prop_name.len())
|
|
|
|
} else {
|
|
|
|
// combine results of declarations and globalThis properties
|
|
|
|
let mut candidates = get_expression_property_names(
|
2024-07-02 18:37:54 -04:00
|
|
|
&mut self.repl_session_proxy,
|
2023-09-15 20:42:09 -04:00
|
|
|
"globalThis",
|
|
|
|
)
|
|
|
|
.await
|
|
|
|
.into_iter()
|
2024-07-02 18:37:54 -04:00
|
|
|
.chain(
|
|
|
|
get_global_lexical_scope_names(&mut self.repl_session_proxy)
|
|
|
|
.await,
|
|
|
|
)
|
2023-09-15 20:42:09 -04:00
|
|
|
.filter(|n| n.starts_with(expr) && n != &*repl::REPL_INTERNALS_NAME)
|
|
|
|
.collect::<Vec<_>>();
|
|
|
|
|
|
|
|
// sort and remove duplicates
|
|
|
|
candidates.sort();
|
|
|
|
candidates.dedup(); // make sure to sort first
|
|
|
|
|
|
|
|
(candidates, cursor_pos - expr.len())
|
|
|
|
};
|
2024-05-21 16:35:21 -04:00
|
|
|
|
2024-04-30 22:30:40 -04:00
|
|
|
connection
|
2024-05-21 16:35:21 -04:00
|
|
|
.send(
|
|
|
|
messaging::CompleteReply {
|
|
|
|
matches: completions,
|
|
|
|
cursor_start,
|
|
|
|
cursor_end: cursor_pos,
|
|
|
|
metadata: Default::default(),
|
|
|
|
status: ReplyStatus::Ok,
|
|
|
|
error: None,
|
|
|
|
}
|
|
|
|
.as_child_of(parent),
|
|
|
|
)
|
2023-09-15 20:42:09 -04:00
|
|
|
.await?;
|
|
|
|
}
|
|
|
|
}
|
2024-05-21 16:35:21 -04:00
|
|
|
|
|
|
|
JupyterMessageContent::InspectRequest(_req) => {
|
|
|
|
// TODO(bartlomieju?): implement introspection request
|
|
|
|
// The inspect request is used to get information about an object at cursor position.
|
|
|
|
// There are two detail levels: 0 is typically documentation, 1 is typically source code
|
|
|
|
|
|
|
|
// The response includes a MimeBundle to render the object:
|
|
|
|
// {
|
|
|
|
// "status": "ok",
|
|
|
|
// "found": true,
|
|
|
|
// "data": {
|
|
|
|
// "text/plain": "Plain documentation here",
|
|
|
|
// "text/html": "<div>Rich documentation here</div>",
|
|
|
|
// "application/json": {
|
|
|
|
// "key1": "value1",
|
|
|
|
// "key2": "value2"
|
|
|
|
// }
|
|
|
|
// },
|
|
|
|
// }
|
|
|
|
|
|
|
|
connection
|
|
|
|
.send(
|
|
|
|
messaging::InspectReply {
|
|
|
|
status: ReplyStatus::Ok,
|
|
|
|
found: false,
|
|
|
|
data: Default::default(),
|
|
|
|
metadata: Default::default(),
|
|
|
|
error: None,
|
|
|
|
}
|
|
|
|
.as_child_of(parent),
|
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
}
|
|
|
|
|
|
|
|
JupyterMessageContent::IsCompleteRequest(_) => {
|
|
|
|
connection
|
|
|
|
.send(messaging::IsCompleteReply::complete().as_child_of(parent))
|
|
|
|
.await?;
|
|
|
|
}
|
|
|
|
JupyterMessageContent::KernelInfoRequest(_) => {
|
|
|
|
connection.send(kernel_info().as_child_of(parent)).await?;
|
2023-09-15 20:42:09 -04:00
|
|
|
}
|
2024-05-21 16:35:21 -04:00
|
|
|
JupyterMessageContent::CommOpen(comm) => {
|
|
|
|
connection
|
|
|
|
.send(
|
|
|
|
messaging::CommClose {
|
|
|
|
comm_id: comm.comm_id,
|
|
|
|
data: Default::default(),
|
|
|
|
}
|
|
|
|
.as_child_of(parent),
|
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
}
|
|
|
|
JupyterMessageContent::HistoryRequest(_req) => {
|
|
|
|
connection
|
|
|
|
.send(
|
|
|
|
messaging::HistoryReply {
|
|
|
|
history: vec![],
|
|
|
|
error: None,
|
|
|
|
status: ReplyStatus::Ok,
|
|
|
|
}
|
|
|
|
.as_child_of(parent),
|
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
}
|
|
|
|
JupyterMessageContent::InputReply(_rep) => {
|
|
|
|
// TODO(@zph): implement input reply from https://github.com/denoland/deno/pull/23592
|
|
|
|
// NOTE: This will belong on the stdin channel, not the shell channel
|
|
|
|
}
|
|
|
|
JupyterMessageContent::CommInfoRequest(_req) => {
|
|
|
|
connection
|
|
|
|
.send(
|
|
|
|
messaging::CommInfoReply {
|
|
|
|
comms: Default::default(),
|
|
|
|
status: ReplyStatus::Ok,
|
|
|
|
error: None,
|
|
|
|
}
|
|
|
|
.as_child_of(parent),
|
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
}
|
|
|
|
JupyterMessageContent::CommMsg(_)
|
|
|
|
| JupyterMessageContent::CommClose(_) => {
|
|
|
|
// Do nothing with regular comm messages
|
|
|
|
}
|
|
|
|
// Any unknown message type is ignored
|
2023-09-15 20:42:09 -04:00
|
|
|
_ => {
|
2024-05-21 16:35:21 -04:00
|
|
|
log::error!(
|
|
|
|
"Unrecognized shell message type: {}",
|
|
|
|
msg.content.message_type()
|
|
|
|
);
|
2023-09-15 20:42:09 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-30 22:30:40 -04:00
|
|
|
self
|
2024-05-21 16:35:21 -04:00
|
|
|
.send_iopub(messaging::Status::idle().as_child_of(parent))
|
2023-09-15 20:42:09 -04:00
|
|
|
.await?;
|
2024-05-21 16:35:21 -04:00
|
|
|
|
2023-09-15 20:42:09 -04:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn handle_execution_request(
|
|
|
|
&mut self,
|
2024-05-21 16:35:21 -04:00
|
|
|
execute_request: messaging::ExecuteRequest,
|
|
|
|
parent_message: &JupyterMessage,
|
|
|
|
connection: &mut KernelShellConnection,
|
2023-09-15 20:42:09 -04:00
|
|
|
) -> Result<(), AnyError> {
|
2024-05-21 16:35:21 -04:00
|
|
|
if !execute_request.silent && execute_request.store_history {
|
2024-07-27 04:39:08 -04:00
|
|
|
self.execution_count.increment();
|
2024-03-26 14:48:23 -04:00
|
|
|
}
|
2024-07-04 18:12:14 -04:00
|
|
|
*self.last_execution_request.lock() = Some(parent_message.clone());
|
2023-09-15 20:42:09 -04:00
|
|
|
|
2024-04-30 22:30:40 -04:00
|
|
|
self
|
2024-05-21 16:35:21 -04:00
|
|
|
.send_iopub(
|
|
|
|
messaging::ExecuteInput {
|
|
|
|
execution_count: self.execution_count,
|
|
|
|
code: execute_request.code.clone(),
|
|
|
|
}
|
|
|
|
.as_child_of(parent_message),
|
|
|
|
)
|
2023-09-15 20:42:09 -04:00
|
|
|
.await?;
|
|
|
|
|
|
|
|
let result = self
|
2024-07-02 18:37:54 -04:00
|
|
|
.repl_session_proxy
|
|
|
|
.evaluate_line_with_object_wrapping(execute_request.code)
|
2023-09-15 20:42:09 -04:00
|
|
|
.await;
|
|
|
|
|
|
|
|
let evaluate_response = match result {
|
|
|
|
Ok(eval_response) => eval_response,
|
|
|
|
Err(err) => {
|
2024-04-30 22:30:40 -04:00
|
|
|
self
|
2024-05-21 16:35:21 -04:00
|
|
|
.send_iopub(
|
|
|
|
messaging::ErrorOutput {
|
|
|
|
ename: err.to_string(),
|
|
|
|
evalue: err.to_string(),
|
|
|
|
traceback: vec![],
|
|
|
|
}
|
|
|
|
.as_child_of(parent_message),
|
|
|
|
)
|
2023-09-15 20:42:09 -04:00
|
|
|
.await?;
|
2024-04-30 22:30:40 -04:00
|
|
|
connection
|
2024-05-21 16:35:21 -04:00
|
|
|
.send(
|
|
|
|
messaging::ExecuteReply {
|
|
|
|
execution_count: self.execution_count,
|
|
|
|
status: ReplyStatus::Error,
|
2024-05-29 18:46:47 -04:00
|
|
|
payload: Default::default(),
|
2024-05-21 16:35:21 -04:00
|
|
|
user_expressions: None,
|
|
|
|
error: None,
|
|
|
|
}
|
|
|
|
.as_child_of(parent_message),
|
|
|
|
)
|
2023-09-15 20:42:09 -04:00
|
|
|
.await?;
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-11-05 17:58:59 -05:00
|
|
|
let cdp::EvaluateResponse {
|
2023-09-15 20:42:09 -04:00
|
|
|
result,
|
|
|
|
exception_details,
|
|
|
|
} = evaluate_response.value;
|
|
|
|
|
|
|
|
if exception_details.is_none() {
|
2024-07-02 18:37:54 -04:00
|
|
|
publish_result(
|
|
|
|
&mut self.repl_session_proxy,
|
|
|
|
&result,
|
|
|
|
self.execution_count,
|
|
|
|
)
|
|
|
|
.await?;
|
2023-10-12 18:32:38 -04:00
|
|
|
|
2024-04-30 22:30:40 -04:00
|
|
|
connection
|
2024-05-21 16:35:21 -04:00
|
|
|
.send(
|
|
|
|
messaging::ExecuteReply {
|
|
|
|
execution_count: self.execution_count,
|
|
|
|
status: ReplyStatus::Ok,
|
|
|
|
user_expressions: None,
|
2024-05-29 18:46:47 -04:00
|
|
|
payload: Default::default(),
|
2024-05-21 16:35:21 -04:00
|
|
|
error: None,
|
|
|
|
}
|
|
|
|
.as_child_of(parent_message),
|
|
|
|
)
|
2023-09-15 20:42:09 -04:00
|
|
|
.await?;
|
|
|
|
// Let's sleep here for a few ms, so we give a chance to the task that is
|
|
|
|
// handling stdout and stderr streams to receive and flush the content.
|
|
|
|
// Otherwise, executing multiple cells one-by-one might lead to output
|
|
|
|
// from various cells be grouped together in another cell result.
|
|
|
|
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
|
2023-10-05 14:49:09 -04:00
|
|
|
} else if let Some(exception_details) = exception_details {
|
2023-09-18 18:07:33 -04:00
|
|
|
// Determine the exception value and name
|
2024-05-08 22:45:06 -04:00
|
|
|
let (name, message, stack) = if let Some(exception) =
|
|
|
|
exception_details.exception
|
|
|
|
{
|
|
|
|
let result = self
|
2024-07-02 18:37:54 -04:00
|
|
|
.repl_session_proxy
|
2024-05-08 22:45:06 -04:00
|
|
|
.call_function_on_args(
|
|
|
|
r#"
|
2023-09-18 18:07:33 -04:00
|
|
|
function(object) {
|
|
|
|
if (object instanceof Error) {
|
|
|
|
const name = "name" in object ? String(object.name) : "";
|
|
|
|
const message = "message" in object ? String(object.message) : "";
|
|
|
|
const stack = "stack" in object ? String(object.stack) : "";
|
|
|
|
return JSON.stringify({ name, message, stack });
|
|
|
|
} else {
|
|
|
|
const message = String(object);
|
|
|
|
return JSON.stringify({ name: "", message, stack: "" });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"#
|
2024-05-08 22:45:06 -04:00
|
|
|
.into(),
|
2024-07-02 18:37:54 -04:00
|
|
|
vec![exception],
|
2024-05-08 22:45:06 -04:00
|
|
|
)
|
|
|
|
.await?;
|
2023-09-18 18:07:33 -04:00
|
|
|
|
2024-05-08 22:45:06 -04:00
|
|
|
match result.result.value {
|
|
|
|
Some(serde_json::Value::String(str)) => {
|
|
|
|
if let Ok(object) =
|
|
|
|
serde_json::from_str::<HashMap<String, String>>(&str)
|
|
|
|
{
|
|
|
|
let get = |k| object.get(k).cloned().unwrap_or_default();
|
|
|
|
(get("name"), get("message"), get("stack"))
|
|
|
|
} else {
|
|
|
|
log::error!("Unexpected result while parsing JSON {str}");
|
2023-09-18 18:07:33 -04:00
|
|
|
("".into(), "".into(), "".into())
|
|
|
|
}
|
|
|
|
}
|
2024-05-08 22:45:06 -04:00
|
|
|
_ => {
|
|
|
|
log::error!("Unexpected result while parsing exception {result:?}");
|
|
|
|
("".into(), "".into(), "".into())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
log::error!("Unexpectedly missing exception {exception_details:?}");
|
|
|
|
("".into(), "".into(), "".into())
|
|
|
|
};
|
2023-09-18 18:07:33 -04:00
|
|
|
|
|
|
|
let stack = if stack.is_empty() {
|
|
|
|
format!(
|
|
|
|
"{}\n at <unknown>",
|
|
|
|
serde_json::to_string(&message).unwrap()
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
stack
|
|
|
|
};
|
|
|
|
let traceback = format!("Stack trace:\n{stack}")
|
|
|
|
.split('\n')
|
|
|
|
.map(|s| s.to_owned())
|
|
|
|
.collect::<Vec<_>>();
|
|
|
|
|
|
|
|
let ename = if name.is_empty() {
|
|
|
|
"Unknown error".into()
|
|
|
|
} else {
|
|
|
|
name
|
|
|
|
};
|
|
|
|
|
|
|
|
let evalue = if message.is_empty() {
|
|
|
|
"(none)".into()
|
2023-09-15 20:42:09 -04:00
|
|
|
} else {
|
2023-09-18 18:07:33 -04:00
|
|
|
message
|
2023-09-15 20:42:09 -04:00
|
|
|
};
|
|
|
|
|
2024-04-30 22:30:40 -04:00
|
|
|
self
|
2024-05-21 16:35:21 -04:00
|
|
|
.send_iopub(
|
|
|
|
messaging::ErrorOutput {
|
|
|
|
ename: ename.clone(),
|
|
|
|
evalue: evalue.clone(),
|
|
|
|
traceback: traceback.clone(),
|
|
|
|
}
|
|
|
|
.as_child_of(parent_message),
|
|
|
|
)
|
2023-09-15 20:42:09 -04:00
|
|
|
.await?;
|
2024-04-30 22:30:40 -04:00
|
|
|
connection
|
2024-05-21 16:35:21 -04:00
|
|
|
.send(
|
|
|
|
messaging::ExecuteReply {
|
|
|
|
execution_count: self.execution_count,
|
|
|
|
status: ReplyStatus::Error,
|
2024-07-27 04:39:08 -04:00
|
|
|
error: Some(Box::new(ReplyError {
|
2024-05-21 16:35:21 -04:00
|
|
|
ename,
|
|
|
|
evalue,
|
|
|
|
traceback,
|
2024-07-27 04:39:08 -04:00
|
|
|
})),
|
2024-05-21 16:35:21 -04:00
|
|
|
user_expressions: None,
|
2024-05-29 18:46:47 -04:00
|
|
|
payload: Default::default(),
|
2024-05-21 16:35:21 -04:00
|
|
|
}
|
|
|
|
.as_child_of(parent_message),
|
|
|
|
)
|
2023-09-15 20:42:09 -04:00
|
|
|
.await?;
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
2024-04-30 22:30:40 -04:00
|
|
|
|
|
|
|
async fn send_iopub(
|
|
|
|
&mut self,
|
2024-05-21 16:35:21 -04:00
|
|
|
message: JupyterMessage,
|
2024-04-30 22:30:40 -04:00
|
|
|
) -> Result<(), AnyError> {
|
2024-07-27 04:39:08 -04:00
|
|
|
self.iopub_connection.lock().send(message.clone()).await
|
2024-04-30 22:30:40 -04:00
|
|
|
}
|
2023-09-15 20:42:09 -04:00
|
|
|
}
|
|
|
|
|
2024-05-21 16:35:21 -04:00
|
|
|
fn kernel_info() -> messaging::KernelInfoReply {
|
|
|
|
messaging::KernelInfoReply {
|
|
|
|
status: ReplyStatus::Ok,
|
|
|
|
protocol_version: "5.3".to_string(),
|
|
|
|
implementation: "Deno kernel".to_string(),
|
2024-08-15 17:47:16 -04:00
|
|
|
implementation_version: crate::version::DENO_VERSION_INFO.deno.to_string(),
|
2024-05-21 16:35:21 -04:00
|
|
|
language_info: messaging::LanguageInfo {
|
|
|
|
name: "typescript".to_string(),
|
2024-08-15 17:47:16 -04:00
|
|
|
version: crate::version::DENO_VERSION_INFO.typescript.to_string(),
|
2024-05-21 16:35:21 -04:00
|
|
|
mimetype: "text/x.typescript".to_string(),
|
|
|
|
file_extension: ".ts".to_string(),
|
|
|
|
pygments_lexer: "typescript".to_string(),
|
|
|
|
codemirror_mode: messaging::CodeMirrorMode::typescript(),
|
|
|
|
nbconvert_exporter: "script".to_string(),
|
2023-09-15 20:42:09 -04:00
|
|
|
},
|
2024-05-21 16:35:21 -04:00
|
|
|
banner: "Welcome to Deno kernel".to_string(),
|
|
|
|
help_links: vec![messaging::HelpLink {
|
|
|
|
text: "Visit Deno manual".to_string(),
|
2024-08-18 18:39:53 -04:00
|
|
|
url: "https://docs.deno.com".to_string(),
|
2023-09-15 20:42:09 -04:00
|
|
|
}],
|
2024-05-21 16:35:21 -04:00
|
|
|
debugger: false,
|
|
|
|
error: None,
|
|
|
|
}
|
2023-09-15 20:42:09 -04:00
|
|
|
}
|
|
|
|
|
2023-10-12 18:32:38 -04:00
|
|
|
async fn publish_result(
|
2024-07-02 18:37:54 -04:00
|
|
|
repl_session_proxy: &mut JupyterReplProxy,
|
2023-09-15 20:42:09 -04:00
|
|
|
evaluate_result: &cdp::RemoteObject,
|
2024-07-27 04:39:08 -04:00
|
|
|
execution_count: ExecutionCount,
|
2023-09-15 20:42:09 -04:00
|
|
|
) -> Result<Option<HashMap<String, serde_json::Value>>, AnyError> {
|
2023-10-12 18:32:38 -04:00
|
|
|
let arg0 = cdp::CallArgument {
|
2024-07-27 04:39:08 -04:00
|
|
|
value: Some(execution_count.into()),
|
2023-10-12 18:32:38 -04:00
|
|
|
unserializable_value: None,
|
|
|
|
object_id: None,
|
|
|
|
};
|
|
|
|
|
|
|
|
let arg1 = cdp::CallArgument::from(evaluate_result);
|
|
|
|
|
2024-07-02 18:37:54 -04:00
|
|
|
let Some(response) = repl_session_proxy.call_function_on(arg0, arg1).await
|
|
|
|
else {
|
|
|
|
return Ok(None);
|
|
|
|
};
|
2023-09-15 20:42:09 -04:00
|
|
|
|
2023-09-17 12:38:52 -04:00
|
|
|
if let Some(exception_details) = &response.exception_details {
|
2023-09-18 12:31:20 -04:00
|
|
|
// If the object doesn't have a Jupyter.display method or it throws an
|
|
|
|
// exception, we just ignore it and let the caller handle it.
|
2024-05-08 22:45:06 -04:00
|
|
|
log::error!("Exception encountered: {}", exception_details.text);
|
2023-09-15 20:42:09 -04:00
|
|
|
return Ok(None);
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(bartlomieju): dedup with repl::editor
|
|
|
|
fn get_expr_from_line_at_pos(line: &str, cursor_pos: usize) -> &str {
|
|
|
|
let start = line[..cursor_pos].rfind(is_word_boundary).unwrap_or(0);
|
|
|
|
let end = line[cursor_pos..]
|
|
|
|
.rfind(is_word_boundary)
|
|
|
|
.map(|i| cursor_pos + i)
|
|
|
|
.unwrap_or(cursor_pos);
|
|
|
|
|
|
|
|
let word = &line[start..end];
|
|
|
|
let word = word.strip_prefix(is_word_boundary).unwrap_or(word);
|
|
|
|
let word = word.strip_suffix(is_word_boundary).unwrap_or(word);
|
|
|
|
|
|
|
|
word
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(bartlomieju): dedup with repl::editor
|
|
|
|
fn is_word_boundary(c: char) -> bool {
|
|
|
|
if matches!(c, '.' | '_' | '$') {
|
|
|
|
false
|
|
|
|
} else {
|
|
|
|
char::is_ascii_whitespace(&c) || char::is_ascii_punctuation(&c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(bartlomieju): dedup with repl::editor
|
|
|
|
async fn get_global_lexical_scope_names(
|
2024-07-02 18:37:54 -04:00
|
|
|
repl_session_proxy: &mut JupyterReplProxy,
|
2023-09-15 20:42:09 -04:00
|
|
|
) -> Vec<String> {
|
2024-07-02 18:37:54 -04:00
|
|
|
repl_session_proxy.global_lexical_scope_names().await.names
|
2023-09-15 20:42:09 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(bartlomieju): dedup with repl::editor
|
|
|
|
async fn get_expression_property_names(
|
2024-07-02 18:37:54 -04:00
|
|
|
repl_session_proxy: &mut JupyterReplProxy,
|
2023-09-15 20:42:09 -04:00
|
|
|
expr: &str,
|
|
|
|
) -> Vec<String> {
|
|
|
|
// try to get the properties from the expression
|
2024-07-02 18:37:54 -04:00
|
|
|
if let Some(properties) =
|
|
|
|
get_object_expr_properties(repl_session_proxy, expr).await
|
|
|
|
{
|
2023-09-15 20:42:09 -04:00
|
|
|
return properties;
|
|
|
|
}
|
|
|
|
|
|
|
|
// otherwise fall back to the prototype
|
2024-07-02 18:37:54 -04:00
|
|
|
let expr_type = get_expression_type(repl_session_proxy, expr).await;
|
2023-09-15 20:42:09 -04:00
|
|
|
let object_expr = match expr_type.as_deref() {
|
|
|
|
// possibilities: https://chromedevtools.github.io/devtools-protocol/v8/Runtime/#type-RemoteObject
|
|
|
|
Some("object") => "Object.prototype",
|
|
|
|
Some("function") => "Function.prototype",
|
|
|
|
Some("string") => "String.prototype",
|
|
|
|
Some("boolean") => "Boolean.prototype",
|
|
|
|
Some("bigint") => "BigInt.prototype",
|
|
|
|
Some("number") => "Number.prototype",
|
|
|
|
_ => return Vec::new(), // undefined, symbol, and unhandled
|
|
|
|
};
|
|
|
|
|
2024-07-02 18:37:54 -04:00
|
|
|
get_object_expr_properties(repl_session_proxy, object_expr)
|
2023-09-15 20:42:09 -04:00
|
|
|
.await
|
|
|
|
.unwrap_or_default()
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(bartlomieju): dedup with repl::editor
|
|
|
|
async fn get_expression_type(
|
2024-07-02 18:37:54 -04:00
|
|
|
repl_session_proxy: &mut JupyterReplProxy,
|
2023-09-15 20:42:09 -04:00
|
|
|
expr: &str,
|
|
|
|
) -> Option<String> {
|
2024-07-02 18:37:54 -04:00
|
|
|
evaluate_expression(repl_session_proxy, expr)
|
2023-09-15 20:42:09 -04:00
|
|
|
.await
|
|
|
|
.map(|res| res.result.kind)
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(bartlomieju): dedup with repl::editor
|
|
|
|
async fn get_object_expr_properties(
|
2024-07-02 18:37:54 -04:00
|
|
|
repl_session_proxy: &mut JupyterReplProxy,
|
2023-09-15 20:42:09 -04:00
|
|
|
object_expr: &str,
|
|
|
|
) -> Option<Vec<String>> {
|
2024-07-02 18:37:54 -04:00
|
|
|
let evaluate_result =
|
|
|
|
evaluate_expression(repl_session_proxy, object_expr).await?;
|
2023-09-15 20:42:09 -04:00
|
|
|
let object_id = evaluate_result.result.object_id?;
|
|
|
|
|
2024-07-02 18:37:54 -04:00
|
|
|
let get_properties_response =
|
|
|
|
repl_session_proxy.get_properties(object_id.clone()).await?;
|
2023-09-15 20:42:09 -04:00
|
|
|
Some(
|
|
|
|
get_properties_response
|
|
|
|
.result
|
|
|
|
.into_iter()
|
|
|
|
.map(|prop| prop.name)
|
|
|
|
.collect(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(bartlomieju): dedup with repl::editor
|
|
|
|
async fn evaluate_expression(
|
2024-07-02 18:37:54 -04:00
|
|
|
repl_session_proxy: &mut JupyterReplProxy,
|
2023-09-15 20:42:09 -04:00
|
|
|
expr: &str,
|
|
|
|
) -> Option<cdp::EvaluateResponse> {
|
2024-07-02 18:37:54 -04:00
|
|
|
let evaluate_response = repl_session_proxy.evaluate(expr.to_string()).await?;
|
2023-09-15 20:42:09 -04:00
|
|
|
if evaluate_response.exception_details.is_some() {
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
Some(evaluate_response)
|
|
|
|
}
|
|
|
|
}
|