diff --git a/Cargo.lock b/Cargo.lock index 9aad5d9fed..e886504cb3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4548,6 +4548,8 @@ dependencies = [ name = "ide-http" version = "0.1.55" dependencies = [ + "base64 0.22.1", + "http", "hyper-util", "ide-core", "ide-vfs", @@ -4746,18 +4748,22 @@ dependencies = [ name = "ide-notebook" version = "0.1.55" dependencies = [ + "futures", "ide-core", + "ide-http", "ide-vfs", "jupyter-protocol", "jupyter-zmq-client", "libc", "parking_lot 0.12.5", + "reqwest", "serde", "serde_json", "specta", "specta-typescript", "tempfile", "tokio", + "tokio-tungstenite", "uuid", "windows-sys 0.61.2", "zeromq", diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index aae2d9c8e8..994d90e2e0 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -139,6 +139,8 @@ pub struct Host { pub web: ide_web::WebServer, /// The HTTP proxy's saved password (see `proxy.rs`). proxy_password: ide_ssh::secrets::SecretFile, + /// Tokens of the Jupyter servers notebooks run on, by server base URL. + jupyter_tokens: ide_ssh::secrets::SecretFile, /// The proxy password when it could not be saved (no credential store). proxy_session_password: Mutex>, /// Values of agents' and MCP servers' environment variables and headers (see `agent_secrets.rs`). @@ -235,6 +237,7 @@ impl Host { trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)), mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)), proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")), + jupyter_tokens: ide_ssh::secrets::SecretFile::new(data_dir.join("jupyter-tokens.json")), proxy_session_password: Mutex::default(), agent_secrets: Arc::new(agent_secrets::AgentSecrets::new(&data_dir)), remote: Arc::new(ide_remote::RemoteService::new(ssh.clone(), data_dir.join("remote"))), diff --git a/crates/ide-host/src/notebook.rs b/crates/ide-host/src/notebook.rs index 0698a75890..c9afcf137f 100644 --- a/crates/ide-host/src/notebook.rs +++ b/crates/ide-host/src/notebook.rs @@ -3,7 +3,7 @@ use crate::ops::Channel; use base64::Engine; use ide_core::error::ErrorKind; use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, IpcPath, SharedSink}; -use ide_notebook::kernel::{KernelManager, KernelOutput}; +use ide_notebook::kernel::{KernelManager, KernelOutput, KernelTarget}; use ide_notebook::{NotebookDocument, NotebookEdit, NotebookSnapshot}; use parking_lot::Mutex; use serde::{Deserialize, Serialize}; @@ -375,7 +375,7 @@ impl NotebookService { pub(crate) async fn execute( self: &Arc, admission: ExecutionAdmission, - python: PathBuf, + target: KernelTarget, on_output: Channel, ) -> IdeResult { let document = admission.guard.document.clone(); @@ -384,7 +384,7 @@ impl NotebookService { tokio::spawn(async move { let ExecutionAdmission { guard, generation, plan } = admission; let result = - service.run_batch(document.clone(), generation, plan, python, guard.batch.clone(), on_output).await; + service.run_batch(document.clone(), generation, plan, target, guard.batch.clone(), on_output).await; drop(guard); match result { Ok(()) => snapshot(&document), @@ -400,7 +400,7 @@ impl NotebookService { document: Arc, generation: u64, plan: Vec<(String, String)>, - python: PathBuf, + target: KernelTarget, batch: Arc, on_output: Channel, ) -> IdeResult<()> { @@ -428,7 +428,7 @@ impl NotebookService { .kernels .execute( &document.path, - &python, + target.clone(), &source, batch.cancel.clone(), Arc::new(move |output: KernelOutput| { diff --git a/crates/ide-host/src/ops/notebook.rs b/crates/ide-host/src/ops/notebook.rs index a7b7e76edc..85d260c2b4 100644 --- a/crates/ide-host/src/ops/notebook.rs +++ b/crates/ide-host/src/ops/notebook.rs @@ -4,6 +4,7 @@ pub use crate::notebook::NotebookOutputEvent; use crate::ops::Channel; use ide_command::command; use ide_core::{IdeError, IdeResult, RequestId}; +use ide_notebook::kernel::{KernelSpec, KernelTarget, RemoteKernel, kernel_specs, normalize_server_url}; use ide_notebook::{NotebookEdit, NotebookSnapshot}; use std::path::PathBuf; @@ -124,6 +125,10 @@ pub async fn notebook_execute( let admission = project.notebooks.admit(&id, cells, cancel.clone())?; let selected = match python { Some(path) if path.trim().is_empty() => return Err(IdeError::invalid("select a Python interpreter")), + Some(kernel) if kernel.starts_with("http://") || kernel.starts_with("https://") => { + let target = KernelTarget::Remote(remote_kernel(host, &kernel)?); + return project.notebooks.execute(admission, target, on_output).await; + } Some(path) => PathBuf::from(path), None => { let root = project.root.clone(); @@ -143,7 +148,60 @@ pub async fn notebook_execute( // Do not canonicalize this path: resolving a venv symlink to base Python // changes sys.prefix and executes in the wrong environment. let python = if selected.is_absolute() { selected } else { project.root.join(selected) }; - project.notebooks.execute(admission, python, on_output).await + project.notebooks.execute(admission, KernelTarget::Local(python), on_output).await +} + +/// A kernel choice on a Jupyter server, `#`, with its saved token. +fn remote_kernel(host: &Host, choice: &str) -> IdeResult { + let (base, spec) = choice + .split_once('#') + .filter(|(_, spec)| !spec.is_empty()) + .ok_or_else(|| IdeError::invalid("select a kernel of the Jupyter server"))?; + let token = host.jupyter_tokens.get(base).ok_or_else(|| { + IdeError::unavailable(format!("connect to the Jupyter server {base} again: its token is not saved")) + })?; + Ok(RemoteKernel { base: base.to_owned(), token, spec: spec.to_owned() }) +} + +/// A Jupyter server notebooks can run on. +#[derive(serde::Serialize, specta::Type)] +pub struct JupyterServer { + /// Base URL, ending in `/`. + pub url: String, + pub kernels: Vec, +} + +/// Checks `url` and `token` against the server and saves them. A `?token=` in the URL +/// (as JupyterLab prints it) is used when `token` is empty. +#[command(trust = trusted)] +pub async fn jupyter_server_add(host: &Host, window: &str, url: String, token: String) -> IdeResult { + host.require_trust(window)?; + let (url, in_url) = normalize_server_url(&url)?; + let token = if token.trim().is_empty() { in_url.unwrap_or_default() } else { token.trim().to_owned() }; + let kernels = kernel_specs(&url, &token).await?; + host.jupyter_tokens.set(&url, &token)?; + Ok(JupyterServer { url, kernels }) +} + +/// The saved servers and their kernel specs; a server that cannot be reached has none. +#[command(trust = trusted)] +pub async fn jupyter_servers(host: &Host, window: &str) -> IdeResult> { + host.require_trust(window)?; + let servers = host.jupyter_tokens.keys().into_iter().map(|url| async move { + let kernels = match host.jupyter_tokens.get(&url) { + Some(token) => kernel_specs(&url, &token).await.unwrap_or_default(), + None => Vec::new(), + }; + JupyterServer { url, kernels } + }); + Ok(futures::future::join_all(servers).await) +} + +#[command(trust = always)] +pub fn jupyter_server_remove(host: &Host, window: &str, url: String) -> IdeResult<()> { + let _ = window; + host.jupyter_tokens.delete(&url); + Ok(()) } struct RequestGuard<'a> { @@ -162,6 +220,9 @@ impl Drop for RequestGuard<'_> { ide_command::domain!( notebook: + jupyter_server_add, + jupyter_server_remove, + jupyter_servers, notebook_cell_docs, notebook_close, notebook_edit, diff --git a/crates/ide-http/Cargo.toml b/crates/ide-http/Cargo.toml index 2c8accf851..ef01c6bdf0 100644 --- a/crates/ide-http/Cargo.toml +++ b/crates/ide-http/Cargo.toml @@ -11,8 +11,11 @@ ide-vfs.workspace = true serde.workspace = true serde_json = { workspace = true, features = ["raw_value"] } specta.workspace = true -tokio.workspace = true +# `net`: tunnel.rs opens connections reqwest does not (a WebSocket). +tokio = { workspace = true, features = ["net"] } parking_lot.workspace = true +base64.workspace = true +http = "1" reqwest.workspace = true # The system proxy reqwest reads, to notice when it changes (see `client::shared`). hyper-util = { version = "0.1", default-features = false, features = ["client-proxy", "client-proxy-system"] } diff --git a/crates/ide-http/src/lib.rs b/crates/ide-http/src/lib.rs index 2ccfb7385f..2e9d41401b 100644 --- a/crates/ide-http/src/lib.rs +++ b/crates/ide-http/src/lib.rs @@ -11,6 +11,7 @@ pub mod env; pub mod exec; pub mod history; pub mod parse; +pub mod tunnel; pub use env::Environments; pub use exec::{HttpResponse, PreparedRequest}; diff --git a/crates/ide-http/src/tunnel.rs b/crates/ide-http/src/tunnel.rs new file mode 100644 index 0000000000..b6ba7017fd --- /dev/null +++ b/crates/ide-http/src/tunnel.rs @@ -0,0 +1,165 @@ +//! A TCP connection routed like the HTTP client's requests, for protocols reqwest does not +//! speak (a WebSocket): direct, or through an HTTP proxy's `CONNECT` tunnel. + +use base64::Engine; +use ide_core::proxy_settings::ProxyRoute; +use ide_core::{IdeError, IdeResult}; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; + +const CONNECT_TIMEOUT: Duration = Duration::from_secs(30); + +/// A connection to `url`'s host and port, through the proxy System Settings › HTTP Proxy +/// (or, in Auto mode, the system) routes that host to. +pub async fn connect(url: &reqwest::Url) -> IdeResult { + let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?; + let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?; + let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") }; + let proxy = match ide_core::proxy_settings::proxy().route(Some(host)) { + ProxyRoute::Direct => None, + ProxyRoute::Via(via) => Some(via), + ProxyRoute::System => { + // The system proxy of the scheme reqwest would use (`ws` → `http`). + let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" }; + let uri: http::Uri = + format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))?; + hyper_util::client::proxy::matcher::Matcher::from_system().intercept(&uri).map(|intercept| { + let auth = + intercept.raw_auth().map(|(user, password)| format!("{user}:{password}@")).unwrap_or_default(); + let uri = intercept.uri(); + format!( + "{}://{auth}{}", + uri.scheme_str().unwrap_or("http"), + uri.authority().map(|a| a.as_str()).unwrap_or_default() + ) + }) + } + }; + let connecting = async { + let Some(proxy) = proxy else { + return TcpStream::connect(&target).await.map_err(|error| reach(&target, &error)); + }; + let proxy = reqwest::Url::parse(&proxy).map_err(|_| IdeError::invalid("invalid proxy URL"))?; + if proxy.scheme() != "http" { + return Err(IdeError::unavailable(format!( + "a {} proxy cannot carry this connection; set an HTTP proxy", + proxy.scheme() + ))); + } + let address = + format!("{}:{}", proxy.host_str().unwrap_or_default(), proxy.port_or_known_default().unwrap_or(80)); + let stream = TcpStream::connect(&address).await.map_err(|error| reach(&address, &error))?; + let auth = (!proxy.username().is_empty()).then(|| { + let user = percent_decode(proxy.username()); + let password = percent_decode(proxy.password().unwrap_or_default()); + base64::engine::general_purpose::STANDARD.encode(format!("{user}:{password}")) + }); + tunnel(stream, &target, auth.as_deref()).await + }; + tokio::time::timeout(CONNECT_TIMEOUT, connecting) + .await + .map_err(|_| IdeError::unavailable(format!("connecting to {target} timed out")))? +} + +fn reach(address: &str, error: &std::io::Error) -> IdeError { + IdeError::unavailable(format!("could not connect to {address}: {error}")) +} + +fn percent_decode(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' + && let Some(byte) = text.get(i + 1..i + 3).and_then(|hex| u8::from_str_radix(hex, 16).ok()) + { + out.push(byte); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8_lossy(&out).into_owned() +} + +/// Asks the proxy on `stream` for a tunnel to `target` (`host:port`). +async fn tunnel(mut stream: TcpStream, target: &str, auth: Option<&str>) -> IdeResult { + let auth = auth.map(|auth| format!("Proxy-Authorization: Basic {auth}\r\n")).unwrap_or_default(); + let request = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n{auth}\r\n"); + let failed = |error: std::io::Error| IdeError::unavailable(format!("proxy: {error}")); + stream.write_all(request.as_bytes()).await.map_err(failed)?; + // The reply's head only: nothing follows it until this side speaks. + let mut head = Vec::new(); + let mut byte = [0u8; 1]; + while !head.ends_with(b"\r\n\r\n") { + if head.len() > 8192 || stream.read(&mut byte).await.map_err(failed)? == 0 { + return Err(IdeError::unavailable("the proxy closed the connection")); + } + head.push(byte[0]); + } + let status = String::from_utf8_lossy(&head); + let status = status.lines().next().unwrap_or_default(); + match status.split_whitespace().nth(1) { + Some("200") => Ok(stream), + Some("407") => Err(IdeError::unavailable("the proxy needs a login (HTTP Proxy settings)")), + _ => Err(IdeError::unavailable(format!("the proxy refused the connection: {status}"))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tokio::net::TcpListener; + + /// A proxy that answers `reply` to one CONNECT and then echoes; returns what it was asked. + async fn proxy(reply: &'static str) -> (String, tokio::task::JoinHandle) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap().to_string(); + let task = tokio::spawn(async move { + let (mut client, _) = listener.accept().await.unwrap(); + let mut head = Vec::new(); + let mut byte = [0u8; 1]; + while !head.ends_with(b"\r\n\r\n") { + client.read_exact(&mut byte).await.unwrap(); + head.push(byte[0]); + } + client.write_all(reply.as_bytes()).await.unwrap(); + let mut echo = [0u8; 5]; + if client.read_exact(&mut echo).await.is_ok() { + client.write_all(&echo).await.unwrap(); + } + String::from_utf8(head).unwrap() + }); + (address, task) + } + + #[tokio::test] + async fn a_tunnel_carries_bytes_after_the_proxy_agrees() { + let (address, asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await; + let stream = TcpStream::connect(&address).await.unwrap(); + let mut stream = tunnel(stream, "hub.example.com:443", Some("dTpw")).await.unwrap(); + stream.write_all(b"hello").await.unwrap(); + let mut back = [0u8; 5]; + stream.read_exact(&mut back).await.unwrap(); + assert_eq!(&back, b"hello"); + let asked = asked.await.unwrap(); + assert!(asked.starts_with("CONNECT hub.example.com:443 HTTP/1.1\r\n")); + assert!(asked.contains("Proxy-Authorization: Basic dTpw\r\n")); + } + + #[tokio::test] + async fn a_refused_tunnel_says_why() { + let (address, _) = proxy("HTTP/1.1 407 Proxy Authentication Required\r\n\r\n").await; + let stream = TcpStream::connect(&address).await.unwrap(); + let error = tunnel(stream, "hub.example.com:443", None).await.unwrap_err(); + assert!(error.message.contains("needs a login"), "{}", error.message); + } + + #[test] + fn proxy_credentials_are_percent_decoded() { + assert_eq!(percent_decode("a%40b%3Ac"), "a@b:c"); + assert_eq!(percent_decode("100%"), "100%"); + } +} diff --git a/crates/ide-notebook/Cargo.toml b/crates/ide-notebook/Cargo.toml index 66cb358188..5e4877aac7 100644 --- a/crates/ide-notebook/Cargo.toml +++ b/crates/ide-notebook/Cargo.toml @@ -19,6 +19,10 @@ jupyter-zmq-client.workspace = true jupyter-protocol.workspace = true zeromq.workspace = true tempfile.workspace = true +ide-http.workspace = true +reqwest.workspace = true +tokio-tungstenite.workspace = true +futures.workspace = true [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/crates/ide-notebook/src/kernel.rs b/crates/ide-notebook/src/kernel.rs index dd58d20405..cb29eef41f 100644 --- a/crates/ide-notebook/src/kernel.rs +++ b/crates/ide-notebook/src/kernel.rs @@ -22,6 +22,45 @@ use tokio::sync::Mutex as AsyncMutex; /// not drain; an Interrupt then stops it like a run. const READ_LIMIT: Duration = Duration::from_secs(5); +pub use transport::remote::{KernelSpec, kernel_specs, normalize_server_url}; + +/// Where a notebook's kernel runs. +#[derive(Clone, PartialEq, Eq)] +pub enum KernelTarget { + /// A kernel the IDE starts from this Python interpreter. + Local(PathBuf), + /// A kernel started on a Jupyter server. + Remote(RemoteKernel), +} + +/// A kernel spec on a Jupyter server, and the token to reach it. +#[derive(Clone, PartialEq, Eq)] +pub struct RemoteKernel { + /// The server's base URL, ending in `/` (see [`normalize_server_url`]). + pub base: String, + pub token: String, + pub spec: String, +} + +impl std::fmt::Debug for RemoteKernel { + // Leaves out the token. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RemoteKernel").field("base", &self.base).field("spec", &self.spec).finish() + } +} + +impl From<&Path> for KernelTarget { + fn from(python: &Path) -> Self { + Self::Local(python.to_path_buf()) + } +} + +impl From<&PathBuf> for KernelTarget { + fn from(python: &PathBuf) -> Self { + Self::Local(python.clone()) + } +} + pub(super) type StatusCallback = Arc) + Send + Sync>; pub(super) type OutputCallback = Arc; @@ -141,11 +180,12 @@ impl KernelManager { pub async fn execute( &self, notebook: &Path, - python: &Path, + target: impl Into, code: &str, cancel: CancellationToken, on_output: OutputCallback, ) -> IdeResult { + let target = target.into(); if cancel.is_cancelled() { return Err(IdeError::cancelled()); } @@ -176,7 +216,7 @@ impl KernelManager { if slot.closed.load(Ordering::Acquire) { return Err(IdeError::unavailable("notebook kernel was closed")); } - if running.as_ref().is_some_and(|r| r.python != python || r.is_finished()) + if running.as_ref().is_some_and(|r| r.target != target || r.is_finished()) && let Some(old) = running.take() { old.shutdown().await; @@ -188,7 +228,7 @@ impl KernelManager { let (new, ready) = transport::Running::spawn( self.runtime_dir.clone(), notebook.to_path_buf(), - python.to_path_buf(), + target, self.on_status.clone(), ); *slot.stop.lock() = Some(new.stop.clone()); @@ -284,10 +324,10 @@ impl KernelManager { return Err(IdeError::unavailable("notebook kernel was closed")); } let Some(old) = running.take() else { return Ok(()) }; - let python = old.python.clone(); + let target = old.target.clone(); old.shutdown().await; let (new, ready) = - transport::Running::spawn(self.runtime_dir.clone(), notebook.to_path_buf(), python, self.on_status.clone()); + transport::Running::spawn(self.runtime_dir.clone(), notebook.to_path_buf(), target, self.on_status.clone()); *slot.stop.lock() = Some(new.stop.clone()); *running = Some(new); if slot.closed.load(Ordering::Acquire) { diff --git a/crates/ide-notebook/src/kernel/transport.rs b/crates/ide-notebook/src/kernel/transport.rs index 18250d0da6..7a07f37655 100644 --- a/crates/ide-notebook/src/kernel/transport.rs +++ b/crates/ide-notebook/src/kernel/transport.rs @@ -1,5 +1,5 @@ use super::process::Process; -use super::{ExecutionResult, KernelOutput, KernelState, OutputCallback, StatusCallback}; +use super::{ExecutionResult, KernelOutput, KernelState, KernelTarget, OutputCallback, StatusCallback}; use ide_core::{CancellationToken, IdeError, IdeResult}; use jupyter_protocol::{ExecuteRequest, JupyterMessage, KernelInfoRequest, ShutdownRequest}; use jupyter_zmq_client::{ClientControlConnection, Connection, DealerSendConnection, RawMessage}; @@ -16,7 +16,11 @@ use tokio::time::{Instant, MissedTickBehavior}; use uuid::Uuid; use zeromq::SocketRecv; +pub(crate) mod remote; + const STARTUP_TIMEOUT: Duration = Duration::from_secs(30); +/// A heavy kernel on a shared server (a JupyterHub) can take longer. +const REMOTE_STARTUP_TIMEOUT: Duration = Duration::from_secs(60); const INTERRUPT_TIMEOUT: Duration = Duration::from_secs(5); const SEND_TIMEOUT: Duration = Duration::from_secs(3); const MAX_MESSAGE_BYTES: usize = 8 * 1024 * 1024; @@ -44,7 +48,7 @@ struct Execution { } pub(super) struct Running { - pub python: PathBuf, + pub target: KernelTarget, pub stop: CancellationToken, requests: mpsc::Sender, task: Option>, @@ -55,14 +59,14 @@ impl Running { pub fn spawn( runtime: PathBuf, notebook: PathBuf, - python: PathBuf, + target: KernelTarget, status: StatusCallback, ) -> (Self, oneshot::Receiver>) { let stop = CancellationToken::new(); let (requests, receiver) = mpsc::channel(1); let (ready, ready_rx) = oneshot::channel(); - let task = tokio::spawn(supervise(runtime, notebook, python.clone(), status, stop.clone(), receiver, ready)); - (Self { python, stop, requests, task: Some(task), busy: Arc::new(AtomicBool::new(false)) }, ready_rx) + let task = tokio::spawn(supervise(runtime, notebook, target.clone(), status, stop.clone(), receiver, ready)); + (Self { target, stop, requests, task: Some(task), busy: Arc::new(AtomicBool::new(false)) }, ready_rx) } pub fn is_finished(&self) -> bool { @@ -225,21 +229,63 @@ fn protocol(error: impl std::fmt::Display) -> IdeError { IdeError::new(ide_core::error::ErrorKind::Protocol, format!("Jupyter protocol: {error}")) } +/// How messages reach the kernel: ZeroMQ to a process the IDE owns, or a Jupyter server. +#[expect(clippy::large_enum_variant, reason = "one per running kernel")] +enum Link { + Local { process: Process, shell: DealerSendConnection, control: ClientControlConnection }, + Remote(remote::Link), +} + +impl Link { + async fn send(&mut self, message: JupyterMessage) -> IdeResult<()> { + match self { + Self::Local { shell, .. } => send(shell, message).await, + Self::Remote(link) => link.send(message).await, + } + } + + async fn interrupt(&mut self) -> IdeResult<()> { + match self { + Self::Local { process, .. } => process.interrupt(), + Self::Remote(link) => link.interrupt().await, + } + } + + /// Why a local process exited; a remote kernel's death closes its reader instead. + fn death(&mut self) -> IdeResult> { + match self { + Self::Local { process, .. } => process.death(), + Self::Remote(_) => Ok(None), + } + } + + fn stderr(&self) -> String { + match self { + Self::Local { process, .. } => process.stderr(), + Self::Remote(_) => String::new(), + } + } +} + struct Session { - process: Process, - shell: DealerSendConnection, - control: ClientControlConnection, + link: Link, frames: mpsc::Receiver, failure: Failure, _readers: Readers, } impl Session { - async fn connect( - runtime: &std::path::Path, - notebook: &std::path::Path, - python: &std::path::Path, - ) -> IdeResult { + async fn connect(runtime: &std::path::Path, notebook: &std::path::Path, target: &KernelTarget) -> IdeResult { + let python = match target { + KernelTarget::Local(python) => python, + KernelTarget::Remote(kernel) => { + let (tx, frames) = mpsc::channel(QUEUED_MESSAGES); + let failure = Failure::new(); + let queued = Arc::new(Semaphore::new(QUEUED_BYTES)); + let (link, reader) = remote::connect(kernel, tx, failure.clone(), queued).await?; + return Ok(Self { link: Link::Remote(link), frames, failure, _readers: Readers(vec![reader]) }); + } + }; let (process, info) = Process::spawn(runtime, notebook, python).await?; let session = Uuid::new_v4().to_string(); let identity = jupyter_zmq_client::peer_identity_for_session(&session).map_err(protocol)?; @@ -257,11 +303,12 @@ impl Session { reader(iopub, Channel::Iopub, tx.clone(), failure.clone(), queued.clone()), reader(shell_recv, Channel::Shell, tx, failure.clone(), queued), ]); - Ok(Self { process, shell, control, frames, failure, _readers: readers }) + Ok(Self { link: Link::Local { process, shell, control }, frames, failure, _readers: readers }) } async fn ready(&mut self, stop: &CancellationToken) -> IdeResult<()> { - let deadline = Instant::now() + STARTUP_TIMEOUT; + let remote = matches!(self.link, Link::Remote(_)); + let deadline = Instant::now() + if remote { REMOTE_STARTUP_TIMEOUT } else { STARTUP_TIMEOUT }; let mut probe = tokio::time::interval(Duration::from_millis(250)); probe.set_missed_tick_behavior(MissedTickBehavior::Delay); let mut request = String::new(); @@ -272,10 +319,13 @@ impl Session { biased; _ = stop.cancelled() => return Err(IdeError::cancelled()), _ = self.failure.token.cancelled() => return Err(self.failure.error()), - _ = tokio::time::sleep_until(deadline) => return Err(IdeError::unavailable(format!( - "selected Python kernel was not ready within 30 seconds; {}", self.process.stderr()))), + _ = tokio::time::sleep_until(deadline) => return Err(IdeError::unavailable(if remote { + "the kernel on the Jupyter server was not ready within 60 seconds".to_owned() + } else { + format!("selected Python kernel was not ready within 30 seconds; {}", self.link.stderr()) + })), _ = probe.tick() => { - if let Some(message) = self.process.death()? { + if let Some(message) = self.link.death()? { return Err(IdeError::unavailable(message)); } // Only readiness probes are retried, never user execution. @@ -284,7 +334,7 @@ impl Session { let message: JupyterMessage = KernelInfoRequest {}.into(); request = message.header.msg_id.clone(); idle = false; - send(&mut self.shell, message).await?; + self.link.send(message).await?; } else if !idle { // A slow subscriber can miss the first idle. Probe again // after a reply, proving BOTH live shell and subscription. @@ -326,7 +376,7 @@ impl Session { let request_id = request.header.msg_id.clone(); // If sending fails/times out, delivery is uncertain. Supervisor closes // the process; no caller may retry user code automatically. - send(&mut self.shell, request).await?; + self.link.send(request).await?; if !silent { status(notebook, KernelState::Busy, None); } @@ -342,19 +392,19 @@ impl Session { _ = stop.cancelled() => return Err(IdeError::cancelled()), _ = self.failure.token.cancelled() => return Err(self.failure.error()), _ = execution.cancel.cancelled(), if !interrupted => { - self.process.interrupt()?; + self.link.interrupt().await?; interrupted = true; interrupt_deadline = Some(Instant::now() + INTERRUPT_TIMEOUT); }, // Also after a read's time limit, which leaves no deadline. _ = execution.interrupt.cancelled(), if interrupt_deadline.is_none() => { - self.process.interrupt()?; + self.link.interrupt().await?; interrupted = true; interrupt_deadline = Some(Instant::now() + INTERRUPT_TIMEOUT); }, _ = death.tick() => { if execution.reply.is_closed() && !interrupted { - self.process.interrupt()?; + self.link.interrupt().await?; interrupted = true; interrupt_deadline = Some(Instant::now() + INTERRUPT_TIMEOUT); } @@ -365,7 +415,7 @@ impl Session { } interrupt_deadline = None; } - if let Some(message) = self.process.death()? { return Err(IdeError::unavailable(message)); } + if let Some(message) = self.link.death()? { return Err(IdeError::unavailable(message)); } }, frame = self.frames.recv() => { let frame = frame.ok_or_else(|| IdeError::unavailable("kernel readers closed during execution"))?; @@ -390,19 +440,23 @@ impl Session { } async fn shutdown(&mut self) { + let (process, control) = match &mut self.link { + Link::Local { process, control, .. } => (process, control), + Link::Remote(link) => return link.shutdown().await, + }; // Stop is separate from user interrupt: graceful shutdown, then kill only // our process group/job. It must remain bounded even for wedged Python. let request: JupyterMessage = ShutdownRequest { restart: false }.into(); - let _ = tokio::time::timeout(Duration::from_millis(500), self.control.send(request)).await; + let _ = tokio::time::timeout(Duration::from_millis(500), control.send(request)).await; let deadline = Instant::now() + Duration::from_millis(750); while Instant::now() < deadline { - match self.process.death() { + match process.death() { Ok(None) => {} _ => break, } tokio::time::sleep(Duration::from_millis(25)).await; } - self.process.shutdown().await; + process.shutdown().await; } } @@ -490,32 +544,40 @@ impl Budget { async fn supervise( runtime: PathBuf, notebook: PathBuf, - python: PathBuf, + target: KernelTarget, status: StatusCallback, stop: CancellationToken, mut requests: mpsc::Receiver, ready: oneshot::Sender>, ) { status(¬ebook, KernelState::Starting, None); + // Starting a remote kernel also waits for the server's REST answer. + let limit = match &target { + KernelTarget::Local(_) => STARTUP_TIMEOUT, + KernelTarget::Remote(_) => REMOTE_STARTUP_TIMEOUT + Duration::from_secs(15), + }; let startup = async { - let mut session = Session::connect(&runtime, ¬ebook, &python).await?; + let mut session = Session::connect(&runtime, ¬ebook, &target).await?; session.ready(&stop).await?; IdeResult::Ok(session) }; let result = tokio::select! { biased; _ = stop.cancelled() => Err(IdeError::cancelled()), - result = tokio::time::timeout(STARTUP_TIMEOUT, startup) => result.unwrap_or_else(|_| Err(IdeError::unavailable("selected Python kernel startup timed out"))), + result = tokio::time::timeout(limit, startup) => result.unwrap_or_else(|_| Err(IdeError::unavailable("kernel startup timed out"))), }; let mut session = match result { Ok(session) => session, Err(error) => { - let message = format!( - "{}; selected Python: {}. Ensure ipykernel is installed in this exact environment ({} -m pip install ipykernel); no fallback interpreter was used", - error.message, - python.display(), - python.display() - ); + let message = match &target { + KernelTarget::Local(python) => format!( + "{}; selected Python: {}. Ensure ipykernel is installed in this exact environment ({} -m pip install ipykernel); no fallback interpreter was used", + error.message, + python.display(), + python.display() + ), + KernelTarget::Remote(kernel) => format!("{}; Jupyter server: {}", error.message, kernel.base), + }; let error = IdeError::new(error.kind, message); status(¬ebook, KernelState::Dead, Some(error.message.clone())); let _ = ready.send(Err(error)); @@ -535,7 +597,7 @@ async fn supervise( biased; _ = stop.cancelled() => break, _ = failure.token.cancelled() => { reason = Some(failure.error().message); break; }, - _ = death.tick() => match session.process.death() { + _ = death.tick() => match session.link.death() { Ok(None) => {}, Ok(Some(message)) => { reason = Some(message); break; }, Err(error) => { reason = Some(error.message); break; }, diff --git a/crates/ide-notebook/src/kernel/transport/remote.rs b/crates/ide-notebook/src/kernel/transport/remote.rs new file mode 100644 index 0000000000..516629a380 --- /dev/null +++ b/crates/ide-notebook/src/kernel/transport/remote.rs @@ -0,0 +1,423 @@ +//! A kernel on a Jupyter server (`jupyter server`, JupyterLab, a JupyterHub user server): +//! REST calls start, interrupt and delete it, and its messages go over the kernel's +//! channels WebSocket as JSON text frames. +use super::{Channel, Failure, Frame, MAX_MESSAGE_BYTES, SEND_TIMEOUT, protocol}; +use crate::kernel::RemoteKernel; +use futures::SinkExt; +use futures::stream::StreamExt; +use ide_core::{IdeError, IdeResult}; +use jupyter_protocol::JupyterMessage; +use reqwest::Method; +use serde::Serialize; +use serde_json::{Value, json}; +use specta::Type; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; +use tokio::net::TcpStream; +use tokio::sync::{Semaphore, mpsc, oneshot}; +use tokio::task::JoinHandle; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::protocol::WebSocketConfig; +use tokio_tungstenite::tungstenite::{Message, http::HeaderValue}; +use tokio_tungstenite::{Connector, MaybeTlsStream, WebSocketStream, client_async_tls_with_config}; + +const REQUEST_TIMEOUT: Duration = Duration::from_secs(15); +/// Waits between attempts to reopen a dropped channels socket, about 15 s in all. +const RECONNECT_DELAYS: [Duration; 5] = [ + Duration::from_millis(500), + Duration::from_secs(1), + Duration::from_secs(2), + Duration::from_secs(4), + Duration::from_secs(8), +]; + +type Socket = WebSocketStream>; + +/// A kernel spec a Jupyter server offers. +#[derive(Clone, Debug, PartialEq, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct KernelSpec { + pub name: String, + pub display_name: String, +} + +/// Where a page's path starts on a Jupyter server (JupyterLab, Notebook, their editors). +const PAGES: [&str; 6] = ["lab", "tree", "notebooks", "edit", "doc", "voila"]; + +/// The server's base URL (`http(s)://host[:port]/[prefix/]`) from what a user pastes, and +/// the `?token=` it carries. A page's path (`/lab/tree/x.ipynb`, `/notebooks/x.ipynb`) is +/// dropped, so a URL copied from the browser works. A JupyterHub user server's +/// `/user//` is kept whatever the name. +pub fn normalize_server_url(text: &str) -> IdeResult<(String, Option)> { + let invalid = || IdeError::invalid("enter the Jupyter server's http:// or https:// URL"); + let mut url = reqwest::Url::parse(text.trim()).map_err(|_| invalid())?; + if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none_or(str::is_empty) { + return Err(invalid()); + } + let token = url.query_pairs().find(|(key, _)| key == "token").map(|(_, value)| value.into_owned()); + let mut segments: Vec = + url.path_segments().into_iter().flatten().filter(|s| !s.is_empty()).map(str::to_owned).collect(); + let prefix = if segments.first().is_some_and(|first| first == "user") { 2 } else { 0 }; + if let Some(page) = segments.iter().skip(prefix).position(|s| PAGES.contains(&s.as_str())) { + segments.truncate(prefix + page); + } + let path = segments.iter().map(|segment| format!("{segment}/")).collect::(); + url.set_path(&format!("/{path}")); + url.set_query(None); + url.set_fragment(None); + let _ = url.set_username(""); + let _ = url.set_password(None); + Ok((url.to_string(), token)) +} + +async fn call(base: &str, token: &str, method: Method, path: &str, body: Option) -> IdeResult { + // Redirects are not followed: the token must not travel to another host. + let client = ide_http::client::shared_without_redirects()?; + let write = method != Method::GET; + let mut request = client.request(method, format!("{base}{path}")).timeout(REQUEST_TIMEOUT); + if !token.is_empty() { + request = request.header(reqwest::header::AUTHORIZATION, format!("token {token}")); + } else if write && let Some(xsrf) = xsrf(&client, base).await { + // A server without a token checks XSRF on every request that changes something. + request = request.header(reqwest::header::COOKIE, format!("_xsrf={xsrf}")).header("X-XSRFToken", xsrf); + } + if let Some(body) = body { + request = request.header(reqwest::header::CONTENT_TYPE, "application/json").body(body.to_string()); + } + let response = request.send().await.map_err(|error| { + IdeError::unavailable(format!("could not reach the Jupyter server: {}", ide_http::client::describe(&error))) + })?; + let status = response.status(); + if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN { + return Err(IdeError::unavailable(if token.is_empty() { + "the Jupyter server needs a token" + } else { + "the Jupyter server did not accept the token" + })); + } + if !status.is_success() { + return Err(IdeError::unavailable(format!("the Jupyter server answered {status} to {path}"))); + } + let bytes = response + .bytes() + .await + .map_err(|error| IdeError::unavailable(format!("Jupyter server: {}", ide_http::client::describe(&error))))?; + if bytes.is_empty() { + return Ok(Value::Null); + } + serde_json::from_slice(&bytes).map_err(|_| IdeError::unavailable("the URL did not answer like a Jupyter server")) +} + +/// The `_xsrf` cookie the server sets on any page (an API reply sets none). +async fn xsrf(client: &reqwest::Client, base: &str) -> Option { + let response = client.get(base).timeout(REQUEST_TIMEOUT).send().await.ok()?; + response.headers().get_all(reqwest::header::SET_COOKIE).iter().find_map(|cookie| { + let value = cookie.to_str().ok()?.split(';').next()?.trim().strip_prefix("_xsrf=")?; + Some(value.trim_matches('"').to_owned()) + }) +} + +/// The server's kernel specs, its default first. Also checks the URL and the token. +pub async fn kernel_specs(base: &str, token: &str) -> IdeResult> { + parse_specs(&call(base, token, Method::GET, "api/kernelspecs", None).await?) +} + +fn parse_specs(reply: &Value) -> IdeResult> { + let specs = reply["kernelspecs"] + .as_object() + .ok_or_else(|| IdeError::unavailable("the URL did not answer like a Jupyter server"))?; + let default = reply["default"].as_str().unwrap_or_default(); + let mut specs: Vec = specs + .iter() + .map(|(name, spec)| KernelSpec { + name: name.clone(), + display_name: spec["spec"]["display_name"].as_str().unwrap_or(name).to_owned(), + }) + .collect(); + specs.sort_by(|a, b| (a.name != default, &a.display_name).cmp(&(b.name != default, &b.display_name))); + Ok(specs) +} + +/// A kernel the IDE started on a server. Deleted there when the last handle goes, so a +/// startup that fails, times out or is cancelled leaves nothing running. +struct Kernel { + base: String, + token: String, + id: String, + deleted: AtomicBool, +} + +async fn delete(base: &str, token: &str, id: &str) { + let _ = call(base, token, Method::DELETE, &format!("api/kernels/{id}"), None).await; +} + +impl Kernel { + async fn delete(&self) { + if !self.deleted.swap(true, Ordering::AcqRel) { + delete(&self.base, &self.token, &self.id).await; + } + } +} + +impl Drop for Kernel { + fn drop(&mut self) { + if !*self.deleted.get_mut() + && let Ok(runtime) = tokio::runtime::Handle::try_current() + { + let (base, token, id) = (self.base.clone(), self.token.clone(), self.id.clone()); + runtime.spawn(async move { delete(&base, &token, &id).await }); + } + } +} + +pub(crate) struct Link { + kernel: Arc, + outgoing: mpsc::Sender, +} + +/// Starts a kernel of `kernel.spec` and connects to its channels; frames go to `tx` like +/// a local kernel's ZeroMQ frames. The returned task owns the socket and reopens it, for +/// the same kernel, when it drops. +pub(super) async fn connect( + kernel: &RemoteKernel, + tx: mpsc::Sender, + failure: Failure, + queued: Arc, +) -> IdeResult<(Link, JoinHandle<()>)> { + let RemoteKernel { base, token, spec } = kernel.clone(); + // Not cancelled with the caller: a kernel the server starts after that is deleted. + let (sent, started) = oneshot::channel(); + tokio::spawn(async move { + let reply = call(&base, &token, Method::POST, "api/kernels", Some(json!({ "name": spec }))).await; + let kernel = reply.and_then(|reply| { + let id = reply["id"].as_str().ok_or_else(|| protocol("kernel start reply has no id"))?.to_owned(); + Ok(Arc::new(Kernel { base, token, id, deleted: AtomicBool::new(false) })) + }); + let _ = sent.send(kernel); + }); + let kernel = started.await.map_err(|_| IdeError::unavailable("kernel start task ended"))??; + let session = uuid::Uuid::new_v4().to_string(); + let socket = open_channels(&kernel, &session).await?; + let (outgoing, messages) = mpsc::channel(16); + let pump = tokio::spawn(pump(kernel.clone(), session, socket, messages, tx, failure, queued)); + Ok((Link { kernel, outgoing }, pump)) +} + +/// Moves messages between the socket and the session until the link goes. A socket that +/// drops is reopened with the same session id, so the server replays what it buffered. +async fn pump( + kernel: Arc, + session: String, + mut socket: Socket, + mut messages: mpsc::Receiver, + tx: mpsc::Sender, + failure: Failure, + queued: Arc, +) { + loop { + tokio::select! { + message = messages.recv() => { + let Some(message) = message else { return }; + match tokio::time::timeout(SEND_TIMEOUT, socket.send(Message::Text(message.into()))).await { + Ok(Ok(())) => {} + _ => return failure.fail(IdeError::unavailable( + "sending to the Jupyter server failed; delivery uncertain, not retried", + )), + } + } + incoming = socket.next() => { + let text = match incoming { + Some(Ok(Message::Text(text))) => text, + // Binary frames carry messages with buffers (widgets), which notebooks do not show. + Some(Ok(Message::Close(_)) | Err(_)) | None => match reopen(&kernel, &session).await { + Ok(reopened) => { socket = reopened; continue; } + Err(error) => return failure.fail(error), + }, + Some(Ok(_)) => continue, + }; + match frame(text.as_str(), &queued) { + Ok(Some(frame)) => { + if tx.try_send(frame).is_err() { + return failure.fail(IdeError::unavailable( + "kernel output queue overflow; execution stopped to bound memory", + )); + } + } + Ok(None) => {} + Err(error) => return failure.fail(error), + } + } + } + } +} + +async fn reopen(kernel: &Kernel, session: &str) -> IdeResult { + let mut last = None; + for delay in RECONNECT_DELAYS { + tokio::time::sleep(delay).await; + match open_channels(kernel, session).await { + Ok(socket) => return Ok(socket), + Err(error) => last = Some(error), + } + } + let reason = last.map(|error| error.message).unwrap_or_default(); + Err(IdeError::unavailable(format!( + "lost the connection to the Jupyter server ({reason}); the kernel may still be running there" + ))) +} + +async fn open_channels(kernel: &Kernel, session: &str) -> IdeResult { + let Kernel { base, token, id, .. } = kernel; + let ws = base.replacen("http", "ws", 1); + let url = format!("{ws}api/kernels/{id}/channels?session_id={session}"); + let mut request = url + .as_str() + .into_client_request() + .map_err(|error| IdeError::invalid(format!("Jupyter server URL: {error}")))?; + if !token.is_empty() { + let value = HeaderValue::from_str(&format!("token {token}")) + .map_err(|_| IdeError::invalid("the token contains characters a header cannot carry"))?; + request.headers_mut().insert("authorization", value); + } + let config = + WebSocketConfig::default().max_message_size(Some(MAX_MESSAGE_BYTES)).max_frame_size(Some(MAX_MESSAGE_BYTES)); + let connector = if ws.starts_with("wss:") { + Connector::Rustls(Arc::new(ide_http::client::tls_config()?)) + } else { + Connector::Plain + }; + let opening = async { + // Through the HTTP proxy the REST calls use, if any. + let stream = + ide_http::tunnel::connect(&reqwest::Url::parse(&url).map_err(|_| IdeError::invalid("Jupyter server URL"))?) + .await?; + client_async_tls_with_config(request, stream, Some(config), Some(connector)) + .await + .map_err(|error| IdeError::unavailable(format!("could not connect to the kernel's channels: {error}"))) + }; + let (socket, _) = tokio::time::timeout(REQUEST_TIMEOUT, opening) + .await + .map_err(|_| IdeError::unavailable("connecting to the kernel's channels on the Jupyter server timed out"))??; + Ok(socket) +} + +/// One JSON message from the channels socket; `None` for channels notebooks do not use. +fn frame(text: &str, queued: &Arc) -> IdeResult> { + let bytes = text.len(); + if bytes > MAX_MESSAGE_BYTES { + return Err(IdeError::unavailable("kernel message exceeds 8 MiB limit; execution stopped")); + } + let mut value: Value = serde_json::from_str(text).map_err(protocol)?; + let channel = match value["channel"].as_str() { + Some("shell") => Channel::Shell, + Some("iopub") => Channel::Iopub, + _ => return Ok(None), + }; + let kind = value["header"]["msg_type"].as_str().ok_or_else(|| protocol("missing Jupyter message type"))?.to_owned(); + // The server restarts a kernel that died; its state, and any run, is gone. + if kind == "status" && matches!(value["content"]["execution_state"].as_str(), Some("restarting" | "dead")) { + return Err(IdeError::unavailable("the kernel on the Jupyter server died")); + } + let parent = value["parent_header"]["msg_id"].as_str().unwrap_or_default().to_owned(); + let permit = queued + .clone() + .try_acquire_many_owned(bytes as u32) + .map_err(|_| IdeError::unavailable("kernel output queue exceeds 16 MiB; execution stopped"))?; + Ok(Some(Frame { channel, parent, kind, content: value["content"].take(), bytes, _permit: Some(permit) })) +} + +impl Link { + pub(super) async fn send(&mut self, mut message: JupyterMessage) -> IdeResult<()> { + message.channel = Some(jupyter_protocol::Channel::Shell); + let mut value = serde_json::to_value(&message).map_err(protocol)?; + value["buffers"] = json!([]); + tokio::time::timeout(SEND_TIMEOUT, self.outgoing.send(value.to_string())) + .await + .map_err(|_| IdeError::unavailable("kernel request send timed out; delivery uncertain, not retried"))? + .map_err(|_| IdeError::unavailable("the connection to the Jupyter server closed")) + } + + /// Asks the server to interrupt the kernel, without waiting: the run keeps reading + /// output meanwhile, and its interrupt deadline covers a server that does not answer. + pub(super) async fn interrupt(&mut self) -> IdeResult<()> { + let kernel = self.kernel.clone(); + tokio::spawn(async move { + let _ = + call(&kernel.base, &kernel.token, Method::POST, &format!("api/kernels/{}/interrupt", kernel.id), None) + .await; + }); + Ok(()) + } + + /// Deletes the kernel and waits for the server's answer. A server that cannot be + /// reached keeps it until it culls idle kernels, if it is configured to. + pub(super) async fn shutdown(&mut self) { + self.kernel.delete().await; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn server_urls_are_reduced_to_their_base() { + let base = |text| normalize_server_url(text).unwrap(); + assert_eq!(base("http://localhost:8888"), ("http://localhost:8888/".into(), None)); + assert_eq!( + base(" http://127.0.0.1:8888/lab?token=abc "), + ("http://127.0.0.1:8888/".into(), Some("abc".into())) + ); + assert_eq!( + base("https://hub.example.com/user/alice/lab"), + ("https://hub.example.com/user/alice/".into(), None) + ); + assert_eq!( + base("https://hub.example.com/user/alice/tree?x=1#y"), + ("https://hub.example.com/user/alice/".into(), None) + ); + // A page's path, wherever it ends. + assert_eq!(base("http://localhost:8888/lab/tree/work/x.ipynb"), ("http://localhost:8888/".into(), None)); + assert_eq!( + base("http://localhost:8888/notebooks/x.ipynb?token=t"), + ("http://localhost:8888/".into(), Some("t".into())) + ); + assert_eq!(base("https://host/jupyter/doc/tree/x.ipynb"), ("https://host/jupyter/".into(), None)); + // A Hub user named like a page keeps the name. + assert_eq!(base("https://hub.example.com/user/lab/"), ("https://hub.example.com/user/lab/".into(), None)); + assert_eq!( + base("https://hub.example.com/user/lab/lab/tree/a"), + ("https://hub.example.com/user/lab/".into(), None) + ); + assert!(normalize_server_url("file:///tmp").is_err()); + assert!(normalize_server_url("localhost:8888").is_err()); + } + + #[test] + fn kernel_specs_list_the_default_first() { + let reply = json!({"default": "python3", "kernelspecs": { + "ir": {"name": "ir", "spec": {"display_name": "R"}}, + "python3": {"name": "python3", "spec": {"display_name": "Python 3 (ipykernel)"}}, + "julia": {"name": "julia", "spec": {}}, + }}); + let names: Vec<_> = parse_specs(&reply).unwrap().into_iter().map(|s| s.display_name).collect(); + assert_eq!(names, ["Python 3 (ipykernel)", "R", "julia"]); + assert!(parse_specs(&json!({"message": "not found"})).is_err()); + } + + #[test] + fn channel_messages_become_frames() { + let queued = Arc::new(Semaphore::new(1 << 20)); + let reply = json!({"channel": "shell", "header": {"msg_type": "execute_reply"}, + "parent_header": {"msg_id": "run-1"}, "content": {"status": "ok"}}); + let frame = frame(&reply.to_string(), &queued).unwrap().unwrap(); + assert!(frame.channel == Channel::Shell && frame.parent == "run-1" && frame.kind == "execute_reply"); + assert_eq!(frame.content["status"], "ok"); + let stdin = json!({"channel": "stdin", "header": {"msg_type": "input_request"}}); + assert!(super::frame(&stdin.to_string(), &queued).unwrap().is_none()); + let died = json!({"channel": "iopub", "header": {"msg_type": "status"}, "parent_header": {}, + "content": {"execution_state": "restarting"}}); + assert!(super::frame(&died.to_string(), &queued).is_err()); + } +} diff --git a/crates/ide-notebook/tests/kernel_runtime.rs b/crates/ide-notebook/tests/kernel_runtime.rs index ba4eb61c07..b00eb8e35a 100644 --- a/crates/ide-notebook/tests/kernel_runtime.rs +++ b/crates/ide-notebook/tests/kernel_runtime.rs @@ -27,7 +27,7 @@ fn manager(root: &Path) -> Arc { async fn run( manager: &KernelManager, notebook: &Path, - python: &Path, + target: impl Into, code: &str, ) -> (IdeResult, Vec) { let outputs: Outputs = Arc::new(Mutex::new(Vec::new())); @@ -36,7 +36,7 @@ async fn run( Duration::from_secs(45), manager.execute( notebook, - python, + target, code, CancellationToken::new(), Arc::new(move |output| sink.lock().unwrap().push(output)), @@ -424,3 +424,132 @@ async fn interrupt_stops_a_stuck_inspection_and_keeps_state() { assert_eq!(result.unwrap().status, "ok", "the kernel and its state survive"); manager.shutdown().await; } + +#[tokio::test] +#[ignore = "requires OPENIDEA_TEST_JUPYTER_URL (and OPENIDEA_TEST_JUPYTER_TOKEN) of a running Jupyter server"] +async fn remote_kernel_runs_interrupts_restarts_and_is_deleted() { + let (server, token, target) = remote(None).await; + let before = server_kernels(&server, &token).await; + let root = tempfile::tempdir().unwrap(); + let notebook = root.path().join("remote.ipynb"); + let manager = manager(root.path()); + let run = |code: &'static str| { + let (manager, notebook, target) = (manager.clone(), notebook.clone(), target.clone()); + async move { + let outputs: Outputs = Arc::new(Mutex::new(Vec::new())); + let sink = outputs.clone(); + let result = manager + .execute( + ¬ebook, + target, + code, + CancellationToken::new(), + Arc::new(move |o| sink.lock().unwrap().push(o)), + ) + .await; + let outputs = std::mem::take(&mut *outputs.lock().unwrap()); + (result, outputs) + } + }; + let (result, outputs) = run("answer = 6 * 7\nanswer").await; + assert_eq!(result.unwrap().status, "ok"); + assert!(outputs.iter().any(|o| o.kind == "execute_result" && o.content["data"]["text/plain"] == "42")); + let sleeping = tokio::spawn(run("import time\ntime.sleep(30)")); + tokio::time::sleep(Duration::from_secs(2)).await; + manager.interrupt(¬ebook).await.unwrap(); + let (result, _) = tokio::time::timeout(Duration::from_secs(10), sleeping).await.unwrap().unwrap(); + assert!(result.is_err() || result.unwrap().status == "error", "the interrupted run must not succeed"); + let (result, _) = run("answer").await; + assert_eq!(result.unwrap().status, "ok", "state survives an interrupt"); + manager.restart(¬ebook).await.unwrap(); + let (result, outputs) = run("answer").await; + assert_eq!(result.unwrap().status, "error"); + assert!(outputs.iter().any(|o| o.kind == "error" && o.content["ename"] == "NameError")); + manager.shutdown_kernel(¬ebook).await.unwrap(); + assert_eq!(server_kernels(&server, &token).await, before, "closing the notebook deletes its kernel on the server"); +} + +/// The test server from `OPENIDEA_TEST_JUPYTER_URL` / `OPENIDEA_TEST_JUPYTER_TOKEN`, with `base` +/// in place of its URL when given (a forwarder in front of it). +async fn remote(base: Option) -> (String, String, ide_notebook::kernel::KernelTarget) { + use ide_notebook::kernel::{KernelTarget, RemoteKernel, kernel_specs, normalize_server_url}; + let (server, in_url) = normalize_server_url(&std::env::var("OPENIDEA_TEST_JUPYTER_URL").unwrap()).unwrap(); + let token = std::env::var("OPENIDEA_TEST_JUPYTER_TOKEN").ok().or(in_url).unwrap_or_default(); + let spec = kernel_specs(&server, &token).await.unwrap().remove(0).name; + let base = base.unwrap_or(server.clone()); + (server.clone(), token.clone(), KernelTarget::Remote(RemoteKernel { base, token, spec })) +} + +/// The ids of the server's kernels. +async fn server_kernels(server: &str, token: &str) -> std::collections::HashSet { + let client = ide_http::client::shared_without_redirects().unwrap(); + let reply = client.get(format!("{server}api/kernels")).header("Authorization", format!("token {token}")); + let kernels: Vec = serde_json::from_slice(&reply.send().await.unwrap().bytes().await.unwrap()).unwrap(); + kernels.iter().map(|kernel| kernel["id"].as_str().unwrap().to_owned()).collect() +} + +#[tokio::test] +#[ignore = "requires OPENIDEA_TEST_JUPYTER_URL (and OPENIDEA_TEST_JUPYTER_TOKEN) of a running Jupyter server"] +async fn closing_a_notebook_while_its_remote_kernel_starts_deletes_the_kernel() { + let (server, token, target) = remote(None).await; + let before = server_kernels(&server, &token).await; + let root = tempfile::tempdir().unwrap(); + let notebook = root.path().join("closed.ipynb"); + let manager = manager(root.path()); + let starting = { + let (manager, notebook) = (manager.clone(), notebook.clone()); + tokio::spawn(async move { run(&manager, ¬ebook, target, "1").await }) + }; + // Closed once the server has the kernel, before it answers. + while server_kernels(&server, &token).await == before { + tokio::time::sleep(Duration::from_millis(20)).await; + } + manager.shutdown_kernel(¬ebook).await.unwrap(); + assert!(starting.await.unwrap().0.is_err()); + for _ in 0..50 { + if server_kernels(&server, &token).await == before { + return; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + panic!("the kernel was left on the server"); +} + +#[tokio::test] +#[ignore = "requires OPENIDEA_TEST_JUPYTER_URL (and OPENIDEA_TEST_JUPYTER_TOKEN) of a running Jupyter server"] +async fn a_dropped_connection_to_the_server_reconnects_and_keeps_the_kernel() { + // A forwarder in front of the server whose connections can be cut. + let (server, token, _) = remote(None).await; + let upstream = reqwest::Url::parse(&server).unwrap(); + let upstream = format!("{}:{}", upstream.host_str().unwrap(), upstream.port_or_known_default().unwrap()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}/", listener.local_addr().unwrap()); + let links: Arc>>> = Arc::default(); + let accepting = { + let links = links.clone(); + tokio::spawn(async move { + while let Ok((mut client, _)) = listener.accept().await { + let upstream = upstream.clone(); + links.lock().unwrap().push(tokio::spawn(async move { + let mut server = tokio::net::TcpStream::connect(upstream).await.unwrap(); + let _ = tokio::io::copy_bidirectional(&mut client, &mut server).await; + })); + } + }) + }; + let (_, _, target) = remote(Some(base)).await; + let before = server_kernels(&server, &token).await; + let root = tempfile::tempdir().unwrap(); + let notebook = root.path().join("dropped.ipynb"); + let manager = manager(root.path()); + let (result, _) = run(&manager, ¬ebook, target.clone(), "kept = 5").await; + assert_eq!(result.unwrap().status, "ok"); + links.lock().unwrap().drain(..).for_each(|link| link.abort()); + tokio::time::sleep(Duration::from_millis(300)).await; + let (result, outputs) = run(&manager, ¬ebook, target, "kept").await; + assert_eq!(result.unwrap().status, "ok", "the run goes to the same kernel after reconnecting"); + assert!(outputs.iter().any(|o| o.kind == "execute_result" && o.content["data"]["text/plain"] == "5")); + manager.shutdown_kernel(¬ebook).await.unwrap(); + accepting.abort(); + assert_eq!(server_kernels(&server, &token).await, before, "closing the notebook deletes its one kernel"); +} diff --git a/docs/en/guide/notebook.mdx b/docs/en/guide/notebook.mdx index 8423b4b709..d315dc9c6b 100644 --- a/docs/en/guide/notebook.mdx +++ b/docs/en/guide/notebook.mdx @@ -42,6 +42,19 @@ Your choice is remembered per notebook. Change it while no cell is running. Each open notebook gets its own kernel process. Closing the notebook shuts its kernel down. +## Run on a Jupyter server + +To run a notebook where the data or the GPU is, choose **Connect to Jupyter Server…** at the bottom of the interpreter list (or run it from Find Action) and enter: + +- **URL**: the server's address, for example `http://localhost:8888/`, or a JupyterHub user server such as `https://hub.example.com/user/alice/`. A URL copied from JupyterLab, with `/lab` or `?token=…`, works too. +- **Token**: the server's token, or a JupyterHub API token. Not needed when the URL carries `?token=`. + +OpenIDEA checks them against the server, keeps the token in the system credential store and lists the server's kernels in every notebook's interpreter list. The choice is remembered per notebook, like an interpreter. + +Running, interrupting and restarting work as with a local kernel. OpenIDEA starts a kernel on the server for the notebook and shuts it down when you close the notebook. Only the source of the cells you run is sent; the notebook file stays on your computer and is saved there. If the connection to the server drops, OpenIDEA reconnects to the same kernel for about 15 seconds before giving up. The kernel's connection goes through the HTTP proxy of **Settings › Appearance & Behavior › System Settings › HTTP Proxy**, like the server's other requests. Signing in to JupyterHub through the browser is not supported; create an API token on the Hub's Token page instead. + +To forget a server and its token, choose **Remove Jupyter Server…** in the interpreter list or in Find Action. + ## Edit cells Every cell has a small toolbar: @@ -107,6 +120,6 @@ The list is read from the kernel without a visible run: it adds no output, histo ## Limits -- Only Python kernels are supported. Kernels for other languages and remote Jupyter servers are not. +- Local kernels are Python only. A Jupyter server's other kernels can run cells, but code intelligence is for Python. - Interactive widgets (ipywidgets) and JavaScript outputs do not run. - Undo and redo are not available while cells are running. diff --git a/docs/zh/guide/notebook.mdx b/docs/zh/guide/notebook.mdx index 67fe9e9cb1..dd30db753c 100644 --- a/docs/zh/guide/notebook.mdx +++ b/docs/zh/guide/notebook.mdx @@ -42,6 +42,19 @@ OpenIDEA 用笔记本编辑器打开 `.ipynb` 文件。你可以编辑代码单 每个打开的笔记本各有一个内核进程,关闭笔记本时内核随之关闭。 +## 在 Jupyter 服务器上运行 + +要在数据或 GPU 所在的机器上运行笔记本,请在解释器下拉框底部选择 **连接到 Jupyter 服务器…**(或在查找操作中运行),然后填写: + +- **URL**:服务器地址,例如 `http://localhost:8888/`,或 JupyterHub 的用户服务器,例如 `https://hub.example.com/user/alice/`。从 JupyterLab 复制的、带 `/lab` 或 `?token=…` 的 URL 也可以。 +- **令牌**:服务器的令牌,或 JupyterHub 的 API 令牌。URL 中带有 `?token=` 时无需填写。 + +OpenIDEA 会先用服务器校验它们,再把令牌保存在系统凭据库中,并在每个笔记本的解释器下拉框里列出该服务器的内核。和解释器一样,选择结果按笔记本分别记住。 + +运行、中断和重启的用法与本地内核相同。OpenIDEA 会为笔记本在服务器上启动一个内核,关闭笔记本时将其关闭。只会发送所运行单元格的源码,笔记本文件仍保存在你的电脑上。与服务器的连接断开时,OpenIDEA 会在约 15 秒内重新连接同一个内核,之后才放弃。内核的连接和服务器的其他请求一样,经过 **设置 › 外观与行为 › 系统设置 › HTTP 代理** 中的代理。不支持通过浏览器登录 JupyterHub,请在 Hub 的 Token 页面创建 API 令牌。 + +要移除某个服务器及其令牌,请在解释器下拉框或查找操作中选择 **移除 Jupyter 服务器…**。 + ## 编辑单元格 每个单元格都有一个小工具栏: @@ -107,6 +120,6 @@ OpenIDEA 用笔记本编辑器打开 `.ipynb` 文件。你可以编辑代码单 ## 限制 -- 只支持 Python 内核,不支持其他语言的内核,也不能连接远程 Jupyter 服务器。 +- 本地内核只支持 Python。Jupyter 服务器上的其他内核可以运行单元格,但代码智能只支持 Python。 - 交互式组件(ipywidgets)和 JavaScript 输出不会运行。 - 单元格运行期间不能撤销或重做。 diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index d33fafa953..ec2a092dea 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -368,6 +368,9 @@ jdk_download_location always project_host bin jdk_download_releases always project_host bindings async jdk_download_vendors always project_host bindings sync jdtls_required_java always project_host bindings async +jupyter_server_add trusted project_host bindings async +jupyter_server_remove always project_host bindings sync +jupyter_servers trusted project_host bindings async jvm_file_presentations always project_host bindings async languages always desktop bindings sync light_edit_open always desktop bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 6e52a10f45..64c2307c05 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -938,6 +938,14 @@ export const commands = { jdkDownloadVendors: () => __TAURI_INVOKE("jdk_download_vendors"), /** The Java version the window's jdtls needs; `None` while it isn't installed or doesn't tell. */ jdtlsRequiredJava: () => typedError(__TAURI_INVOKE("jdtls_required_java")), + /** + * Checks `url` and `token` against the server and saves them. A `?token=` in the URL + * (as JupyterLab prints it) is used when `token` is empty. + */ + jupyterServerAdd: (url: string, token: string) => typedError(__TAURI_INVOKE("jupyter_server_add", { url, token })), + jupyterServerRemove: (url: string) => typedError(__TAURI_INVOKE("jupyter_server_remove", { url })), + /** The saved servers and their kernel specs; a server that cannot be reached has none. */ + jupyterServers: () => typedError(__TAURI_INVOKE("jupyter_servers")), jvmFilePresentations: (paths: string[]) => typedError(__TAURI_INVOKE("jvm_file_presentations", { paths })), languages: () => __TAURI_INVOKE("languages"), /** @@ -9505,6 +9513,13 @@ export type JunitLaunch = { surefire: string[], }; +/** A Jupyter server notebooks can run on. */ +export type JupyterServer = { + /** Base URL, ending in `/`. */ + url: string, + kernels: KernelSpec[], +}; + /** The backend that reads a debugged JVM's objects (instances, fields, referrers). */ export type JvmBackendState = { kind: "ready" } | /** Turned off for the rest of the session: the debug adapter lacks what it needs. */ @@ -9647,6 +9662,12 @@ export type JvmValue = { kind: "null" } | { kind: "primitive"; typeName: string; /** `text` is `None` when `length` exceeds [`STRING_PREVIEW_CHARS`]. */ { kind: "string"; id: number; text: string | null; length: number } | { kind: "boxed"; id: number; typeName: string; text: string } | { kind: "object"; id: number; typeName: string } | { kind: "array"; id: number; typeName: string; length: number }; +/** A kernel spec a Jupyter server offers. */ +export type KernelSpec = { + name: string, + displayName: string, +}; + /** Editor › Code Style › › Tabs and Indents (unset fields inherit). */ export type LanguageCodeStyle = LanguageCodeStyle_Serialize | LanguageCodeStyle_Deserialize; diff --git a/src/features/notebook/Notebook.module.css b/src/features/notebook/Notebook.module.css index 72e8476bc4..f1ec08a51e 100644 --- a/src/features/notebook/Notebook.module.css +++ b/src/features/notebook/Notebook.module.css @@ -267,3 +267,25 @@ flex-wrap: wrap; } } + +.serverForm { + display: grid; + grid-template-columns: fit-content(30%) minmax(0, 1fr); + align-items: center; + gap: var(--space-2) var(--space-3); + padding: 14px; +} + +.serverLabel { + color: var(--fg-secondary); + text-align: right; +} + +.serverHint { + color: var(--fg-muted); +} + +.serverError { + color: var(--danger); + overflow-wrap: anywhere; +} diff --git a/src/features/notebook/NotebookEditor.tsx b/src/features/notebook/NotebookEditor.tsx index 15bb616a9f..28ad7d746d 100644 --- a/src/features/notebook/NotebookEditor.tsx +++ b/src/features/notebook/NotebookEditor.tsx @@ -13,9 +13,10 @@ import type { NotebookCell, NotebookCellDoc } from "@/bindings"; import { tx } from "@/platform/i18n"; import { useMarkdownPreviewFontSize } from "@/platform/languageSettings"; import { useProject } from "@/platform/project"; -import { Button, Dialog, EmptyState, IconButton, Select, Spinner } from "@/ui"; +import { Button, Dialog, EmptyState, IconButton, Select, Spinner, type SelectOption } from "@/ui"; import type { EditorInput } from "@/workbench/contributions"; import { CellEditor } from "./CellEditor"; +import { CONNECT, connectJupyterServer, REMOVE, remoteKernel, removeJupyterServer } from "./jupyterServer"; import { CellOutputs, MarkdownCell } from "./OutputView"; import { notebookSession, type CellReveal, type NotebookSession } from "./session"; import styles from "./Notebook.module.css"; @@ -100,13 +101,26 @@ function NotebookDocument({ session }: { session: NotebookSession }) { } as CSSProperties; const disabled = state.frozen || !state.snapshot; const historyDisabled = disabled || state.running; - const options = state.environments.map((sdk) => ({ + const options: SelectOption[] = state.environments.map((sdk) => ({ value: sdk.path, verbatim: true, verbatimDetail: true, label: sdk.name, detail: sdk.path, })); + for (const server of state.servers) { + options.push({ value: server.url, label: server.url, verbatim: true, section: true }); + for (const kernel of server.kernels) + options.push({ + value: remoteKernel(server.url, kernel.name), + verbatim: true, + verbatimDetail: true, + label: kernel.displayName, + detail: server.url, + }); + } + options.push({ value: CONNECT, label: "Connect to Jupyter Server…" }); + if (state.servers.length) options.push({ value: REMOVE, label: "Remove Jupyter Server…" }); if (state.python && !options.some((option) => option.value === state.python)) options.unshift({ value: state.python, @@ -181,13 +195,19 @@ function NotebookDocument({ session }: { session: NotebookSession }) { value={state.python} options={options} disabled={disabled || state.running} - onChange={(value) => session.selectPython(value)} + onChange={(value) => + value === CONNECT + ? connectJupyterServer(session) + : value === REMOVE + ? void removeJupyterServer() + : session.selectPython(value) + } /> invoke(session.detectEnvironments())} + onClick={() => invoke(session.detectEnvironments(true))} /> {state.running && } diff --git a/src/features/notebook/index.ts b/src/features/notebook/index.ts index 1ede7ae977..62325d0d9b 100644 --- a/src/features/notebook/index.ts +++ b/src/features/notebook/index.ts @@ -8,6 +8,7 @@ import { maybeEditorService, registerEditorKind, registerFileEditorProvider, + registerOverlay, registerToolWindow, registerUriOpener, toolWindowService, @@ -16,6 +17,7 @@ import { import { isTauri } from "@/platform/ipc"; import { ProviderAcquisitions } from "@/workbench/providerAcquisition"; import { registerConversions } from "./convert"; +import { connectJupyterServer, JupyterServerDialog, removeJupyterServer } from "./jupyterServer"; import { closeNotebook, existingNotebookSession, @@ -74,6 +76,7 @@ export function activate(): () => void { order: 28, component: lazyComponent(() => import("./VariablesView").then((m) => m.VariablesView)), }), + registerOverlay({ id: "notebook.jupyterServer", component: JupyterServerDialog }), registerActions([ { id: "notebook.variables.show", @@ -82,6 +85,20 @@ export function activate(): () => void { when: "projectOpen", run: () => toolWindowService().show(VARIABLES, true), }, + { + id: "notebook.connectJupyterServer", + title: "Connect to Jupyter Server…", + category: "Tools", + when: "projectOpen", + run: () => connectJupyterServer(), + }, + { + id: "notebook.removeJupyterServer", + title: "Remove Jupyter Server…", + category: "Tools", + when: "projectOpen", + run: () => void removeJupyterServer(), + }, ]), registerEditorKind({ kind: "notebook", diff --git a/src/features/notebook/jupyterServer.tsx b/src/features/notebook/jupyterServer.tsx new file mode 100644 index 0000000000..14f5de33ea --- /dev/null +++ b/src/features/notebook/jupyterServer.tsx @@ -0,0 +1,121 @@ +/** Connect to Jupyter Server…: saves a server's URL and token; its kernels join the notebook's kernel list. */ +import { useState } from "react"; +import { create } from "zustand"; +import type { JupyterServer } from "@/bindings"; +import { tx } from "@/platform/i18n"; +import { call, commands } from "@/platform/ipc"; +import { Dialog, Input, T } from "@/ui"; +import { chooseItem } from "@/workbench/inputDialogs"; +import { notebookBackend, notebookSessions, type NotebookSession } from "./session"; +import styles from "./Notebook.module.css"; + +/** The kernel drop-down's value for a kernel spec of a server. */ +export const remoteKernel = (server: string, spec: string) => `${server}#${spec}`; + +/** The drop-down entry that opens the dialog. */ +export const CONNECT = "jupyter:connect"; +/** The drop-down entry that removes a saved server. */ +export const REMOVE = "jupyter:remove"; + +const useConnect = create<{ open: boolean; session: NotebookSession | null }>(() => ({ open: false, session: null })); + +/** Opens the dialog; a server added from a notebook's drop-down becomes that notebook's kernel. */ +export function connectJupyterServer(session: NotebookSession | null = null) { + useConnect.setState({ open: true, session }); +} + +/** Probes the saved servers again and lists them in every open notebook. */ +function serversChanged() { + for (const open of notebookSessions()) void open.detectEnvironments(true); +} + +/** Remove Jupyter Server…: forgets a saved server and its token. */ +export async function removeJupyterServer() { + const servers = await notebookBackend.servers().catch(() => []); + const url = await chooseItem({ + title: "Remove Jupyter Server", + items: servers.map((server) => server.url), + empty: "No Jupyter servers saved", + }); + if (!url) return; + await call(commands.jupyterServerRemove(url)); + serversChanged(); +} + +function connected(server: JupyterServer, session: NotebookSession | null) { + serversChanged(); + const first = server.kernels[0]; + if (session && first) session.selectPython(remoteKernel(server.url, first.name)); +} + +export function JupyterServerDialog() { + const { open, session } = useConnect(); + if (!open) return null; + return useConnect.setState({ open: false, session: null })} />; +} + +function ConnectDialog({ session, onClose }: { session: NotebookSession | null; onClose: () => void }) { + const [url, setUrl] = useState(""); + const [token, setToken] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const connect = async () => { + setBusy(true); + setError(null); + try { + connected(await call(commands.jupyterServerAdd(url, token)), session); + onClose(); + } catch (cause) { + setError(cause instanceof Error ? cause.message : String(cause)); + } finally { + setBusy(false); + } + }; + return ( + void connect() }, + ]} + > +
+ + setUrl(e.target.value)} + /> + + + {error} + + + )} +
+
+ ); +} diff --git a/src/features/notebook/session.test.ts b/src/features/notebook/session.test.ts index bede0e5c87..a56cb80cc0 100644 --- a/src/features/notebook/session.test.ts +++ b/src/features/notebook/session.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import type * as TauriCore from "@tauri-apps/api/core"; import { EditorState } from "@codemirror/state"; -import type { IdeEvent, NotebookSnapshot } from "@/bindings"; +import type { IdeEvent, JupyterServer, NotebookSnapshot } from "@/bindings"; import { IpcError } from "@/platform/ipc"; import type * as Ipc from "@/platform/ipc"; import { @@ -79,6 +79,7 @@ function model() { open: async () => structuredClone(document), get: async () => structuredClone(document), environments: async () => [[], null], + servers: async () => [], close: async () => null, interrupt: async () => null, cancel: async () => {}, @@ -117,6 +118,20 @@ function model() { } describe("shared notebook mutation session", () => { + it("lists local interpreters without waiting for saved Jupyter servers", async () => { + const m = model(); + let answer: (servers: JupyterServer[]) => void = () => {}; + m.backend.environments = async () => [[{ name: "Python 3.12", path: "/py" } as never], "/py"]; + m.backend.servers = () => new Promise((resolve) => (answer = resolve)); + const session = new NotebookSession("/p/a.ipynb", m.backend, true); + await session.load(); + await vi.waitFor(() => expect(session.getState().environments).toHaveLength(1)); + expect(session.getState().servers).toEqual([]); + answer([{ url: "http://h/", kernels: [{ name: "python3", displayName: "Python 3" }] }]); + await vi.waitFor(() => expect(session.getState().servers).toHaveLength(1)); + await session.close(); + }); + it("fetches the code cells' language-server documents when the code cells change", async () => { const m = model(); const cellDocs = vi.fn(m.backend.cellDocs); diff --git a/src/features/notebook/session.ts b/src/features/notebook/session.ts index 251b41298e..109bfdd7b9 100644 --- a/src/features/notebook/session.ts +++ b/src/features/notebook/session.ts @@ -1,10 +1,20 @@ import { Channel } from "@tauri-apps/api/core"; import type { EditorState } from "@codemirror/state"; -import type { NotebookCellDoc, NotebookSnapshot, NotebookEdit, NotebookOutputEvent, Sdk, RequestId } from "@/bindings"; +import type { + JupyterServer, + NotebookCellDoc, + NotebookSnapshot, + NotebookEdit, + NotebookOutputEvent, + Sdk, + RequestId, +} from "@/bindings"; import { call, commands, IpcError, isTauri, nextRequestId, onIdeEvent } from "@/platform/ipc"; import { notifyEditorDocumentChanged } from "@/workbench/contributions"; import { OutputReducer } from "./outputs"; +let savedServers: Promise | null = null; + export const notebookBackend = { open: (path: string) => call(commands.notebookOpen(path)), get: (id: string) => call(commands.notebookGet(id)), @@ -25,6 +35,15 @@ export const notebookBackend = { output: Channel, ) => call(commands.notebookExecute(id, cells, python, request, output)), environments: () => Promise.all([call(commands.sdkDetect("python")), call(commands.sdkPythonEffective(null))]), + /** Saved Jupyter servers, probed over the network once for every notebook until `refresh`. */ + servers: (refresh = false) => { + if (refresh || !savedServers) + savedServers = call(commands.jupyterServers()).catch((error: unknown) => { + savedServers = null; + throw error; + }); + return savedServers; + }, cancel: (request: RequestId) => commands.cancelRequest(request), }; @@ -48,6 +67,8 @@ export interface NotebookViewState { kernel: string; python: string | null; environments: Sdk[]; + /** Saved Jupyter servers and their kernel specs. */ + servers: JupyterServer[]; pending: number; /** Language-server documents of the code cells, by cell id (none without a server). */ cellDocs: ReadonlyMap; @@ -109,6 +130,7 @@ export class NotebookSession { kernel: "idle", python: null, environments: [], + servers: [], pending: 0, cellDocs: new Map(), reveal: null, @@ -287,7 +309,10 @@ export class NotebookSession { .finally(() => this.publish({ loading: false })); return this.loading; } - async detectEnvironments() { + async detectEnvironments(refreshServers = false) { + // Saved servers answer over the network, or not at all: local interpreters do not wait. + // They are optional: an untrusted project or an unreachable store leaves local ones. + const servers = this.backend.servers(refreshServers).catch(() => []); try { const [environments, effective] = await this.backend.environments(); if (!this.disposed) { @@ -297,6 +322,8 @@ export class NotebookSession { } catch (error) { if (!this.disposed) this.reportOperation(error, "environment"); } + const listed = await servers; + if (!this.disposed) this.publish({ servers: listed }); } selectPython(python: string) { if (this.state.running || this.state.frozen) return; diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index bf16b2b19d..aad2ff7161 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4072,6 +4072,13 @@ "No notebook open": "No notebook open", "No kernel running": "No kernel running", "Run a cell to start the kernel.": "Run a cell to start the kernel.", + "Connect to Jupyter Server": "Connect to Jupyter Server", + "Connect to Jupyter Server…": "Connect to Jupyter Server…", + "Remove Jupyter Server": "Remove Jupyter Server", + "Remove Jupyter Server…": "Remove Jupyter Server…", + "No Jupyter servers saved": "No Jupyter servers saved", + "Not needed when the URL has ?token=": "Not needed when the URL has ?token=", + "The token is kept in the system credential store. Only cell source is sent to the server.": "The token is kept in the system credential store. Only cell source is sent to the server.", "Execute Selection in Python Console": "Execute Selection in Python Console", "No Python interpreter": "No Python interpreter", "Select an interpreter for this project to use the Python Console.": "Select an interpreter for this project to use the Python Console.", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 5aaee2d100..270b9a1b21 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -6849,6 +6849,13 @@ "No notebook open": "没有打开的笔记本", "No kernel running": "没有运行中的内核", "Run a cell to start the kernel.": "运行一个单元格以启动内核。", + "Connect to Jupyter Server": "连接到 Jupyter 服务器", + "Connect to Jupyter Server…": "连接到 Jupyter 服务器…", + "Remove Jupyter Server": "移除 Jupyter 服务器", + "Remove Jupyter Server…": "移除 Jupyter 服务器…", + "No Jupyter servers saved": "没有保存的 Jupyter 服务器", + "Not needed when the URL has ?token=": "URL 中带有 ?token= 时无需填写", + "The token is kept in the system credential store. Only cell source is sent to the server.": "令牌保存在系统凭据库中。只会把单元格源码发送到服务器。", "Retry Pending Edits": "重试待提交更改", "Run All": "运行全部", "Run Cell": "运行单元格",