diff --git a/crates/ide-db/src/conn.rs b/crates/ide-db/src/conn.rs index 640479758..2d5a930c0 100644 --- a/crates/ide-db/src/conn.rs +++ b/crates/ide-db/src/conn.rs @@ -749,6 +749,14 @@ impl Pool { } /// The keep-alive ping (Oracle needs a FROM clause). + /// Keep-alive: one cheap round trip on the session. + pub async fn ping(&self) -> IdeResult<()> { + match self { + Pool::Jdbc(p) => p.ping().await, + _ => self.rows(self.ping_sql(), 1).await.map(|_| ()), + } + } + pub fn ping_sql(&self) -> &'static str { match self { Pool::Oracle(_) => "SELECT 1 FROM DUAL", diff --git a/crates/ide-db/src/jdbc/mod.rs b/crates/ide-db/src/jdbc/mod.rs index 4ed2d8d6d..bc8a23bd6 100644 --- a/crates/ide-db/src/jdbc/mod.rs +++ b/crates/ide-db/src/jdbc/mod.rs @@ -458,6 +458,44 @@ 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; + } + result + } + + /// Keep-alive: checks the session (any SQL would be dialect-specific) and closes a dead one. + pub(crate) async fn ping(&self) -> IdeResult<()> { + if self.session_valid().await { + return Ok(()); + } + self.close().await; + Err(IdeError::new(ide_core::error::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; + } + 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()), diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index bd5d8ab05..bbd858b03 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -379,8 +379,8 @@ pub(crate) fn keep_alive(pool: &Arc, every: Duration) { loop { tick.tick().await; let Some(p) = pool.upgrade().filter(|p| !p.is_closed()) else { break }; - if let Err(e) = p.rows(p.ping_sql(), 1).await { - tracing::debug!("keep-alive: {}", e.message); + if let Err(e) = p.ping().await { + tracing::info!("keep-alive: {}", e.message); } } }); @@ -847,12 +847,12 @@ impl DbManager { } pub fn is_connected(&self, id: &str) -> bool { - self.pools.lock().contains_key(id) + self.pools.lock().get(id).is_some_and(|p| !p.is_closed()) } /// Connected targets (data source ids, `:`). pub fn connected(&self) -> Vec { - self.pools.lock().keys().cloned().collect() + self.pools.lock().iter().filter(|(_, p)| !p.is_closed()).map(|(id, _)| id.clone()).collect() } /// The pool of target `id`, connecting first if needed. @@ -862,8 +862,13 @@ impl DbManager { if self.tunnels.lock().get(source_id).is_some_and(|t| t.is_closed()) { self.disconnect_source(source_id).await; } - if let Some(p) = self.pools.lock().get(id) { - return Ok(p.clone()); + let cached = self.pools.lock().get(id).cloned(); + if let Some(p) = cached { + if !p.is_closed() { + return Ok(p); + } + // The connection broke (a custom JDBC session whose TCP connection was dropped): reconnect. + self.disconnect(id).await; } let source = self.source(id)?; let password = self.password(&source).await; @@ -917,7 +922,7 @@ impl DbManager { /// Disconnects every database of data source `id`. pub async fn disconnect_source(&self, id: &str) { - let targets: Vec = self.connected().into_iter().filter(|t| split_target(t).0 == id).collect(); + let targets: Vec = self.pools.lock().keys().filter(|t| split_target(t).0 == id).cloned().collect(); for t in targets { self.disconnect(&t).await; } diff --git a/crates/ide-db/tests/jdbc.rs b/crates/ide-db/tests/jdbc.rs index 1d772b046..ca526f336 100644 --- a/crates/ide-db/tests/jdbc.rs +++ b/crates/ide-db/tests/jdbc.rs @@ -213,3 +213,36 @@ async fn unresponsive_driver_closes_before_reconnect() -> IdeResult<()> { 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<()> { + let tmp = tempfile::tempdir()?; + let db = manager(tmp.path()); + db.save_jdbc_driver(DbJdbcDriver { + id: "fixture".into(), + name: "Fixture".into(), + jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()], + class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(), + url_template: String::new(), + })?; + let source = DataSource { + id: "test".into(), + name: "Fixture".into(), + driver: DbDriver::Jdbc, + global: true, + jdbc_driver: "fixture".into(), + url: "jdbc:fixture:".into(), + ..Default::default() + }; + db.save_sources(vec![source]).await?; + let cancel = CancellationToken::new(); + db.execute("test", "first", 1, &cancel).await?; + // The fixture's session reports itself invalid after "drop", like a connection a proxy reset. + assert!(db.execute("test", "drop", 1, &cancel).await.unwrap_err().message.contains("connection reset")); + assert!(!db.is_connected("test"), "a lost session is no longer listed as connected"); + assert_eq!(db.execute("test", "after reconnect", 1, &cancel).await?.affected, Some(1.0)); + assert!(db.is_connected("test")); + db.disconnect("test").await; + Ok(()) +} diff --git a/java/jdbc-bridge/openidea-jdbc-bridge.jar b/java/jdbc-bridge/openidea-jdbc-bridge.jar index 6a54f0f24..412c92bb5 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/OpenIdeaJdbc.java b/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java index f9bf30214..c8a710e7e 100644 --- a/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java +++ b/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java @@ -243,6 +243,20 @@ public final class OpenIdeaJdbc { } catch (SQLException | AbstractMethodError ignored) {} row(reply, name); } + case "valid" -> { + // After a failed statement: whether the session survived (a dropped TCP + // connection leaves every later statement failing until the IDE reconnects). + header(reply, "valid"); + boolean valid; + try { + valid = connection != null && !connection.isClosed() && connection.isValid(5); + } catch (AbstractMethodError | SQLFeatureNotSupportedException e) { + valid = true; // A pre-JDBC 4 driver cannot tell: keep the session. + } catch (SQLException e) { + valid = false; + } + row(reply, Boolean.toString(valid)); + } case "page" -> execute(work, a, reply, true); case "query" -> { if (a.size() == 3 || a.get(3).isEmpty()) { diff --git a/java/jdbc-bridge/tests/SelfTest.java b/java/jdbc-bridge/tests/SelfTest.java index 9f8dfeb5d..86198140c 100644 --- a/java/jdbc-bridge/tests/SelfTest.java +++ b/java/jdbc-bridge/tests/SelfTest.java @@ -14,6 +14,7 @@ import java.util.logging.Logger; public class SelfTest { public static class Fixture implements Driver { private boolean readonly; + private boolean dropped; private int changes; private Path started; @@ -36,6 +37,8 @@ public class SelfTest { case "getMetaData" -> meta; case "close" -> null; case "createStatement" -> statement(); + case "isClosed" -> false; + case "isValid" -> !dropped; default -> throw new SQLFeatureNotSupportedException(); }); } @@ -53,6 +56,7 @@ public class SelfTest { throw new SQLException("statement cancelled"); } if (sql.equals("write") && readonly) throw new SQLException("read-only"); + if (sql.equals("drop")) { dropped = true; throw new SQLException("connection reset"); } changes++; yield false; } @@ -122,6 +126,12 @@ public class SelfTest { send(out, 5, "query", "after cancel", "0", "2"); var result = reply(in); assert result[0] == 1 && result[result.length - 1] == 2; + send(out, 6, "valid"); + assert new String(reply(in), StandardCharsets.UTF_8).contains("true"); + send(out, 7, "query", "drop", "0", "2"); + assert reply(in)[0] == 0; + send(out, 8, "valid"); + assert new String(reply(in), StandardCharsets.UTF_8).contains("false"); } finally { child.destroyForcibly().waitFor(); } diff --git a/src/features/database/SourceDialog.tsx b/src/features/database/SourceDialog.tsx index a635139c0..5de9d35c1 100644 --- a/src/features/database/SourceDialog.tsx +++ b/src/features/database/SourceDialog.tsx @@ -1020,14 +1020,16 @@ export function SourceDialog({ } onChange={(e) => setOptions({ timeZone: e.target.value })} /> - setOptions({ keepAliveSecs })} - /> )} + {!sqlite && ( + setOptions({ keepAliveSecs })} + /> + )} null); + if (!server || server.includes(id) || !useDatabase.getState().connected.has(id)) return; + useDatabase.setState((s) => { + const connected = new Set(s.connected); + connected.delete(id); + return { connected }; + }); + log("info", `${targetLabel(id)}: the connection was lost; the next statement reconnects`); +} + async function run( id: string, statements: SqlStatement[], @@ -1087,6 +1099,8 @@ async function run( ); if (!current()) return outcomes; if (!wasConnected) log("info", "Connected"); + // A failed statement can have found the session dead; the backend then dropped it. + if (outcomes.some((o) => o.error)) void syncDropped(id); const prompt = schema || promptOf(id); for (const o of outcomes) { log("statement", o.statement.text, `${prompt}>`);