diff --git a/crates/ide-db/src/jdbc/bridge.rs b/crates/ide-db/src/jdbc/bridge.rs new file mode 100644 index 000000000..4fc114653 --- /dev/null +++ b/crates/ide-db/src/jdbc/bridge.rs @@ -0,0 +1,416 @@ +use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind}; +use parking_lot::Mutex; +use std::{ + collections::HashMap, + path::Path, + process::Stdio, + sync::{ + Arc, + atomic::{AtomicU64, Ordering}, + }, + time::Duration, +}; +use tokio::{ + io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}, + process::Command, + sync::{mpsc, oneshot}, + time::{Instant, timeout, timeout_at}, +}; + +const LIMIT: usize = 16 * 1024 * 1024; +const HEADER: usize = 16; +const CANCEL_GRACE: Duration = Duration::from_secs(3); +type Replies = Arc>>>>; + +pub(super) struct Bridge { + closed: CancellationToken, + exited: CancellationToken, + sequence: AtomicU64, + outgoing: mpsc::Sender, + replies: Replies, +} + +struct Outgoing { + frame: Vec, + session: CancellationToken, + sent: oneshot::Sender>, +} + +struct Pending<'a> { + bridge: &'a Bridge, + id: u64, + incoming: mpsc::Receiver>, +} + +impl Drop for Pending<'_> { + fn drop(&mut self) { + self.bridge.replies.lock().remove(&self.id); + } +} + +impl Pending<'_> { + async fn recv(&mut self) -> IdeResult> { + tokio::select! { + biased; + frame = self.incoming.recv() => frame.ok_or_else(disconnected), + () = self.bridge.closed.cancelled() => Err(disconnected()), + } + } +} + +impl Bridge { + pub(super) fn start(cache: &Path, jars: &[String]) -> IdeResult { + let jdks = ide_sdk::java::installed_jdks(); + let java = ide_sdk::java::java_runtime(&jdks, 17) + .ok_or_else(|| IdeError::invalid("Install a Java 17 or newer runtime to use custom JDBC drivers"))?; + let jar = ide_sdk::java::jdbc_bridge_jar(cache) + .ok_or_else(|| IdeError::invalid("Cannot install the JDBC bridge in the application data directory"))?; + let classpath = std::env::join_paths(std::iter::once(jar.as_path()).chain(jars.iter().map(Path::new))) + .map_err(|_| IdeError::invalid("A JDBC JAR path contains the system classpath separator"))?; + // Embedded databases can resolve file URLs against the JVM's working directory. + let files = cache.join("files"); + std::fs::create_dir_all(&files)?; + let mut command = Command::new(ide_sdk::java::java_executable(&java.home)); + command.current_dir(files); + ide_core::process::prepare(command.as_std_mut()); + let mut child = command + .args(["-Xms8m", "-Xmx192m", "--enable-native-access=ALL-UNNAMED", "-cp"]) + .arg(classpath) + .args(["ai.openidea.jdbc.OpenIdeaJdbc", "--multiplex"]) + .env_remove("CLASSPATH") + .env_remove("JDK_JAVA_OPTIONS") + .env_remove("JAVA_TOOL_OPTIONS") + .env_remove("_JAVA_OPTIONS") + .kill_on_drop(true) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn()?; + let input = child.stdin.take().expect("piped"); + let output = child.stdout.take().expect("piped"); + let closed = CancellationToken::new(); + let exited = CancellationToken::new(); + tokio::spawn({ + let closed = closed.clone(); + let exited = exited.clone(); + async move { + tokio::select! { + _ = child.wait() => {} + () = closed.cancelled() => { + // The writer drops stdin. Give file-based drivers time to flush. + if timeout(Duration::from_secs(2), child.wait()).await.is_err() { + let _ = child.kill().await; + } + } + } + closed.cancel(); + exited.cancel(); + } + }); + Ok(Self::with_io(input, output, closed, exited)) + } + + fn with_io( + input: impl AsyncWrite + Unpin + Send + 'static, + output: impl AsyncRead + Unpin + Send + 'static, + closed: CancellationToken, + exited: CancellationToken, + ) -> Self { + let (outgoing, writes) = mpsc::channel(4); + let replies = Replies::default(); + tokio::spawn(write_frames(input, writes, closed.clone())); + tokio::spawn(read_frames(output, replies.clone(), closed.clone())); + Self { closed, exited, sequence: AtomicU64::new(1), outgoing, replies } + } + + pub(super) fn shutdown(&self) { + self.closed.cancel(); + } + + pub(super) fn is_closed(&self) -> bool { + self.closed.is_cancelled() + } + + pub(super) async fn close(&self) { + self.shutdown(); + self.exited.cancelled().await; + } + + async fn send(&self, frame: Vec, session: &CancellationToken) -> IdeResult<()> { + let (sent, receipt) = oneshot::channel(); + tokio::select! { + () = self.closed.cancelled() => return Err(disconnected()), + result = self.outgoing.send(Outgoing { frame, session: session.clone(), sent }) => { + result.map_err(|_| disconnected())?; + } + } + tokio::select! { + biased; + result = receipt => result.map_err(|_| disconnected())?, + () = self.closed.cancelled() => Err(disconnected()), + } + } + + pub(super) async fn exchange( + &self, + session: u32, + fields: &[&str], + cancel: &CancellationToken, + active: &CancellationToken, + ) -> IdeResult>> { + if cancel.is_cancelled() { + return Ok(None); + } + if active.is_cancelled() { + return Err(IdeError::cancelled()); + } + let id = self + .sequence + .try_update(Ordering::Relaxed, Ordering::Relaxed, |next| next.checked_add(1)) + .map_err(|_| IdeError::internal("JDBC request IDs exhausted"))?; + let frame = encode(id, session, fields)?; + let (sender, incoming) = mpsc::channel(2); + self.replies.lock().insert(id, sender); + let mut pending = Pending { bridge: self, id, incoming }; + let send = self.send(frame, active); + tokio::pin!(send); + let early_deadline = tokio::select! { + result = &mut send => { result?; None }, + () = cancel.cancelled() => { + let end = Instant::now() + CANCEL_GRACE; + timeout_at(end, send).await.map_err(|_| cancel_timeout())??; + Some(end) + } + }; + let deadline = tokio::select! { + biased; + () = cancel.cancelled() => early_deadline.unwrap_or_else(|| Instant::now() + CANCEL_GRACE), + data = pending.recv() => { + let data = data?; + if data.is_empty() { return Err(IdeError::invalid("Unexpected JDBC cancellation acknowledgement")); } + return Ok(Some(data)); + } + }; + let data = timeout_at(deadline, async { + self.send(header(id, session, 0).to_vec(), active).await?; + let first = pending.recv().await?; + let second = pending.recv().await?; + match (first.is_empty(), second.is_empty()) { + (true, false) => Ok(second), + (false, true) => Ok(first), + _ => Err(IdeError::invalid("Invalid JDBC cancellation acknowledgement")), + } + }) + .await + .map_err(|_| cancel_timeout())??; + match data.first() { + // A committed statement may finish before the bridge receives Cancel. + Some(1) => Ok(Some(data)), + Some(0) => Ok(None), + _ => Err(IdeError::invalid("Invalid JDBC cancellation response")), + } + } + + pub(super) async fn close_session(&self, session: u32) -> IdeResult<()> { + if self.is_closed() { + return Ok(()); + } + let control = CancellationToken::new(); + let data = timeout(CANCEL_GRACE, self.exchange(session, &["close"], &control, &control)) + .await + .map_err(|_| IdeError::new(ErrorKind::TimedOut, "Closing the JDBC console timed out"))??; + super::decode(&data.ok_or_else(IdeError::cancelled)?, "", 0.).map(|_| ()) + } +} + +impl Drop for Bridge { + fn drop(&mut self) { + self.shutdown(); + } +} + +async fn write_frames( + mut input: impl AsyncWrite + Unpin, + mut writes: mpsc::Receiver, + closed: CancellationToken, +) { + while let Some(outgoing) = tokio::select! { + biased; + () = closed.cancelled() => None, + outgoing = writes.recv() => outgoing, + } { + // If Close raced with an enqueued Open or query, discard it before writing. + if outgoing.session.is_cancelled() { + let _ = outgoing.sent.send(Err(IdeError::cancelled())); + continue; + } + let result = tokio::select! { + () = closed.cancelled() => break, + result = input.write_all(&outgoing.frame) => result.map_err(IdeError::from), + }; + let failed = result.is_err(); + let _ = outgoing.sent.send(result); + if failed { + break; + } + } + closed.cancel(); +} + +async fn read_frames(mut output: impl AsyncRead + Unpin, replies: Replies, closed: CancellationToken) { + loop { + let frame = async { + let id = output.read_u64().await?; + Ok::<_, IdeError>((id, read_frame(&mut output).await?)) + }; + let (id, data) = match tokio::select! { + () = closed.cancelled() => break, + result = frame => result, + } { + Ok(frame) => frame, + Err(_) => break, + }; + let sender = replies.lock().get(&id).cloned(); + // A response may arrive after its caller was cancelled and retired. + if let Some(sender) = sender + && matches!(sender.try_send(data), Err(mpsc::error::TrySendError::Full(_))) + { + break; + } + } + closed.cancel(); +} + +fn disconnected() -> IdeError { + IdeError::new(ErrorKind::Io, "JDBC connection was lost") +} + +fn cancel_timeout() -> IdeError { + IdeError::invalid( + "Cancellation timed out and the JDBC session was closed. Check the statement's status on the server before running it again. The next query will try to reconnect.", + ) +} + +fn header(id: u64, session: u32, fields: u32) -> [u8; HEADER] { + let mut bytes = [0; HEADER]; + bytes[..8].copy_from_slice(&id.to_be_bytes()); + bytes[8..12].copy_from_slice(&session.to_be_bytes()); + bytes[12..].copy_from_slice(&fields.to_be_bytes()); + bytes +} + +pub(super) fn frame_size(fields: &[&str]) -> IdeResult { + if fields.is_empty() || fields.len() > 8192 { + return Err(IdeError::invalid("Invalid JDBC field count")); + } + fields + .iter() + .try_fold(HEADER, |n, s| n.checked_add(4)?.checked_add(s.len()).filter(|n| *n <= LIMIT)) + .ok_or_else(|| IdeError::invalid("JDBC request exceeds 16 MiB")) +} + +fn encode(id: u64, session: u32, fields: &[&str]) -> IdeResult> { + let size = frame_size(fields)?; + let mut data = Vec::with_capacity(size); + data.extend_from_slice(&header(id, session, fields.len() as u32)); + for field in fields { + data.extend_from_slice(&(field.len() as u32).to_be_bytes()); + data.extend_from_slice(field.as_bytes()); + } + Ok(data) +} + +async fn read_frame(output: &mut (impl AsyncRead + Unpin)) -> IdeResult> { + let n = output.read_u32().await? as usize; + if n > LIMIT { + return Err(IdeError::invalid("JDBC response exceeds 16 MiB")); + } + let mut data = vec![0; n]; + output.read_exact(&mut data).await?; + Ok(data) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn frame_codec_checks_both_16_mib_boundaries() { + assert_eq!(encode(7, 3, &["a"]).unwrap(), [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 1, b'a']); + let mut field = "x".repeat(LIMIT - HEADER - 4); + assert_eq!(encode(1, 0, &[&field]).unwrap().len(), LIMIT); + field.push('x'); + assert!(encode(1, 0, &[&field]).is_err()); + let mut framed = vec![0u8; LIMIT + 4]; + framed[..4].copy_from_slice(&(LIMIT as u32).to_be_bytes()); + assert_eq!(read_frame(&mut framed.as_slice()).await.unwrap().len(), LIMIT); + assert!(read_frame(&mut &((LIMIT + 1) as u32).to_be_bytes()[..]).await.is_err()); + assert!(read_frame(&mut &[0, 0, 0, 2, 1u8][..]).await.is_err()); + } + + async fn reply(output: &mut (impl AsyncWrite + Unpin), id: u64, body: &[u8]) { + output.write_u64(id).await.unwrap(); + output.write_u32(body.len() as u32).await.unwrap(); + output.write_all(body).await.unwrap(); + } + + #[tokio::test] + async fn exchange_rejects_an_acknowledgement_for_an_uncancelled_request() { + let (input, mut peer_input) = tokio::io::duplex(32); + let (output, mut peer_output) = tokio::io::duplex(32); + let active = CancellationToken::new(); + let bridge = Bridge::with_io(input, output, CancellationToken::new(), CancellationToken::new()); + let peer = async { + let frame = encode(1, 0, &["query"]).unwrap(); + let mut actual = vec![0; frame.len()]; + peer_input.read_exact(&mut actual).await.unwrap(); + assert_eq!(actual, frame); + reply(&mut peer_output, 1, &[]).await; + }; + let (result, ()) = tokio::join!(bridge.exchange(0, &["query"], &active, &active), peer); + assert!(result.unwrap_err().message.contains("Unexpected JDBC cancellation acknowledgement")); + } + + #[tokio::test] + async fn cancellation_drains_tagged_replies_without_stealing_a_siblings_response() { + for ack_first in [true, false] { + let (input, mut peer_input) = tokio::io::duplex(1); + let (output, mut peer_output) = tokio::io::duplex(1); + let active = CancellationToken::new(); + let cancel = CancellationToken::new(); + let bridge = Bridge::with_io(input, output, CancellationToken::new(), CancellationToken::new()); + let peer = async { + let frame = encode(1, 11, &["query"]).unwrap(); + let mut request = vec![0; frame.len()]; + peer_input.read_exact(&mut request).await.unwrap(); + assert_eq!(request, frame); + peer_input.read_exact(&mut request).await.unwrap(); + assert_eq!(request, encode(2, 22, &["query"]).unwrap()); + + // Cancel during a partial reply header; the reader must stay on that frame. + peer_output.write_all(&1u64.to_be_bytes()[..2]).await.unwrap(); + cancel.cancel(); + let mut stop = [0; HEADER]; + peer_input.read_exact(&mut stop).await.unwrap(); + assert_eq!(stop, header(1, 11, 0)); + + peer_output.write_all(&1u64.to_be_bytes()[2..]).await.unwrap(); + let terminal = !ack_first; + peer_output.write_u32(u32::from(terminal)).await.unwrap(); + if terminal { + peer_output.write_u8(1).await.unwrap(); + } + reply(&mut peer_output, 2, &[1, b'b']).await; + reply(&mut peer_output, 1, if ack_first { &[0] } else { &[] }).await; + }; + let (a, b, ()) = tokio::join!( + biased; + bridge.exchange(11, &["query"], &cancel, &active), + bridge.exchange(22, &["query"], &active, &active), + peer, + ); + assert_eq!(a.unwrap(), (!ack_first).then(|| vec![1])); + assert_eq!(b.unwrap(), Some(vec![1, b'b'])); + } + } +} diff --git a/crates/ide-db/src/jdbc/mod.rs b/crates/ide-db/src/jdbc/mod.rs index 2b53ccf63..e2a3761bb 100644 --- a/crates/ide-db/src/jdbc/mod.rs +++ b/crates/ide-db/src/jdbc/mod.rs @@ -2,21 +2,21 @@ //! can run driver-specific initialization. A project source may connect only with the //! settings its user last accepted in the dialog; the approval lives outside the project. use crate::local_settings::persist_local; -use crate::{DataSource, DbManager, QueryResult, ResultColumn}; -use ide_core::{CancellationToken, IdeError, IdeResult}; +use crate::{ConsoleId, DataSource, DbManager, QueryResult, ResultColumn}; +use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind}; use serde::{Deserialize, Serialize}; use specta::Type; use std::collections::HashMap; use std::io::{Cursor, Read}; use std::path::{Path, PathBuf}; -use std::process::Stdio; +use std::sync::Arc; use std::time::{Duration, Instant}; -use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; -use tokio::process::{ChildStdin, ChildStdout, Command}; use tokio::sync::Mutex; -use tokio::time::{Instant as Deadline, timeout_at}; +use tokio::time::timeout; -const LIMIT: usize = 16 * 1024 * 1024; +mod bridge; + +use bridge::Bridge; #[derive(Debug, Clone, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -203,171 +203,73 @@ impl DbManager { } } -struct Bridge { - stop: tokio::sync::oneshot::Sender<()>, - exited: tokio::task::JoinHandle<()>, - sequence: u64, - input: ChildStdin, - output: ChildStdout, +struct Session { + id: u32, + // A physical JDBC Connection executes one request at a time. + opened: Mutex, + retired: CancellationToken, +} + +impl Session { + fn new(id: u32) -> Self { + Self { id, opened: Mutex::new(id == 0), retired: CancellationToken::new() } + } +} + +#[derive(Default)] +struct ConsoleSessions { + latest: u32, + opened: HashMap<(String, String), Arc>, } pub struct JdbcPool { - bridge: Mutex>, - closed: CancellationToken, + bridge: Arc, + service: Session, + consoles: parking_lot::Mutex, + shared_connection: bool, pub(crate) version: String, pub(crate) identifier_quote: String, } -impl Bridge { - fn start(cache: &Path, jars: &[String]) -> IdeResult { - let jdks = ide_sdk::java::installed_jdks(); - let java = ide_sdk::java::java_runtime(&jdks, 17) - .ok_or_else(|| IdeError::invalid("Install a Java 17 or newer runtime to use custom JDBC drivers"))?; - let jar = ide_sdk::java::jdbc_bridge_jar(cache) - .ok_or_else(|| IdeError::invalid("Cannot install the JDBC bridge in the application data directory"))?; - let classpath = std::env::join_paths(std::iter::once(jar.as_path()).chain(jars.iter().map(Path::new))) - .map_err(|_| IdeError::invalid("A JDBC JAR path contains the system classpath separator"))?; - // Embedded databases can resolve file URLs against the JVM's working directory. - let files = cache.join("files"); - std::fs::create_dir_all(&files)?; - let mut command = Command::new(ide_sdk::java::java_executable(&java.home)); - command.current_dir(files); - ide_core::process::prepare(command.as_std_mut()); - let mut child = command - .args(["-Xms8m", "-Xmx192m", "--enable-native-access=ALL-UNNAMED", "-cp"]) - .arg(classpath) - .arg("ai.openidea.jdbc.OpenIdeaJdbc") - .env_remove("CLASSPATH") - .env_remove("JDK_JAVA_OPTIONS") - .env_remove("JAVA_TOOL_OPTIONS") - .env_remove("_JAVA_OPTIONS") - .kill_on_drop(true) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .spawn()?; - let input = child.stdin.take().expect("piped"); - let output = child.stdout.take().expect("piped"); - let (stop, stopped) = tokio::sync::oneshot::channel(); - let exited = tokio::spawn(async move { - tokio::select! { - stop = stopped => { - // Disconnect closes stdin so a file-backed driver can flush. A dropped - // request or an unresponsive driver must be reaped without waiting. - if stop.is_err() || tokio::time::timeout(Duration::from_secs(2), child.wait()).await.is_err() { - let _ = child.kill().await; - } - } - _ = child.wait() => {} - } - }); - Ok(Self { input, output, stop, exited, sequence: 0 }) - } - - async fn close(self) { - drop(self.input); - let _ = self.stop.send(()); - let _ = self.exited.await; - } +/// Dropped futures and uncertain transport errors retire the connection they were using. +struct ActiveRequest<'a> { + pool: &'a JdbcPool, + session: &'a Session, + completed: bool, } -// Request: u64 request id, u32 field count, then length-prefixed UTF-8 fields. -// Zero fields cancels that id. Replies have a u32 length; zero acknowledges Cancel. -fn encode(id: u64, fields: &[&str]) -> IdeResult> { - if fields.is_empty() || fields.len() > 8192 { - return Err(IdeError::invalid("Invalid JDBC field count")); - } - let size = fields - .iter() - .try_fold(12usize, |n, s| n.checked_add(4)?.checked_add(s.len()).filter(|n| *n <= LIMIT)) - .ok_or_else(|| IdeError::invalid("JDBC request exceeds 16 MiB"))?; - let mut data = Vec::with_capacity(size); - data.extend_from_slice(&id.to_be_bytes()); - data.extend_from_slice(&(fields.len() as u32).to_be_bytes()); - for field in fields { - data.extend_from_slice(&(field.len() as u32).to_be_bytes()); - data.extend_from_slice(field.as_bytes()); - } - Ok(data) -} - -async fn read_frame(output: &mut (impl AsyncRead + Unpin)) -> IdeResult> { - let n = output.read_u32().await? as usize; - if n > LIMIT { - return Err(IdeError::invalid("JDBC response exceeds 16 MiB")); - } - let mut data = vec![0; n]; - output.read_exact(&mut data).await?; - Ok(data) -} - -const CANCEL_GRACE: Duration = Duration::from_secs(3); - -fn cancel_timeout() -> IdeError { - IdeError::invalid( - "Cancellation timed out and the JDBC session was closed. Check the statement's status on the server before running it again. The next query will try to reconnect.", - ) -} - -async fn exchange( - input: &mut (impl AsyncWrite + Unpin), - output: &mut (impl AsyncRead + Unpin), - frame: Vec, - cancel: &CancellationToken, -) -> IdeResult>> { - let mut stop = [0; 12]; - stop[..8].copy_from_slice(&frame[..8]); - let early_deadline = { - let send = input.write_all(&frame); - tokio::pin!(send); - tokio::select! { - result = &mut send => { result?; None }, - () = cancel.cancelled() => { - let end = Deadline::now() + CANCEL_GRACE; - timeout_at(end, send).await.map_err(|_| cancel_timeout())??; - Some(end) - } +impl Drop for ActiveRequest<'_> { + fn drop(&mut self) { + if !self.completed { + self.pool.retire(self.session); } - }; - drop(frame); - let (first, deadline) = { - let reply = read_frame(output); - tokio::pin!(reply); - let end = tokio::select! { - biased; - () = cancel.cancelled() => early_deadline.unwrap_or_else(|| Deadline::now() + CANCEL_GRACE), - data = &mut reply => { - let data = data?; - if data.is_empty() { return Err(IdeError::invalid("Unexpected JDBC cancellation acknowledgement")); } - return Ok(Some(data)); - } - }; - let first = timeout_at(end, async { - input.write_all(&stop).await?; - reply.await - }) - .await - .map_err(|_| cancel_timeout())??; - (first, end) - }; - // Drain both frames before the next statement can use this session. The driver - // may complete the statement before or after the control thread acknowledges it. - let data = if first.is_empty() { - timeout_at(deadline, read_frame(output)).await.map_err(|_| cancel_timeout())?? - } else { - if timeout_at(deadline, output.read_u32()).await.map_err(|_| cancel_timeout())?? != 0 { - return Err(IdeError::invalid("Invalid JDBC cancellation acknowledgement")); - } - first - }; - match data.first() { - // A committed statement may have finished before the control thread received Cancel. - Some(1) => Ok(Some(data)), - Some(0) => Ok(None), - _ => Err(IdeError::invalid("Invalid JDBC cancellation response")), } } +/// A second connection to an anonymous database would see a different database. +fn private_database_url(url: &str) -> bool { + if let Some(h2) = url.strip_prefix("jdbc:h2:mem:") { + return h2.is_empty() || h2.starts_with(';'); + } + let Some(sqlite) = url.strip_prefix("jdbc:sqlite:") else { + return false; + }; + let (path, query) = sqlite.split_once('?').unwrap_or((sqlite, "")); + if matches!(path, "" | ":memory:" | "file:") { + return true; + } + let option = |name| { + query + .split('&') + .rev() + .filter_map(|part| part.split_once('=')) + .find_map(|(key, value)| (key == name).then_some(value)) + }; + path.starts_with("file:") + && (path == "file::memory:" || option("mode") == Some("memory")) + && option("cache") != Some("shared") +} + impl JdbcPool { async fn connect( source: &DataSource, @@ -393,32 +295,85 @@ impl JdbcPool { let bridge = tokio::task::spawn_blocking(move || Bridge::start(&cache, &driver.jars)) .await .map_err(|e| IdeError::internal(e.to_string()))??; - let mut pool = Self { - bridge: Mutex::new(Some(bridge)), - closed: CancellationToken::new(), - version: String::new(), - identifier_quote: String::new(), - }; let args: Vec<_> = fields.iter().map(String::as_str).collect(); let cancel = CancellationToken::new(); - let result = tokio::time::timeout(Duration::from_secs(30), pool.request(&args, "", &cancel)) + let data = timeout(Duration::from_secs(30), bridge.exchange(0, &args, &cancel, &cancel)) .await - .map_err(|_| IdeError::new(ide_core::error::ErrorKind::TimedOut, "JDBC connection timed out"))??; + .map_err(|_| IdeError::new(ErrorKind::TimedOut, "JDBC connection timed out"))??; + let result = decode(&data.ok_or_else(IdeError::cancelled)?, "", 0.)?; let mut metadata = result.rows.into_iter().next().unwrap_or_default().into_iter(); - pool.version = metadata.next().flatten().unwrap_or_else(|| "Connected".into()); - pool.identifier_quote = metadata.next().flatten().unwrap_or_default().trim().into(); - Ok(pool) + Ok(Self { + bridge: Arc::new(bridge), + service: Session::new(0), + consoles: Default::default(), + shared_connection: private_database_url(&source.url), + version: metadata.next().flatten().unwrap_or_else(|| "Connected".into()), + identifier_quote: metadata.next().flatten().unwrap_or_default().trim().into(), + }) } pub(crate) async fn close(&self) { - self.closed.cancel(); - if let Some(bridge) = self.bridge.lock().await.take() { - bridge.close().await; - } + self.bridge.close().await; } pub(crate) fn is_closed(&self) -> bool { - self.closed.is_cancelled() + self.bridge.is_closed() + } + + fn console(&self, console: ConsoleId<'_>) -> IdeResult> { + let key = (console.window.to_owned(), console.path.to_owned()); + let mut sessions = self.consoles.lock(); + if let Some(existing) = sessions.opened.get(&key) + && !existing.retired.is_cancelled() + { + return Ok(existing.clone()); + } + let id = sessions.latest.checked_add(1).ok_or_else(|| IdeError::internal("JDBC session IDs exhausted"))?; + sessions.latest = id; + let session = Arc::new(Session::new(id)); + sessions.opened.insert(key, session.clone()); + Ok(session) + } + + pub(crate) async fn release_console(&self, console: ConsoleId<'_>) -> IdeResult<()> { + let key = (console.window.to_owned(), console.path.to_owned()); + // Retire the ID before allowing a reopened editor to allocate a replacement. + let session = self.consoles.lock().opened.remove(&key).inspect(|session| session.retired.cancel()); + if let Some(session) = session { + let closed = self.bridge.close_session(session.id).await; + self.shutdown_service_if_idle(); + closed?; + } + Ok(()) + } + + fn retire(&self, session: &Session) { + if session.retired.is_cancelled() { + return; + } + session.retired.cancel(); + if session.id != 0 { + let bridge = self.bridge.clone(); + let id = session.id; + tokio::spawn(async move { + let _ = bridge.close_session(id).await; + }); + } + self.shutdown_service_if_idle(); + } + + fn shutdown_service_if_idle(&self) { + if !self.service.retired.is_cancelled() { + return; + } + let has_consoles = + self.consoles.lock().opened.values().any(|session| { + !session.retired.is_cancelled() && session.opened.try_lock().map_or(true, |opened| *opened) + }); + // Service failure cannot discard a healthy editor's transaction or temporary tables. + if !has_consoles { + self.bridge.shutdown(); + } } pub(crate) async fn query( @@ -439,7 +394,21 @@ impl JdbcPool { cancel: &CancellationToken, schema: Option<&str>, ) -> IdeResult { - self.request( + self.query_in_console(sql, skip, max, cancel, schema, None).await + } + + pub(crate) async fn query_in_console( + &self, + sql: &str, + skip: usize, + max: usize, + cancel: &CancellationToken, + schema: Option<&str>, + console: Option>, + ) -> IdeResult { + let session = console.filter(|_| !self.shared_connection).map(|console| self.console(console)).transpose()?; + self.request_on( + session.as_deref().unwrap_or(&self.service), &["query", sql, &skip.to_string(), &max.min(i32::MAX as usize).to_string(), schema.unwrap_or_default()], sql, cancel, @@ -462,77 +431,84 @@ impl JdbcPool { } async fn request(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult { - let result = self.exchange_once(fields, sql, cancel).await; - if let Err(e) = &result - && fields.first() != Some(&"open") - && e.kind != ide_core::error::ErrorKind::Cancelled - && !self.is_closed() - && !self.session_valid().await - { - // The session is gone (a proxy or tunnel dropped the idle TCP connection): close the - // pool so the next statement or Connect starts a new one instead of failing forever. - self.close().await; + self.request_on(&self.service, fields, sql, cancel).await + } + + async fn request_on( + &self, + session: &Session, + fields: &[&str], + sql: &str, + cancel: &CancellationToken, + ) -> IdeResult { + // A rejected local request has not used the connection and cannot invalidate it. + bridge::frame_size(fields)?; + let mut opened = tokio::select! { + biased; + () = cancel.cancelled() => return Err(IdeError::cancelled()), + () = session.retired.cancelled() => { + return Err(if session.id == 0 { + IdeError::new(ErrorKind::Io, "The JDBC service connection was lost. Reconnect to restore catalog access.") + } else { + IdeError::cancelled() + }); + } + slot = session.opened.lock() => slot, + }; + let mut active = ActiveRequest { pool: self, session, completed: false }; + if !*opened { + let data = timeout(Duration::from_secs(30), self.exchange(session, &["open"], cancel)) + .await + .map_err(|_| IdeError::new(ErrorKind::TimedOut, "JDBC connection timed out"))??; + decode(&data.ok_or_else(IdeError::cancelled)?, "", 0.)?; + *opened = true; } + let start = Instant::now(); + let data = self.exchange(session, fields, cancel).await?; + let result = data + .ok_or_else(IdeError::cancelled) + .and_then(|data| decode(&data, sql, start.elapsed().as_secs_f64() * 1000.0)); + if result.as_ref().is_err_and(|error| error.kind != ErrorKind::Cancelled) && !self.session_valid(session).await + { + return result; + } + active.completed = true; result } - /// Keep-alive: checks the session (any SQL would be dialect-specific) and closes a dead one. + async fn exchange( + &self, + session: &Session, + fields: &[&str], + cancel: &CancellationToken, + ) -> IdeResult>> { + tokio::select! { + biased; + () = session.retired.cancelled() => Err(IdeError::cancelled()), + data = self.bridge.exchange(session.id, fields, cancel, &session.retired) => data, + } + } + + /// Keep-alive operates on the service connection without waiting on an editor's query. pub(crate) async fn ping(&self) -> IdeResult<()> { - if self.session_valid().await { + let _service = self.service.opened.lock().await; + if self.service.retired.is_cancelled() || self.session_valid(&self.service).await { return Ok(()); } - self.close().await; - Err(IdeError::new(ide_core::error::ErrorKind::Io, "JDBC connection was lost")) + self.retire(&self.service); + Err(IdeError::new(ErrorKind::Io, "JDBC connection was lost")) } - /// Whether the JDBC session still works, asked after a failed statement. - async fn session_valid(&self) -> bool { - if self.bridge.lock().await.is_none() { - return false; - } + /// Checks that an error was local to this statement before reusing its connection. + async fn session_valid(&self, session: &Session) -> bool { let cancel = CancellationToken::new(); - match tokio::time::timeout(Duration::from_secs(10), self.exchange_once(&["valid"], "", &cancel)).await { - Ok(Ok(result)) => { - result.rows.first().and_then(|row| row.first()).cloned().flatten().as_deref() != Some("false") - } - Ok(Err(_)) | Err(_) => false, - } - } - - async fn exchange_once(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult { - let mut slot = tokio::select! { - biased; - () = cancel.cancelled() => return Err(IdeError::cancelled()), - () = self.closed.cancelled() => return Err(IdeError::invalid("JDBC connection is closed")), - slot = self.bridge.lock() => slot, + let Ok(Ok(Some(data))) = timeout(Duration::from_secs(10), self.exchange(session, &["valid"], &cancel)).await + else { + return false; }; - let bridge = slot - .as_mut() - .ok_or_else(|| IdeError::invalid("JDBC connection is closed; reconnect to start a new session"))?; - bridge.sequence = bridge.sequence.wrapping_add(1); - let frame = encode(bridge.sequence, fields)?; - let mut bridge = slot.take().expect("checked above"); - // Dropping an in-flight request must discard its process and partially consumed frame. - let interrupted = self.closed.clone().drop_guard(); - let start = Instant::now(); - let response = tokio::select! { - biased; - () = self.closed.cancelled() => Err(IdeError::cancelled()), - response = exchange(&mut bridge.input, &mut bridge.output, frame, cancel) => response, - }; - let data = match response { - Ok(data) => { - *slot = Some(bridge); - interrupted.disarm(); - data - } - Err(e) => { - drop(bridge.stop); - let _ = bridge.exited.await; - return Err(e); - } - }; - decode(&data.ok_or_else(IdeError::cancelled)?, sql, start.elapsed().as_secs_f64() * 1000.0) + decode(&data, "", 0.).is_ok_and(|result| { + result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) == Some("true") + }) } } @@ -682,6 +658,33 @@ fn schema_columns(rows: Vec>>) -> HashMap| { @@ -703,68 +706,6 @@ mod tests { assert_eq!(by_table.len(), 2); } - #[tokio::test] - async fn frame_codec_checks_both_16_mib_boundaries() { - assert_eq!(encode(7, &["a"]).unwrap(), [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 1, b'a']); - let mut field = "x".repeat(LIMIT - 16); - assert_eq!(encode(1, &[&field]).unwrap().len(), LIMIT); - field.push('x'); - assert!(encode(1, &[&field]).is_err()); - let mut framed = vec![0u8; LIMIT + 4]; - framed[..4].copy_from_slice(&(LIMIT as u32).to_be_bytes()); - assert_eq!(read_frame(&mut framed.as_slice()).await.unwrap().len(), LIMIT); - assert!(read_frame(&mut &((LIMIT + 1) as u32).to_be_bytes()[..]).await.is_err()); - assert!(read_frame(&mut &[0, 0, 0, 2, 1u8][..]).await.is_err()); - } - - #[tokio::test] - async fn cancel_drains_partial_replies_in_either_order() { - for ack_first in [true, false] { - let (mut input, mut peer_input) = tokio::io::duplex(1); - let (mut output, mut peer_output) = tokio::io::duplex(1); - let cancel = CancellationToken::new(); - let frame = encode(42, &["query"]).unwrap(); - let peer = async { - let mut request = vec![0; frame.len()]; - peer_input.read_exact(&mut request).await.unwrap(); - assert_eq!(request, frame); - // The one-byte pipe forces the reader to consume part of the header before Cancel. - peer_output.write_all(&[0, 0]).await.unwrap(); - cancel.cancel(); - let mut stop = [0; 12]; - peer_input.read_exact(&mut stop).await.unwrap(); - assert_eq!(&stop[..8], &42u64.to_be_bytes()); - assert_eq!(&stop[8..], &[0; 4]); - let frames = if ack_first { [0, 0, 0, 0, 0, 1, 0] } else { [0, 1, 1, 0, 0, 0, 0] }; - peer_output.write_all(&frames).await.unwrap(); - }; - let (result, ()) = tokio::join!(exchange(&mut input, &mut output, frame.clone(), &cancel), peer); - assert_eq!(result.unwrap(), (!ack_first).then(|| vec![1])); - } - } - - #[tokio::test] - async fn exchange_rejects_unexpected_acknowledgements() { - let cancel = CancellationToken::new(); - let mut sink = tokio::io::sink(); - let mut reply = &[0, 0, 0, 1, 1u8][..]; - assert_eq!( - exchange(&mut sink, &mut reply, encode(1, &["query"]).unwrap(), &cancel).await.unwrap(), - Some(vec![1]) - ); - for cancelled in [false, true] { - if cancelled { - cancel.cancel(); - } - let mut duplicate_ack = &[0u8; 8][..]; - assert!(exchange(&mut sink, &mut duplicate_ack, encode(1, &["query"]).unwrap(), &cancel).await.is_err()); - } - let (mut peer, mut output) = tokio::io::duplex(4); - peer.write_u32(0).await.unwrap(); - let error = exchange(&mut sink, &mut output, encode(1, &["query"]).unwrap(), &cancel).await.unwrap_err(); - assert_eq!(error.message, cancel_timeout().message); - } - #[test] fn result_codec_preserves_null_and_rejects_incomplete_frames() { let mut frame = diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index a27a4a04a..c7c3adda5 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -1844,7 +1844,7 @@ impl DbManager { return Err(postgres_console_mode_changed()); } if let Pool::Jdbc(p) = &*pool { - return p.query_in_schema(statement, skip, max_rows, cancel, schema).await; + return p.query_in_console(statement, skip, max_rows, cancel, schema, console).await; } if let Pool::Clickhouse(p) = &*pool && console.is_some() diff --git a/crates/ide-db/src/route.rs b/crates/ide-db/src/route.rs index e015fd85e..17e75d9b6 100644 --- a/crates/ide-db/src/route.rs +++ b/crates/ide-db/src/route.rs @@ -240,22 +240,24 @@ impl DbManager { pub async fn release_target_console(&self, console: crate::ConsoleId<'_>, target: Option<&str>) -> IdeResult<()> { self.cursors.release_console(console, target); - let transactions: Vec<_> = self + let connections: Vec<_> = self .pools .lock() .iter() .filter(|(id, _)| target.is_none_or(|target| id.as_str() == target)) - .filter_map(|(_, slot)| slot.value.get()) - .map(|connection| { - if let Pool::Clickhouse(pool) = &*connection.pool { - pool.release_console(console); - } - connection.console_transactions.clone() - }) + .filter_map(|(_, slot)| slot.value.get().cloned()) .collect(); let mut result = Ok(()); - for transaction in transactions { - if let Err(error) = transaction.release(console).await { + for connection in connections { + let released = match &*connection.pool { + Pool::Clickhouse(pool) => { + pool.release_console(console); + Ok(()) + } + Pool::Jdbc(pool) => pool.release_console(console).await, + _ => connection.console_transactions.release(console).await, + }; + if let Err(error) = released { result = Err(error); } } diff --git a/crates/ide-db/tests/jdbc.rs b/crates/ide-db/tests/jdbc.rs index c939bacf0..46c296f69 100644 --- a/crates/ide-db/tests/jdbc.rs +++ b/crates/ide-db/tests/jdbc.rs @@ -1,5 +1,5 @@ use ide_core::{CancellationToken, IdeResult}; -use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey}; +use ide_db::{ConsoleId, DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey}; use std::{path::Path, sync::Arc}; fn manager(dir: &Path) -> DbManager { @@ -208,9 +208,11 @@ async fn duckdb_named_file_enforces_read_only_at_open() -> IdeResult<()> { reopened.save_sources(vec![source.clone()]).await?; assert_eq!(reopened.source("test")?.vendor, "duckdb"); assert_eq!(reopened.execute("test", "select id from items", 1, &cancel).await?.rows, [vec![Some("1".into())]]); - for query in ["insert into items values (2)", "create table added (id int)"] { - let err = reopened.execute("test", query, 1, &cancel).await.unwrap_err(); - assert!(err.message.to_lowercase().contains("read-only"), "{}", err.message); + for console in [None, Some(ConsoleId::new("window", "/reader.sql"))] { + for query in ["insert into items values (2)", "create table added (id int)"] { + let err = reopened.execute_in_console("test", query, 0, 1, &cancel, None, console).await.unwrap_err(); + assert!(err.message.to_lowercase().contains("read-only"), "{}", err.message); + } } assert!(!reopened.tables("test", "main").await?.iter().any(|table| table.name == "added")); reopened.disconnect("test").await; @@ -259,6 +261,89 @@ async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> { Ok(()) } +#[tokio::test] +#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"] +async fn duckdb_consoles_share_catalog_but_isolate_transactions_and_temporary_tables() -> IdeResult<()> { + let tmp = tempfile::tempdir()?; + let db = manager(tmp.path()); + register_duckdb(&db, Some("duckdb"))?; + db.save_sources(vec![DataSource { + id: "test".into(), + name: "DuckDB in memory".into(), + driver: DbDriver::Jdbc, + vendor: "duckdb".into(), + global: true, + jdbc_driver: "duck".into(), + url: "jdbc:duckdb:".into(), + ..Default::default() + }]) + .await?; + let cancel = CancellationToken::new(); + let a = ConsoleId::new("first", "/console.sql"); + let b = ConsoleId::new("second", "/console.sql"); + let run = |console, sql: &'static str| db.execute_in_console("test", sql, 0, 10, &cancel, None, Some(console)); + + db.execute("test", "CREATE TABLE durable (id INTEGER)", 1, &cancel).await?; + run(a, "CREATE TEMP TABLE local_only AS SELECT 7 AS id").await?; + assert!(run(b, "SELECT id FROM local_only").await.is_err(), "B must not see A's temporary table"); + run(b, "CREATE TEMP TABLE local_only AS SELECT 9 AS id").await?; + assert_eq!(run(a, "SELECT id FROM local_only").await?.rows, [vec![Some("7".into())]]); + + run(a, "BEGIN TRANSACTION").await?; + run(a, "INSERT INTO durable VALUES (1)").await?; + assert_eq!(run(a, "SELECT id FROM durable").await?.rows, [vec![Some("1".into())]]); + assert!(run(b, "SELECT id FROM durable").await?.rows.is_empty()); + db.release_target_console(a, Some("test")).await?; + assert_eq!(run(b, "SELECT id FROM local_only").await?.rows, [vec![Some("9".into())]]); + assert!(run(a, "SELECT id FROM local_only").await.is_err(), "a reopened console starts a fresh session"); + assert!(run(a, "SELECT id FROM durable").await?.rows.is_empty(), "closing A rolls back its transaction"); + db.disconnect("test").await; + Ok(()) +} + +#[tokio::test] +#[ignore = "requires SQLITE_JDBC_CLASSPATH, H2_JDBC_JAR and a local Java 17+ runtime"] +async fn anonymous_jdbc_databases_stay_shared_across_consoles() -> IdeResult<()> { + let sqlite = std::env::split_paths(&std::env::var_os("SQLITE_JDBC_CLASSPATH").expect("SQLITE_JDBC_CLASSPATH")) + .map(|p| p.display().to_string()) + .collect(); + let h2 = vec![std::env::var("H2_JDBC_JAR").expect("H2_JDBC_JAR")]; + for (class_name, jars, url) in + [("org.sqlite.JDBC", sqlite, "jdbc:sqlite::memory:"), ("org.h2.Driver", h2, "jdbc:h2:mem:;DB_CLOSE_DELAY=-1")] + { + let tmp = tempfile::tempdir()?; + let db = manager(tmp.path()); + db.save_jdbc_driver(DbJdbcDriver { + id: "private".into(), + class_name: class_name.into(), + name: class_name.into(), + vendor: None, + jars, + url_template: String::new(), + })?; + db.save_sources(vec![DataSource { + id: "test".into(), + name: "Anonymous memory".into(), + driver: DbDriver::Jdbc, + global: true, + jdbc_driver: "private".into(), + url: url.into(), + ..Default::default() + }]) + .await?; + let cancel = CancellationToken::new(); + let a = ConsoleId::new("window", "/a.sql"); + let b = ConsoleId::new("window", "/b.sql"); + let run = |console, sql: &'static str| db.execute_in_console("test", sql, 0, 1, &cancel, None, Some(console)); + db.execute("test", "CREATE TABLE preserved (id INTEGER)", 1, &cancel).await?; + run(a, "INSERT INTO preserved VALUES (1)").await?; + db.release_target_console(a, Some("test")).await?; + assert_eq!(run(b, "SELECT id FROM preserved").await?.rows, [vec![Some("1".into())]]); + db.disconnect("test").await; + } + Ok(()) +} + #[tokio::test] #[ignore = "requires CLICKHOUSE_JDBC_CLASSPATH and a loopback ClickHouse fixture on CLICKHOUSE_JDBC_TEST_PORT"] async fn clickhouse_vendor_driver_reads_catalog_and_results() -> IdeResult<()> { @@ -363,6 +448,72 @@ async fn unresponsive_driver_closes_before_reconnect() -> IdeResult<()> { Ok(()) } +#[tokio::test] +#[ignore = "requires JDBC_FIXTURE_JAR (java/jdbc-bridge/build.py --test --out fixture.jar) and Java 17+"] +async fn unresponsive_console_cancellation_keeps_other_jdbc_connections() -> IdeResult<()> { + use std::time::Duration; + let tmp = tempfile::tempdir()?; + let db = manager(tmp.path()); + let started = tmp.path().join("started"); + db.save_jdbc_driver(DbJdbcDriver { + id: "fixture".into(), + name: "Fixture".into(), + vendor: None, + jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()], + class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(), + url_template: String::new(), + })?; + db.save_sources(vec![DataSource { + id: "test".into(), + name: "Fixture".into(), + driver: DbDriver::Jdbc, + global: true, + jdbc_driver: "fixture".into(), + url: format!("jdbc:fixture:{}", started.display()), + ..Default::default() + }]) + .await?; + let a = ConsoleId::new("window", "/a.sql"); + let b = ConsoleId::new("window", "/b.sql"); + let stop = CancellationToken::new(); + let normal = CancellationToken::new(); + let (ran_a, sibling) = tokio::time::timeout(Duration::from_secs(15), async { + tokio::join!(db.execute_in_console("test", "ignore cancel", 0, 1, &stop, None, Some(a)), async { + while !started.is_file() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + let sibling = tokio::time::timeout(Duration::from_secs(2), async { + let b = db.execute_in_console("test", "from B", 0, 1, &normal, None, Some(b)).await?; + let service = db.execute("test", "service", 1, &normal).await?; + Ok::<_, ide_core::IdeError>((b.affected, service.affected)) + }) + .await; + stop.cancel(); + sibling + }) + }) + .await + .expect("cancellation must remain bounded"); + assert_eq!(sibling.expect("B and service can finish while A is executing")?, (Some(1.0), Some(1.0))); + assert!(ran_a.unwrap_err().message.contains("Cancellation timed out")); + assert_eq!(db.connected(), ["test"]); + // The fixture's update count is cumulative within a physical connection. + assert_eq!(db.execute_in_console("test", "still B", 0, 1, &normal, None, Some(b)).await?.affected, Some(2.0)); + assert_eq!(db.execute_in_console("test", "new session A", 0, 1, &normal, None, Some(a)).await?.affected, Some(1.0)); + assert!(db.execute("test", "drop", 1, &normal).await.unwrap_err().message.contains("connection reset")); + assert!(db.is_connected("test"), "a lost service connection must not retire the console sessions"); + assert_eq!( + db.execute_in_console("test", "B after service failure", 0, 1, &normal, None, Some(b)).await?.affected, + Some(3.0) + ); + db.release_target_console(a, Some("test")).await?; + db.release_target_console(b, Some("test")).await?; + assert!(!db.is_connected("test"), "the failed service pool can be re-established after the last console"); + assert_eq!(db.execute("test", "new service session", 1, &normal).await?.affected, Some(1.0)); + db.disconnect("test").await; + Ok(()) +} + #[tokio::test] #[ignore = "requires JDBC_FIXTURE_JAR (java/jdbc-bridge/build.py --test --out fixture.jar) and Java 17+"] async fn a_lost_session_reconnects_on_the_next_statement() -> IdeResult<()> { diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index 9ff86a706..4bbf32e26 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1639,7 +1639,7 @@ pub fn jdbc_bridge_jar(data_dir: &Path) -> Option { install_bundle( data_dir, "jdbc-bridge", - "1.0.0", + "2.0.0", include_bytes!("../../../java/jdbc-bridge/openidea-jdbc-bridge.jar"), ) } diff --git a/docs/en/guide/database.mdx b/docs/en/guide/database.mdx index 2a8481011..b40181002 100644 --- a/docs/en/guide/database.mdx +++ b/docs/en/guide/database.mdx @@ -40,6 +40,10 @@ When switching to JDBC, configure TLS and driver-specific settings in the JDBC U Select the profile, enter the vendor's JDBC URL, and use the **User**, **Password**, and **Advanced** fields for credentials and driver properties. The URL and Advanced properties are stored in the data source configuration. Put credentials in the password field to use the existing OS credential store. On Linux, saving a password requires a running Secret Service. You can also enter the password for the current session. The **Read-only** option asks the JDBC driver for a read-only connection. Use a database account with read-only privileges to enforce it. Cancelling a query keeps the session and its temporary tables when the driver stops the statement. If the driver does not respond within three seconds, OpenIDEA closes the session. A submitted statement can still finish on the server. **Test Connection** reports the database product and version. Schema, table and column browsing use JDBC metadata; the SQL console supports auto-commit queries and updates. Vendor-specific DDL, execution plans and table-grid writes are unavailable for custom drivers. +Each SQL console uses its own JDBC connection. Use the same console for statements that need its temporary tables or session settings. Other consoles can run queries while it is busy. OpenIDEA keeps the connection until you close the console and its result tabs. + +DuckDB consoles share the same database, including an in-memory database. Anonymous SQLite and H2 databases belong to one connection, so their consoles share that connection. For independent consoles on the same in-memory database, use a named URL such as `jdbc:sqlite:file:work?mode=memory&cache=shared` or `jdbc:h2:mem:work`. + For a file-backed database, use an absolute path to choose its location. Relative paths start in the persistent `jdbc/files` folder inside OpenIDEA’s application data directory. Profiles are reused across projects. If a project file changes a connection's URL or properties outside the IDE, review the settings in the data source dialog and save them before reconnecting. diff --git a/docs/zh/guide/database.mdx b/docs/zh/guide/database.mdx index d034f0f93..6361917db 100644 --- a/docs/zh/guide/database.mdx +++ b/docs/zh/guide/database.mdx @@ -40,6 +40,10 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行 选择驱动配置,填写厂商的 JDBC URL,在 **用户**、**密码** 和 **高级** 中设置凭据和驱动属性。通过密码字段输入的密码可以保存到系统凭据库。在 Linux 上,保存密码需要正在运行的 Secret Service;也可以仅为当前会话输入密码。**测试连接** 显示数据库产品和版本。可以通过 JDBC 元数据浏览模式、表和列,在 SQL 控制台中查询或以自动提交方式更新数据。自定义驱动不支持厂商特有的 DDL、执行计划或表格编辑。 +每个 SQL 控制台使用独立的 JDBC 连接。依赖临时表或会话设置的语句应在同一控制台中执行,其他控制台可以同时运行查询。关闭控制台及其结果标签页后,OpenIDEA 会释放连接。 + +DuckDB 的各个控制台共享同一个数据库,包括内存数据库。SQLite 和 H2 的匿名数据库仅属于一个连接,因此其控制台会共用该连接。如需让多个控制台通过独立连接访问同一个内存数据库,可使用命名 URL,例如 `jdbc:sqlite:file:work?mode=memory&cache=shared` 或 `jdbc:h2:mem:work`。 + 文件数据库可使用绝对路径指定存储位置。相对路径以 OpenIDEA 应用数据目录下的持久化 `jdbc/files` 文件夹为起点。 驱动配置可以跨项目复用。在 IDE 外更改项目数据源的 URL 或连接属性后,需要在数据源对话框中检查并保存设置,才能重新连接。 diff --git a/java/jdbc-bridge/build.py b/java/jdbc-bridge/build.py index 8b3e5f5ab..d12cfb6db 100644 --- a/java/jdbc-bridge/build.py +++ b/java/jdbc-bridge/build.py @@ -10,7 +10,10 @@ root = Path(__file__).resolve().parent parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--test", action="store_true") parser.add_argument("--out", type=Path, help="output JAR (with --test: the fixture driver for JDBC_FIXTURE_JAR)") +parser.add_argument("--duckdb-jar", type=Path, help="run the real DuckDB pipe tests with this existing JDBC jar") args = parser.parse_args() +if args.duckdb_jar and not args.test: + parser.error("--duckdb-jar requires --test") java_home = os.environ.get("JAVA_HOME") def tool(name): return str(Path(java_home) / "bin" / name) if java_home else name @@ -25,6 +28,10 @@ with tempfile.TemporaryDirectory() as scratch: "-d", classes, *sources], check=True) if args.test: subprocess.run([tool("java"), "-ea", "-cp", classes, "ai.openidea.jdbc.SelfTest"], check=True, timeout=45) + if args.duckdb_jar: + classpath = os.pathsep.join((str(classes), str(args.duckdb_jar.resolve(strict=True)))) + subprocess.run([tool("java"), "-ea", "-cp", classpath, "ai.openidea.jdbc.DuckDbSelfTest"], + check=True, timeout=45) if not args.test or args.out: with zipfile.ZipFile(args.out or root / "openidea-jdbc-bridge.jar", "w") as jar: for path in sorted(classes.rglob("SelfTest*.class" if args.test else "*.class")): diff --git a/java/jdbc-bridge/openidea-jdbc-bridge.jar b/java/jdbc-bridge/openidea-jdbc-bridge.jar index 93e505356..78a8deb97 100644 Binary files a/java/jdbc-bridge/openidea-jdbc-bridge.jar and b/java/jdbc-bridge/openidea-jdbc-bridge.jar differ diff --git a/java/jdbc-bridge/src/ai/openidea/jdbc/MultiplexBridge.java b/java/jdbc-bridge/src/ai/openidea/jdbc/MultiplexBridge.java new file mode 100644 index 000000000..3195a503c --- /dev/null +++ b/java/jdbc-bridge/src/ai/openidea/jdbc/MultiplexBridge.java @@ -0,0 +1,225 @@ +package ai.openidea.jdbc; + +import java.io.*; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.Set; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Opt-in framing: request ID, connection ID and field count, then the legacy fields. + * Replies carry the request ID before the legacy length and payload. Zero fields + * requests cancellation, and a reply with zero length acknowledges it. + */ +final class MultiplexBridge { + private static final int SERVICE = 0; + // The service/shared session and closing drivers occupy slots as well. + private static final int MAX_CONNECTIONS = 32; + private static final int REQUEST_HEADER = Long.BYTES + 2 * Integer.BYTES; + private static final long CLOSE_GRACE = TimeUnit.MILLISECONDS.toNanos(1500); + + private final DataInputStream input; + private final DataOutputStream output; + private final ConcurrentMap sessions = new ConcurrentHashMap<>(); + // Closing drivers still count towards the cap until their Connection.close returns. + private final Set live = ConcurrentHashMap.newKeySet(); + // Reserve before large writes and encodings, not while JDBC executes. This keeps + // frame copies and encoding temporaries within the 192 MiB JVM's headroom. + private final Semaphore largeReplies = new Semaphore(1, true); + private volatile List settings; + private final AtomicBoolean stopping = new AtomicBoolean(); + + MultiplexBridge(DataInputStream input, DataOutputStream output) { + this.input = input; + this.output = output; + } + + private static ThreadFactory daemon(String name) { + return action -> { + var thread = new Thread(action, name); + thread.setDaemon(true); + return thread; + }; + } + + private static final class Session { + final int id; + final OpenIdeaJdbc jdbc = new OpenIdeaJdbc(); + final AtomicReference active = new AtomicReference<>(); + final ExecutorService worker = Executors.newSingleThreadExecutor(daemon("jdbc-session")); + // A driver may hold Statement.cancel indefinitely. Keep it off the reader and + // confine the outstanding calls to this connection. + final ExecutorService canceller = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, + new ArrayBlockingQueue<>(1), daemon("jdbc-cancel"), new ThreadPoolExecutor.DiscardPolicy()); + + Session(int id) { this.id = id; } + + void cancel(OpenIdeaJdbc.Work work) { + var statement = work.requestCancel(); + if (statement != null) canceller.execute(() -> OpenIdeaJdbc.Work.cancelStatement(statement)); + } + } + + private void send(long id, ByteArrayOutputStream payload) throws IOException { + synchronized (output) { + if (stopping.get()) return; + output.writeLong(id); + OpenIdeaJdbc.send(output, payload); + } + } + + private static ByteArrayOutputStream status(String error) throws IOException { + var bytes = new ByteArrayOutputStream(); + var result = new DataOutputStream(bytes); + result.writeBoolean(error == null); + if (error == null) { + OpenIdeaJdbc.header(result); + OpenIdeaJdbc.end(result, false, -1); + } else { + OpenIdeaJdbc.text(result, error); + } + return bytes; + } + + private void retire(Session session) { + if (session == null || !sessions.remove(session.id, session)) return; + var work = session.active.get(); + if (work != null) session.cancel(work); + session.worker.execute(() -> { + try { session.jdbc.close(); } + catch (SQLException | RuntimeException ignored) {} + finally { live.remove(session); } + }); + session.worker.shutdown(); + session.canceller.shutdown(); + } + + private Connection connect(List options) throws Exception { + if (!options.get(0).equals("org.duckdb.DuckDBDriver")) return OpenIdeaJdbc.connect(options); + // A second DuckDB login would create a different unnamed in-memory database. + // Call duplicate on the service worker so it never races another operation + // on the same JDBC Connection. + Session service = sessions.get(SERVICE); + if (service == null) throw new SQLException("The DuckDB service connection is unavailable"); + return service.worker.submit(() -> { + Connection source = service.jdbc.connection; + return (Connection) source.getClass().getMethod("duplicate").invoke(source); + }).get(); + } + + private synchronized void request(long id, int connection, List fields) throws IOException { + if (stopping.get()) return; + String op = fields.get(0); + Session session = sessions.get(connection); + if (op.equals("close")) { + if (connection == SERVICE || fields.size() != 1) { + send(id, status("Invalid JDBC console close request")); + } else { + retire(session); // Retire the ID before acknowledging, even if the driver is busy. + send(id, status(null)); + } + return; + } + + boolean open = op.equals("open"); + List options = settings; + if (open) { + boolean valid = connection == SERVICE + ? fields.size() >= 6 && fields.size() % 2 == 0 + : fields.size() == 1 && options != null; + if (!valid || session != null) { + send(id, status("Invalid JDBC connection open request")); + return; + } + if (live.size() >= MAX_CONNECTIONS) { + send(id, status("JDBC connection limit reached. Close a console or wait for its connection to finish closing, then try again.")); + return; + } + if (connection == SERVICE) options = List.copyOf(fields.subList(1, fields.size())); + session = new Session(connection); + sessions.put(connection, session); + live.add(session); + } else if (session == null) { + send(id, status("JDBC connection is closed")); + return; + } + + var work = new OpenIdeaJdbc.Work(id); + if (!session.active.compareAndSet(null, work)) { + send(id, status("The JDBC connection is already executing a request")); + return; + } + try { + schedule(session, work, fields, open, options); + } catch (RejectedExecutionException closed) { + session.active.compareAndSet(work, null); + send(id, status("JDBC connection is closed")); + } + } + + private void schedule(Session session, OpenIdeaJdbc.Work work, List fields, + boolean open, List options) { + session.worker.execute(() -> { + try (var buffer = new ReplyBuffer(largeReplies)) { + var answer = session.jdbc.reply(work, fields, + args -> session.id == SERVICE ? OpenIdeaJdbc.connect(args) : connect(options), buffer); + if (open) { + if (session.jdbc.connection == null) retire(session); + else if (session.id == SERVICE) settings = options; + } + session.active.compareAndSet(work, null); + send(work.id, answer); + } catch (Throwable fatal) { + abort(); + } + }); + } + + private void abort() { + if (!stopping.compareAndSet(false, true)) return; + // The reader may be blocked on stdin and the worker cannot join itself. + var closer = new Thread(() -> { + try { closeSessions(); } + finally { Runtime.getRuntime().halt(1); } + }, "jdbc-broken-pipe"); + closer.setDaemon(false); + closer.start(); + } + + private void closeSessions() { + List remaining; + synchronized (this) { remaining = List.copyOf(live); } + for (Session session : remaining) retire(session); + long deadline = System.nanoTime() + CLOSE_GRACE; + for (Session session : remaining) { + long wait = deadline - System.nanoTime(); + if (wait <= 0) break; + try { session.worker.awaitTermination(wait, TimeUnit.NANOSECONDS); } + catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } + } + } + + void run() throws IOException { + try { + while (!stopping.get()) { + long id; + try { id = input.readLong(); } catch (EOFException eof) { return; } + int connection = input.readInt(); + int count = input.readInt(); + if (count == 0) { + Session session = sessions.get(connection); + var work = session == null ? null : session.active.get(); + if (work != null && work.id == id) session.cancel(work); + send(id, null); + } else { + request(id, connection, OpenIdeaJdbc.readFields(input, count, REQUEST_HEADER)); + } + } + } finally { + if (stopping.compareAndSet(false, true)) closeSessions(); + } + } +} diff --git a/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java b/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java index 889db01be..0836e9932 100644 --- a/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java +++ b/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java @@ -11,8 +11,6 @@ import java.util.concurrent.atomic.AtomicReference; public final class OpenIdeaJdbc { static final int LIMIT = 16 * 1024 * 1024; - final DataInputStream input = new DataInputStream(new BufferedInputStream(System.in)); - final DataOutputStream output = new DataOutputStream(new BufferedOutputStream(System.out)); Connection connection; boolean catalogs; boolean namespaceKnown; @@ -23,6 +21,7 @@ public final class OpenIdeaJdbc { if (available < 0 || (value != null && value.length() > available)) throw new IOException("JDBC result exceeds 16 MiB; select fewer or smaller values"); if (value == null) { out.writeInt(-1); return; } + ReplyBuffer.beforeEncoding(out, Integer.BYTES + 3 * value.length()); byte[] data = value.getBytes(StandardCharsets.UTF_8); if (data.length > available) throw new IOException("JDBC result exceeds 16 MiB; select fewer or smaller values"); out.writeInt(data.length); @@ -61,7 +60,7 @@ public final class OpenIdeaJdbc { } } - void open(List a, DataOutputStream out) throws Exception { + static Connection connect(List a) throws Exception { String className = a.get(0), url = a.get(1); Driver driver = Class.forName(className).asSubclass(Driver.class).getConstructor().newInstance(); var props = new Properties(); @@ -80,6 +79,7 @@ public final class OpenIdeaJdbc { } props.setProperty("duckdb.read_only", "true"); } + Connection connection; try { connection = driver.connect(url, props); } catch (SQLException e) { if (!duckDbReadOnly) throw e; @@ -89,12 +89,33 @@ public final class OpenIdeaJdbc { if (readOnly && !duckDbReadOnly) { try { connection.setReadOnly(true); } catch (SQLException | UnsupportedOperationException e) { + try { connection.close(); } catch (SQLException ignored) {} throw new ReadOnlyUnavailable("The JDBC driver rejected Read-only. Check the driver settings and database account privileges."); } } - var m = connection.getMetaData(); - header(out, "version", "quote"); - row(out, m.getDatabaseProductName() + " " + m.getDatabaseProductVersion(), m.getIdentifierQuoteString()); + return connection; + } + + @FunctionalInterface + interface OpenConnection { + Connection open(List args) throws Exception; + } + + private void open(List args, DataOutputStream out, OpenConnection opener) throws Exception { + Connection opened = opener.open(args); + try { + var m = opened.getMetaData(); + header(out, "version", "quote"); + row(out, m.getDatabaseProductName() + " " + m.getDatabaseProductVersion(), m.getIdentifierQuoteString()); + connection = opened; + } catch (Exception | LinkageError failure) { + try { opened.close(); } catch (SQLException ignored) {} + throw failure; + } + } + + void close() throws SQLException { + if (connection != null) connection.close(); } static String pattern(DatabaseMetaData m, String literal) throws SQLException { @@ -210,6 +231,7 @@ public final class OpenIdeaJdbc { if (t == Types.BINARY || t == Types.VARBINARY || t == Types.LONGVARBINARY || t == Types.BLOB) { byte[] b = rs.getBytes(c); if (b != null && b.length > (LIMIT - out.size()) / 2) throw new IOException("JDBC binary value exceeds the result limit"); + if (b != null) ReplyBuffer.beforeEncoding(out, Integer.BYTES + 2 + 2 * b.length); text(out, b == null ? null : "0x" + HexFormat.of().formatHex(b)); } else { text(out, rs.getString(c)); @@ -241,15 +263,25 @@ public final class OpenIdeaJdbc { cancelled = true; st = statement; } + cancelStatement(st); + } + + synchronized Statement requestCancel() { + if (cancelled) return null; + cancelled = true; + return statement; + } + + static void cancelStatement(Statement st) { if (st != null) { try { st.cancel(); } catch (SQLException | UnsupportedOperationException ignored) {} } } } - static List readFields(DataInputStream in, int count) throws IOException { + static List readFields(DataInputStream in, int count, int headerBytes) throws IOException { if (count < 1 || count > 8192) throw new IOException("Invalid JDBC field count"); - int remaining = LIMIT - Long.BYTES - Integer.BYTES; + int remaining = LIMIT - headerBytes; var fields = new ArrayList(count); for (int i = 0; i < count; i++) { remaining -= Integer.BYTES; @@ -263,14 +295,18 @@ public final class OpenIdeaJdbc { return fields; } - ByteArrayOutputStream reply(Work work, List a) throws IOException { - var buffer = new ByteArrayOutputStream(); - var reply = new DataOutputStream(buffer); + ByteArrayOutputStream reply(Work work, List a, OpenConnection opener) throws IOException { + return reply(work, a, opener, new ByteArrayOutputStream()); + } + + ByteArrayOutputStream reply(Work work, List a, OpenConnection opener, + ByteArrayOutputStream buffer) throws IOException { + var reply = ReplyBuffer.writer(buffer); String op = a.remove(0); try { reply.writeBoolean(true); switch (op) { - case "open" -> open(a, reply); + case "open" -> open(a, reply, opener); case "schemas" -> schemas(reply); case "tables", "columns", "schemaColumns" -> metadata(op, a, reply); case "namespace" -> { @@ -327,8 +363,9 @@ public final class OpenIdeaJdbc { } if (!op.equals("query") && !op.equals("page")) end(reply, false, -1); } catch (Exception | LinkageError e) { - buffer = new ByteArrayOutputStream(); - reply = new DataOutputStream(buffer); + if (buffer instanceof ReplyBuffer bounded) bounded.reset(); + else buffer = new ByteArrayOutputStream(); + reply = ReplyBuffer.writer(buffer); reply.writeBoolean(false); if ((e instanceof ClassNotFoundException || e instanceof NoClassDefFoundError) && e.getMessage() != null && e.getMessage().matches("[A-Za-z0-9_.$/]+")) { @@ -349,14 +386,15 @@ public final class OpenIdeaJdbc { return buffer; } - synchronized void send(ByteArrayOutputStream reply) throws IOException { - output.writeInt(reply == null ? 0 : reply.size()); - if (reply != null) reply.writeTo(output); - output.flush(); + static void send(DataOutputStream output, ByteArrayOutputStream reply) throws IOException { + synchronized (output) { + output.writeInt(reply == null ? 0 : reply.size()); + if (reply != null) reply.writeTo(output); + output.flush(); + } } - void run() throws IOException { - System.setOut(System.err); + void run(DataInputStream input, DataOutputStream output) throws IOException { var active = new AtomicReference(); var worker = Executors.newSingleThreadExecutor(r -> { var thread = new Thread(r, "jdbc-session"); @@ -371,17 +409,17 @@ public final class OpenIdeaJdbc { if (count == 0) { var work = active.get(); if (work != null && work.id == id) work.cancel(); - send(null); // Acknowledge even a cancel that raced with a completed request. + send(output, null); // Acknowledge even a cancel that raced with a completed request. continue; } - var fields = readFields(input, count); + var fields = readFields(input, count, Long.BYTES + Integer.BYTES); var work = new Work(id); if (!active.compareAndSet(null, work)) throw new IOException("Overlapping JDBC requests"); worker.execute(() -> { try { - var result = reply(work, fields); + var result = reply(work, fields, OpenIdeaJdbc::connect); active.compareAndSet(work, null); - send(result); + send(output, result); } catch (Throwable fatal) { // Without a complete frame the parent must discard this session. Runtime.getRuntime().halt(1); @@ -394,8 +432,19 @@ public final class OpenIdeaJdbc { } public static void main(String[] args) throws Exception { + var input = new DataInputStream(new BufferedInputStream(System.in)); + boolean multiplex = args.length == 1 && args[0].equals("--multiplex"); + // PrintStream swallows broken pipe errors. The multiplexed writer needs + // the failure so it can close all peers and terminate the transport. + OutputStream wire = multiplex ? new FileOutputStream(FileDescriptor.out) : System.out; + var output = new DataOutputStream(new BufferedOutputStream(wire)); + System.setOut(System.err); + if (multiplex) { + new MultiplexBridge(input, output).run(); + return; + } var bridge = new OpenIdeaJdbc(); - try { bridge.run(); } - finally { if (bridge.connection != null) bridge.connection.close(); } + try { bridge.run(input, output); } + finally { bridge.close(); } } } diff --git a/java/jdbc-bridge/src/ai/openidea/jdbc/ReplyBuffer.java b/java/jdbc-bridge/src/ai/openidea/jdbc/ReplyBuffer.java new file mode 100644 index 000000000..937e8c796 --- /dev/null +++ b/java/jdbc-bridge/src/ai/openidea/jdbc/ReplyBuffer.java @@ -0,0 +1,83 @@ +package ai.openidea.jdbc; + +import java.io.*; +import java.util.Arrays; +import java.util.Objects; +import java.util.concurrent.Semaphore; + +/** Small replies have their own bounded buffer. Only one large reply is encoded at a time. */ +final class ReplyBuffer extends ByteArrayOutputStream { + private static final int SMALL = 64 * 1024; + private static final String BUDGET_ERROR = + "JDBC result exceeds the concurrent reply budget. Select fewer or smaller values."; + private final Semaphore budget; + private boolean reserved; + + ReplyBuffer(Semaphore budget) { this.budget = budget; } + + private static final class Writer extends DataOutputStream { + final ReplyBuffer buffer; + Writer(ReplyBuffer buffer) { + super(buffer); + this.buffer = buffer; + } + } + + static DataOutputStream writer(ByteArrayOutputStream buffer) { + return buffer instanceof ReplyBuffer bounded ? new Writer(bounded) : new DataOutputStream(buffer); + } + + static void beforeEncoding(DataOutputStream output, int bound) { + if (output instanceof Writer writer) { + // A field this size may already own a large value from the driver. Do not + // retain it while waiting behind another large frame. + writer.buffer.reserve((long) writer.buffer.count + bound, bound <= SMALL); + } + } + + private void reserve(long size, boolean wait) { + if (reserved || size <= SMALL) return; + try { + if (wait) budget.acquire(); + else if (!budget.tryAcquire()) throw new UncheckedIOException(new IOException(BUDGET_ERROR)); + reserved = true; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new UncheckedIOException(new IOException("JDBC reply interrupted", e)); + } + } + + private void grow(int extra) { + if (extra > OpenIdeaJdbc.LIMIT - count) + throw new UncheckedIOException(new IOException("JDBC result exceeds 16 MiB")); + int needed = count + extra; + reserve(needed, true); + if (needed > buf.length) { + int limit = reserved ? OpenIdeaJdbc.LIMIT : SMALL; + buf = Arrays.copyOf(buf, Math.min(limit, Math.max(needed, buf.length * 2))); + } + } + + @Override public synchronized void write(int value) { + grow(1); + buf[count++] = (byte) value; + } + + @Override public synchronized void write(byte[] data, int offset, int size) { + Objects.checkFromIndexSize(offset, size, data.length); + grow(size); + System.arraycopy(data, offset, buf, count, size); + count += size; + } + + @Override public synchronized void reset() { + super.reset(); + if (reserved) { + buf = new byte[32]; + reserved = false; + budget.release(); + } + } + + @Override public void close() { reset(); } +} diff --git a/java/jdbc-bridge/tests/DuckDbSelfTest.java b/java/jdbc-bridge/tests/DuckDbSelfTest.java new file mode 100644 index 000000000..393de8300 --- /dev/null +++ b/java/jdbc-bridge/tests/DuckDbSelfTest.java @@ -0,0 +1,118 @@ +package ai.openidea.jdbc; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.concurrent.TimeUnit; + +/** Exercises the production frames with a supplied DuckDB JDBC distribution. */ +public final class DuckDbSelfTest { + private static final class Bridge implements AutoCloseable { + private final Process child; + private final DataInputStream in; + private final DataOutputStream out; + private long id = 1; + + Bridge(String java) throws IOException { + child = SelfTest.start(java, true); + in = new DataInputStream(child.getInputStream()); + out = new DataOutputStream(child.getOutputStream()); + } + + SelfTest.Tagged request(int connection, int status, String... fields) throws IOException { + long current = id++; + SelfTest.sendOn(out, current, connection, fields); + return SelfTest.expect(in, current, status); + } + + void open(String url) throws IOException { + request(0, 1, "open", "org.duckdb.DuckDBDriver", url, "", "", "false"); + } + + void execute(int connection, String sql) throws IOException { + request(connection, 1, "query", sql, "0", "2"); + } + + String value(int connection, String sql) throws IOException { + var message = request(connection, 1, "query", sql, "0", "2"); + try (var value = new DataInputStream(new ByteArrayInputStream(message.data()))) { + assert value.readBoolean(); + assert value.readInt() == 1; + text(value); // Column label. + text(value); // JDBC type. + assert value.readBoolean(); + return text(value); + } + } + + @Override public void close() throws Exception { + try { + out.close(); + if (!child.waitFor(5, TimeUnit.SECONDS)) + throw new AssertionError("JDBC process did not close its connections on EOF"); + assert child.exitValue() == 0 : new String(child.getErrorStream().readAllBytes(), StandardCharsets.UTF_8); + } finally { + if (child.isAlive()) child.destroyForcibly().waitFor(); + in.close(); + } + } + } + + private static String text(DataInputStream in) throws IOException { + int size = in.readInt(); + return size == -1 ? null : new String(in.readNBytes(size), StandardCharsets.UTF_8); + } + + public static void main(String[] args) throws Exception { + var java = Path.of(System.getProperty("java.home"), "bin", "java").toString(); + try (var bridge = new Bridge(java)) { + bridge.open("jdbc:duckdb:"); + bridge.request(1, 1, "open"); + bridge.request(2, 1, "open"); + bridge.execute(1, "CREATE TABLE durable(i INTEGER)"); + bridge.execute(1, "INSERT INTO durable VALUES (41)"); + assert bridge.value(2, "SELECT i FROM durable").equals("41"); + bridge.execute(1, "CREATE TEMP TABLE private_table(i INTEGER)"); + bridge.execute(1, "INSERT INTO private_table VALUES (7)"); + assert bridge.value(1, "SELECT i FROM private_table").equals("7"); + bridge.request(2, 0, "query", "SELECT i FROM private_table", "0", "2"); + + bridge.execute(1, "ATTACH ':memory:' AS attached_catalog"); + bridge.execute(1, "USE attached_catalog"); + assert bridge.value(1, "SELECT current_database()").equals("attached_catalog"); + assert !bridge.value(2, "SELECT current_database()").equals("attached_catalog"); + bridge.execute(1, "CREATE TABLE shared_catalog(i INTEGER)"); + bridge.execute(1, "INSERT INTO shared_catalog VALUES (9)"); + assert bridge.value(2, "SELECT i FROM attached_catalog.main.shared_catalog").equals("9"); + + bridge.request(1, 1, "close"); + assert bridge.value(2, "SELECT i FROM durable").equals("41"); + bridge.request(3, 1, "open"); + assert bridge.value(3, "SELECT i FROM attached_catalog.main.shared_catalog").equals("9"); + } + + var fixture = Files.createTempDirectory("openidea-jdbc-duckdb-"); + var url = "jdbc:duckdb:" + fixture.resolve("fixture.duckdb"); + try { + try (var bridge = new Bridge(java)) { + bridge.open(url); + bridge.request(1, 1, "open"); + bridge.request(2, 1, "open"); + bridge.execute(1, "CREATE TABLE durable(i INTEGER)"); + bridge.execute(1, "INSERT INTO durable VALUES (42)"); + assert bridge.value(2, "SELECT i FROM durable").equals("42"); + bridge.request(1, 1, "close"); + } + try (var reopened = new Bridge(java)) { + reopened.open(url); + assert reopened.value(0, "SELECT i FROM durable").equals("42"); + } + } finally { + try (var paths = Files.walk(fixture)) { + for (var path : paths.sorted(Comparator.reverseOrder()).toList()) Files.delete(path); + } + } + } +} diff --git a/java/jdbc-bridge/tests/SelfTest.java b/java/jdbc-bridge/tests/SelfTest.java index 924483bb8..1b31979f7 100644 --- a/java/jdbc-bridge/tests/SelfTest.java +++ b/java/jdbc-bridge/tests/SelfTest.java @@ -3,16 +3,21 @@ package ai.openidea.jdbc; import java.io.*; import java.lang.reflect.Proxy; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.sql.*; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; /** Drives the bridge over its actual pipes with a deterministic JDBC driver. */ public class SelfTest { public static class Fixture implements Driver { + private static final CountDownLatch releaseCancellation = new CountDownLatch(1); + private static final String LARGE_CELL = "x".repeat(16 * 1024); private boolean readonly; private boolean dropped; private int changes; @@ -42,8 +47,11 @@ public class SelfTest { }); return proxy(Connection.class, (p, m, a) -> switch (m.getName()) { case "setReadOnly" -> { readonly = (boolean) a[0]; yield null; } - case "getMetaData" -> meta; - case "close" -> null; + case "getMetaData" -> { + if (path.equals("fail-metadata")) throw new SQLException("private bootstrap detail"); + yield meta; + } + case "close" -> { System.err.println("connection closed"); yield null; } case "createStatement" -> statement(); case "isClosed" -> false; case "isValid" -> !dropped; @@ -64,12 +72,43 @@ public class SelfTest { }); } + static ResultSet largeRows(boolean fail) { + int[] rows = {0}; + var metadata = proxy(ResultSetMetaData.class, (p, m, a) -> switch (m.getName()) { + case "getColumnCount" -> 1; + case "getColumnLabel" -> "payload"; + case "getColumnTypeName" -> "VARCHAR"; + case "getColumnType" -> Types.VARCHAR; + default -> throw new SQLFeatureNotSupportedException(); + }); + return proxy(ResultSet.class, (p, m, a) -> switch (m.getName()) { + case "next" -> { + if (++rows[0] == 6 && fail) throw new SQLException("large result failed while reading"); + yield rows[0] <= 990; + } + case "getMetaData" -> metadata; + case "getString" -> LARGE_CELL; + case "close" -> null; + default -> throw new SQLFeatureNotSupportedException(); + }); + } + Statement statement() { var stop = new CountDownLatch(1); + var slowCancel = new AtomicBoolean(); + boolean[] failLargeRows = {false}; return proxy(Statement.class, (p, m, a) -> switch (m.getName()) { case "execute" -> { String sql = (String) a[0]; - if (sql.equals("wait") || sql.equals("ignore cancel")) { + if (sql.equals("large rows") || sql.equals("large error")) { + failLargeRows[0] = sql.equals("large error"); + System.err.println("large query started"); + yield true; + } + if (sql.equals("write marker")) Files.writeString(started, "once\n", StandardOpenOption.APPEND); + if (sql.equals("release cancel gate")) releaseCancellation.countDown(); + if (sql.equals("wait for cancel gate")) slowCancel.set(true); + if (sql.equals("wait") || sql.equals("ignore cancel") || slowCancel.get()) { if (started != null) java.nio.file.Files.writeString(started, "started"); System.err.println("statement started"); if (sql.equals("ignore cancel")) Thread.sleep(60_000); @@ -81,7 +120,16 @@ public class SelfTest { changes++; yield false; } - case "cancel" -> { stop.countDown(); yield null; } + case "cancel" -> { + if (slowCancel.get()) { + System.err.println("cancel entered"); + if (!releaseCancellation.await(15, TimeUnit.SECONDS)) + throw new SQLException("cancel gate timed out"); + } + stop.countDown(); + yield null; + } + case "getResultSet" -> largeRows(failLargeRows[0]); case "getUpdateCount" -> changes; case "close" -> null; default -> throw new SQLFeatureNotSupportedException(); @@ -114,6 +162,236 @@ public class SelfTest { return bytes; } + static void sendOn(DataOutputStream out, long id, int connection, String... fields) throws IOException { + out.writeLong(id); + out.writeInt(connection); + out.writeInt(fields.length); + for (String field : fields) { + byte[] data = field.getBytes(StandardCharsets.UTF_8); + out.writeInt(data.length); + out.write(data); + } + out.flush(); + } + + record Tagged(long id, byte[] data) { + int status() { return data.length == 0 ? -1 : data[0]; } + } + + static Tagged tagged(DataInputStream in) throws IOException { + return new Tagged(in.readLong(), reply(in)); + } + + static Tagged expect(DataInputStream in, long id, int status) throws IOException { + var message = tagged(in); + assert message.id() == id && message.status() == status + : "Expected reply " + id + "/" + status + ", got " + message.id() + "/" + message.status(); + return message; + } + + static Process start(String java, boolean multiplex, String... jvmOptions) throws IOException { + var command = new ArrayList(); + command.add(java); + command.addAll(List.of(jvmOptions)); + command.addAll(List.of("--enable-native-access=ALL-UNNAMED", "-cp", System.getProperty("java.class.path"), + OpenIdeaJdbc.class.getName())); + if (multiplex) command.add("--multiplex"); + return new ProcessBuilder(command).start(); + } + + static void multiplex(String java) throws Exception { + var child = start(java, true); + try (var out = new DataOutputStream(child.getOutputStream()); + var in = new DataInputStream(child.getInputStream()); + var log = child.errorReader()) { + sendOn(out, 100, 0, "open", Fixture.class.getName(), "jdbc:fixture:", "", "", "false"); + try { + expect(in, 100, 1); + } catch (IOException e) { + throw new AssertionError("The bridge did not accept the multiplex bootstrap frame", e); + } + sendOn(out, 101, 1, "open"); + expect(in, 101, 1); + sendOn(out, 102, 2, "open"); + expect(in, 102, 1); + sendOn(out, 103, 1, "query", "wait for cancel gate", "0", "2"); + assert log.lines().anyMatch("statement started"::equals); + sendOn(out, 104, 1, "query", "overlap", "0", "2"); + expect(in, 104, 0); + + sendOn(out, 103, 2); // Wrong connection must not cancel the active request. + expect(in, 103, -1); + sendOn(out, 105, 2, "query", "independent console", "0", "2"); + expect(in, 105, 1); + sendOn(out, 103, 1); + expect(in, 103, -1); + assert log.lines().anyMatch("cancel entered"::equals); + sendOn(out, 106, 0, "schemaColumns", "app"); + expect(in, 106, 1); // The driver is still withholding the cancellation response. + sendOn(out, 107, 1, "close"); + expect(in, 107, 1); + sendOn(out, 108, 1, "query", "retired", "0", "2"); + expect(in, 108, 0); + sendOn(out, 109, 2, "query", "release cancel gate", "0", "2"); + var first = tagged(in); + var second = tagged(in); + var statuses = Map.of(first.id(), first.status(), second.id(), second.status()); + assert statuses.equals(Map.of(103L, 0, 109L, 1)) : statuses; + assert log.lines().anyMatch("connection closed"::equals); + + sendOn(out, 110, 2, "query", "after sibling close", "0", "2"); + expect(in, 110, 1); + sendOn(out, 111, 0, "valid"); + assert new String(expect(in, 111, 1).data(), StandardCharsets.UTF_8).contains("true"); + } finally { + child.destroyForcibly().waitFor(); + } + } + + static void capacity(String java) throws Exception { + var child = start(java, true); + try (var out = new DataOutputStream(child.getOutputStream()); + var in = new DataInputStream(child.getInputStream()); + var log = child.errorReader()) { + sendOn(out, 200, 0, "open", Fixture.class.getName(), "jdbc:fixture:fail-metadata", "", "", "false"); + var failure = new String(expect(in, 200, 0).data(), StandardCharsets.UTF_8); + assert failure.contains("JDBC connection failed") && !failure.contains("private bootstrap detail"); + assert log.lines().anyMatch("connection closed"::equals); + sendOn(out, 201, 0, "open", Fixture.class.getName(), "jdbc:fixture:", "", "", "false"); + expect(in, 201, 1); + + for (int i = 1; i <= 31; i++) { + sendOn(out, 201 + i, i, "open"); + expect(in, 201 + i, 1); + } + sendOn(out, 300, 32, "open"); + var full = new String(expect(in, 300, 0).data(), StandardCharsets.UTF_8); + assert full.contains("Close") && full.contains("try again") : full; + sendOn(out, 301, 31, "query", "survives admission failure", "0", "2"); + expect(in, 301, 1); + + sendOn(out, 302, 1, "close"); + expect(in, 302, 1); + sendOn(out, 303, 1, "query", "retired", "0", "2"); + expect(in, 303, 0); + assert log.lines().anyMatch("connection closed"::equals); + boolean reopened = false; + for (int attempt = 0; attempt < 20; attempt++) { + int id = 33 + attempt; + sendOn(out, 304 + attempt, id, "open"); + var response = tagged(in); + assert response.id() == 304 + attempt; + if (response.status() == 1) { + reopened = true; + break; + } + assert response.status() == 0; + Thread.sleep(5); + } + assert reopened : "A closed console did not release its connection slot"; + sendOn(out, 330, 0, "valid"); + expect(in, 330, 1); + } finally { + child.destroyForcibly().waitFor(); + } + } + + static void brokenStreams(String java) throws Exception { + var marker = Files.createTempFile("openidea-jdbc-write-", ".txt"); + try { + for (boolean breakOutput : new boolean[]{false, true}) { + Files.writeString(marker, ""); + var child = start(java, true); + try (var out = new DataOutputStream(child.getOutputStream()); + var in = new DataInputStream(child.getInputStream()); + var log = child.errorReader()) { + sendOn(out, 400, 0, "open", Fixture.class.getName(), "jdbc:fixture:" + marker, "", "", "false"); + expect(in, 400, 1); + sendOn(out, 401, 1, "open"); + expect(in, 401, 1); + if (breakOutput) in.close(); + sendOn(out, 402, 1, "query", "write marker", "0", "2"); + if (!breakOutput) { + expect(in, 402, 1); + out.writeLong(403); + out.writeInt(1); + out.writeInt(1); + out.writeInt(8); + out.writeByte(0); // A truncated field, not a clean EOF between frames. + out.close(); + } + assert child.waitFor(5, TimeUnit.SECONDS) : "Broken JDBC pipe did not terminate (stdout=" + breakOutput + ")"; + assert child.exitValue() != 0; + long closed = log.lines().filter("connection closed"::equals).count(); + assert closed == 2 : "Broken stdout=" + breakOutput + " closed " + closed + " connections"; + assert Files.readAllLines(marker).equals(List.of("once")) : "JDBC write was replayed"; + } finally { + child.destroyForcibly().waitFor(); + } + } + } finally { + Files.delete(marker); + } + } + + static void boundedReplies(String java) throws Exception { + var child = start(java, true, "-Xmx192m"); + try (var out = new DataOutputStream(child.getOutputStream()); + var in = new DataInputStream(child.getInputStream()); + var log = child.errorReader()) { + sendOn(out, 500, 0, "open", Fixture.class.getName(), "jdbc:fixture:", "", "", "false"); + expect(in, 500, 1); + int largeQueries = 16; + for (int i = 1; i <= largeQueries + 1; i++) { + sendOn(out, 500 + i, i, "open"); + expect(in, 500 + i, 1); + } + for (int i = 1; i <= largeQueries; i++) + sendOn(out, 600 + i, i, "query", "large rows", "0", "1000"); + for (int i = 0; i < largeQueries; i++) + assert log.lines().anyMatch("large query started"::equals); + sendOn(out, 700, largeQueries + 1, "query", "small reply", "0", "1"); + sendOn(out, 701, largeQueries + 1); // Stale cancel still produces its tagged acknowledgement. + // Back up stdout while the workers assemble their responses. The parent + // drains the payloads in place rather than retaining the test data. + Thread.sleep(300); + Set replies = new HashSet<>(); + int smallAt = -1, ackAt = -1; + for (int i = 0; i < largeQueries + 2; i++) { + long id = in.readLong(); + int length = in.readInt(); + assert replies.add(id); + if (id == 701) { + assert length == 0; + ackAt = i; + continue; + } + assert length > 0 && length <= OpenIdeaJdbc.LIMIT; + assert in.readBoolean() : "JDBC result did not finish: " + id; + in.skipNBytes(length - 1); + if (id == 700) { + assert length < 1024; + smallAt = i; + } else { + assert id > 600 && id <= 600 + largeQueries && length > 15 * 1024 * 1024; + } + } + assert smallAt >= 0 && smallAt < largeQueries + 1; + assert ackAt >= 0 && ackAt < largeQueries + 1; + sendOn(out, 702, 0, "valid"); + expect(in, 702, 1); + sendOn(out, 703, 1, "query", "large error", "0", "1000"); + expect(in, 703, 0); + sendOn(out, 704, 2, "query", "large rows", "0", "1000"); + assert in.readLong() == 704; + int length = in.readInt(); + assert length > 15 * 1024 * 1024 && in.readBoolean(); + in.skipNBytes(length - 1); // The failed encoding released its reply reservation. + } finally { + child.destroyForcibly().waitFor(); + } + } + public static void main(String[] args) throws Exception { var boundary = new DataOutputStream(OutputStream.nullOutputStream()); OpenIdeaJdbc.text(boundary, "x".repeat(OpenIdeaJdbc.LIMIT - 14)); @@ -124,8 +402,7 @@ public class SelfTest { throw new AssertionError("Oversized reply accepted"); } catch (IOException expected) {} var java = Path.of(System.getProperty("java.home"), "bin", "java").toString(); - var child = new ProcessBuilder(java, "-cp", System.getProperty("java.class.path"), - OpenIdeaJdbc.class.getName()).start(); + var child = start(java, false); try (var out = new DataOutputStream(child.getOutputStream()); var in = new DataInputStream(child.getInputStream()); var log = child.errorReader()) { @@ -163,5 +440,9 @@ public class SelfTest { } finally { child.destroyForcibly().waitFor(); } + multiplex(java); + capacity(java); + brokenStreams(java); + boundedReplies(java); } } diff --git a/src/features/database/results-view.test.tsx b/src/features/database/results-view.test.tsx index b77a6c3af..3045a8c43 100644 --- a/src/features/database/results-view.test.tsx +++ b/src/features/database/results-view.test.tsx @@ -1281,11 +1281,11 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab } }); - it("routes ClickHouse runs and result operations through the originating SQL editor", async () => { + it.each(["clickhouse", "jdbc"] as const)("keeps %s results in their editor session", async (driver) => { const first = "/project/console.sql"; const second = "/project/console_1.sql"; useDatabase.setState({ - sources: [{ id: "pg", name: "Local", driver: "clickhouse", readOnly: false }], + sources: [{ id: "pg", name: "Local", driver, readOnly: false }], }); backend.resultRow.mockResolvedValue({ status: "ok", data: result([{ name: "v" }], [["1"]]) }); backend.explain.mockResolvedValue({ status: "ok", data: [] }); @@ -1305,11 +1305,13 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab await readResultRow(firstResult, 1); expect(backend.resultRow.mock.lastCall?.[5]).toBe(first); - await explainConsole(second, "SELECT 2", 0, 0); - expect(backend.explain.mock.lastCall?.[4]).toBe(second); - const plan = useDatabase.getState().results.find((tab) => !!tab.plan)!; - await rerunResult(plan.id); - expect(backend.explain.mock.lastCall?.[4]).toBe(second); + if (driver === "clickhouse") { + await explainConsole(second, "SELECT 2", 0, 0); + expect(backend.explain.mock.lastCall?.[4]).toBe(second); + const plan = useDatabase.getState().results.find((tab) => !!tab.plan)!; + await rerunResult(plan.id); + expect(backend.explain.mock.lastCall?.[4]).toBe(second); + } await runSql("pg", ["SELECT 3"]); expect(backend.execute.mock.lastCall?.[7]).toBeNull(); diff --git a/src/features/database/store.ts b/src/features/database/store.ts index 3abf4bd14..334878a02 100644 --- a/src/features/database/store.ts +++ b/src/features/database/store.ts @@ -1669,7 +1669,7 @@ function withConsoleConnection( const current = databaseRequest(id); return withConnection(id, async () => { const driver = sourceById(id)?.driver; - if (!path || (driver !== "clickhouse" && driver !== "postgres")) return op(null, null); + if (!path || (driver !== "clickhouse" && driver !== "postgres" && driver !== "jdbc")) return op(null, null); const key = consoleScopeKey(id, path); // A reopened editor waits for the previous session's release before using the same path. const closing = closingConsoles.get(key);