25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(agent): reclaim idle metadata connections
zipg87493881c333
diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rsindex 658e32fbbc..ef7d7a0604 100644--- a/crates/dbx-core/src/connection.rs+++ b/crates/dbx-core/src/connection.rs@@ -3,7 +3,7 @@ use std::path::PathBuf;use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::Arc;use std::time::{Duration, Instant};-use tokio::sync::{Mutex, RwLock};+use tokio::sync::{watch, Mutex, RwLock};#[cfg(feature = "duckdb-bundled")]use tokio::task::JoinHandle;@@ -179,6 +179,7 @@ pub struct AppState {pub connections: Arc<RwLock<HashMap<String, PoolKind>>>,task_supervisor: TaskSupervisor,pool_activity: Arc<RwLock<HashMap<String, PoolActivity>>>,+ draining_pools: Arc<std::sync::Mutex<HashMap<String, watch::Sender<bool>>>>,connection_attempts: RwLock<HashMap<String, ConnectionAttemptState>>,pub configs: RwLock<HashMap<String, ConnectionConfig>>,pub running_queries: RunningQueries,@@ -224,6 +225,19 @@ struct ConnectionAttemptState {client_attempt: Option<u64>,}+struct PoolDrainGuard {+ pool_key: String,+ draining_pools: Arc<std::sync::Mutex<HashMap<String, watch::Sender<bool>>>>,+ signal: watch::Sender<bool>,+}++impl Drop for PoolDrainGuard {+ fn drop(&mut self) {+ self.draining_pools.lock().unwrap_or_else(|error| error.into_inner()).remove(&self.pool_key);+ let _ = self.signal.send(false);+ }+}+impl PoolActivity {fn now() -> Self {Self { last_used_at_ms: std::sync::atomic::AtomicU64::new(pool_activity_now_ms()) }@@ -610,6 +624,7 @@ impl AppState {connections: Arc::new(RwLock::new(HashMap::new())),task_supervisor: TaskSupervisor::new(),pool_activity: Arc::new(RwLock::new(HashMap::new())),+ draining_pools: Arc::new(std::sync::Mutex::new(HashMap::new())),connection_attempts: RwLock::new(HashMap::new()),configs: RwLock::new(HashMap::new()),running_queries: RunningQueries::default(),@@ -848,7 +863,43 @@ impl AppState {Ok(PluginRuntimeEnv::default().with_var("DBX_JAVA_BIN", java.to_string_lossy().to_string()))}- pub async fn insert_connection_pool(&self, pool_key: String, pool: PoolKind, config: &ConnectionConfig) {+ fn begin_pool_drain(&self, pool_key: &str) -> Option<PoolDrainGuard> {+ let mut draining = self.draining_pools.lock().unwrap_or_else(|error| error.into_inner());+ if draining.contains_key(pool_key) {+ return None;+ }+ let (signal, _) = watch::channel(true);+ draining.insert(pool_key.to_string(), signal.clone());+ Some(PoolDrainGuard { pool_key: pool_key.to_string(), draining_pools: self.draining_pools.clone(), signal })+ }++ async fn wait_for_pool_drain(&self, pool_key: &str) {+ loop {+ let receiver = self+ .draining_pools+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .get(pool_key)+ .map(watch::Sender::subscribe);+ let Some(mut receiver) = receiver else {+ return;+ };+ if *receiver.borrow_and_update() && receiver.changed().await.is_err() {+ return;+ }+ }+ }++ async fn insert_connection_pool_inner(+ &self,+ pool_key: String,+ pool: PoolKind,+ config: &ConnectionConfig,+ wait_for_drain: bool,+ ) {+ if wait_for_drain {+ self.wait_for_pool_drain(&pool_key).await;+ }self.stop_keepalive_task(&pool_key).await;self.pool_activity.write().await.insert(pool_key.clone(), PoolActivity::now());self.start_keepalive_task(&pool_key, &pool, config).await;@@ -859,6 +910,10 @@ impl AppState {}}+ pub async fn insert_connection_pool(&self, pool_key: String, pool: PoolKind, config: &ConnectionConfig) {+ self.insert_connection_pool_inner(pool_key, pool, config, true).await;+ }+pub async fn begin_connection_attempt(&self, connection_id: &str) -> u64 {self.begin_connection_attempt_with_client_attempt(connection_id, None).await}@@ -1016,6 +1071,10 @@ impl AppState {self.task_supervisor.stop(&format!("keepalive:{pool_key}"));}+ async fn stop_keepalive_task_and_wait(&self, pool_key: &str) {+ self.task_supervisor.stop_and_wait(&format!("keepalive:{pool_key}")).await;+ }+async fn stop_keepalive_tasks(&self, pool_keys: &[String]) {let keys: Vec<String> = pool_keys.iter().map(|pool_key| format!("keepalive:{pool_key}")).collect();self.task_supervisor.stop_many(keys.iter().map(String::as_str));@@ -1091,19 +1150,30 @@ impl AppState {let validate_existing_pool = should_validate_existing_pool_before_reuse(config.db_type);let base_pool_key = base_pool_key_for(db_type, connection_id, database, false);- let pool_key = session_scoped_pool_key_for(Some(&config), base_pool_key, client_session_id);+ let pool_key = session_scoped_pool_key_for(Some(&config), base_pool_key.clone(), client_session_id);- let conns = self.connections.read().await;- if conns.contains_key(&pool_key) {- drop(conns);- if self.remove_pool_if_duckdb_isolation_mismatch(&pool_key).await {- // Recreate below using the current DuckDB isolation mode.- } else if !validate_existing_pool || !self.remove_stale_connection_pool(&pool_key).await {- self.touch_pool_activity(&pool_key).await;- return Ok(pool_key);+ loop {+ self.wait_for_pool_drain(&pool_key).await;+ let conns = self.connections.read().await;+ if conns.contains_key(&pool_key) {+ drop(conns);+ if self.remove_pool_if_duckdb_isolation_mismatch(&pool_key).await {+ // Recreate below using the current DuckDB isolation mode.+ } else if !validate_existing_pool || !self.remove_stale_connection_pool(&pool_key).await {+ self.touch_pool_activity(&pool_key).await;+ return Ok(pool_key);+ }+ break;}- } else {drop(conns);++ // A reclaim may have removed the pool after the first drain check. Wait+ // for its confirmed close or rollback before deciding to create a new one.+ self.wait_for_pool_drain(&pool_key).await;+ if self.connections.read().await.contains_key(&pool_key) {+ continue;+ }+ break;}let db_config = database_connection_config(&config, database);@@ -1361,7 +1431,7 @@ impl AppState {agent_connect_params(&db_config, &host, port, db_config.effective_database().unwrap_or(""));if db_config.db_type != DatabaseType::Etcd && db_config.db_type != DatabaseType::ZooKeeper {let agent_session_id = uuid::Uuid::new_v4().simple().to_string();- let initial_result = self+ let mut initial_result = self.agent_manager.spawn_shared_connection_client(&db_config.db_type,@@ -1372,6 +1442,37 @@ impl AppState {agent_connect_timeout(&db_config),).await;+ if initial_result.as_ref().is_err_and(|err| {+ normalize_client_session_id(client_session_id).is_some()+ && is_connection_slot_exhausted_error(err)+ }) && self.reclaim_idle_base_pool_for_session(connection_id, &base_pool_key).await+ {+ log::warn!(+ "Reclaimed an idle metadata pool for '{connection_id}' after the database rejected a new Agent session due to exhausted connection slots"+ );+ for retry_delay_ms in [150, 350] {+ tokio::time::sleep(Duration::from_millis(retry_delay_ms)).await;+ initial_result = self+ .agent_manager+ .spawn_shared_connection_client(+ &db_config.db_type,+ db_config.driver_profile.as_deref(),+ &db_config.agent_java_options,+ agent_session_id.clone(),+ agent_connect_params(+ &db_config,+ &host,+ port,+ db_config.effective_database().unwrap_or(""),+ ),+ agent_connect_timeout(&db_config),+ )+ .await;+ if !initial_result.as_ref().is_err_and(|err| is_connection_slot_exhausted_error(err)) {+ break;+ }+ }+ }let client = match initial_result {Ok(client) => client,Err(err) => {@@ -2221,6 +2322,105 @@ impl AppState {}}+ async fn reclaim_idle_base_pool_for_session(&self, connection_id: &str, preferred_base_pool_key: &str) -> bool {+ let pool_prefix = format!("{connection_id}:");+ let activity = self.pool_activity.read().await;+ let connections = self.connections.read().await;+ let mut candidates: Vec<(String, (usize, u64))> = connections+ .iter()+ .filter_map(|(key, pool)| {+ if !matches!(pool, PoolKind::Agent(_))+ || (key != connection_id && !key.starts_with(&pool_prefix))+ || is_session_scoped_pool_key(key)+ || self.running_queries.is_pool_active(key)+ {+ return None;+ }+ let preferred_rank = usize::from(key != preferred_base_pool_key);+ let last_used = activity+ .get(key)+ .map(|value| value.last_used_at_ms.load(std::sync::atomic::Ordering::Relaxed))+ .unwrap_or(0);+ Some((key.clone(), (preferred_rank, last_used)))+ })+ .collect();+ drop(connections);+ drop(activity);+ candidates.sort_by_key(|(_, rank)| *rank);++ for (pool_key, _) in candidates {+ let Some(_drain) = self.begin_pool_drain(&pool_key) else {+ continue;+ };+ if self.try_reclaim_idle_agent_pool(&pool_key).await {+ return true;+ }+ }+ false+ }++ async fn try_reclaim_idle_agent_pool(&self, pool_key: &str) -> bool {+ self.stop_keepalive_task_and_wait(pool_key).await;+ if self.running_queries.is_pool_active(pool_key) {+ self.restart_agent_keepalive(pool_key).await;+ return false;+ }++ let removed = {+ let mut connections = self.connections.write().await;+ let exclusively_idle = match connections.get(pool_key) {+ Some(PoolKind::Agent(client)) => Arc::strong_count(client) == 1 && client.try_lock().is_ok(),+ _ => false,+ };+ exclusively_idle.then(|| connections.remove(pool_key)).flatten()+ };+ let Some(pool) = removed else {+ self.restart_agent_keepalive(pool_key).await;+ return false;+ };++ self.pool_activity.write().await.remove(pool_key);+ self.postgres_cancel_contexts.write().await.remove(pool_key);+ match close_reclaimed_agent_pool(pool).await {+ Ok(()) => true,+ Err((pool, error)) => {+ log::warn!("Failed to close reclaimed Agent pool '{pool_key}': {error}; restoring the pool");+ self.restore_reclaimed_agent_pool(pool_key, pool).await;+ false+ }+ }+ }++ async fn restart_agent_keepalive(&self, pool_key: &str) {+ let config = {+ let configs = self.configs.read().await;+ config_for_pool_key(pool_key, &configs).cloned()+ };+ let client = {+ let connections = self.connections.read().await;+ match connections.get(pool_key) {+ Some(PoolKind::Agent(client)) => Some(client.clone()),+ _ => None,+ }+ };+ if let (Some(config), Some(client)) = (config, client) {+ self.start_keepalive_task(pool_key, &PoolKind::Agent(client), &config).await;+ }+ }++ async fn restore_reclaimed_agent_pool(&self, pool_key: &str, pool: PoolKind) {+ let config = {+ let configs = self.configs.read().await;+ config_for_pool_key(pool_key, &configs).cloned()+ };+ if let Some(config) = config {+ self.insert_connection_pool_inner(pool_key.to_string(), pool, &config, false).await;+ } else {+ self.pool_activity.write().await.insert(pool_key.to_string(), PoolActivity::now());+ self.connections.write().await.insert(pool_key.to_string(), pool);+ }+ }+#[cfg(feature = "duckdb-bundled")]async fn remove_pool_by_key_detached(&self, pool_key: &str) -> bool {self.stop_keepalive_task(pool_key).await;@@ -3090,7 +3290,6 @@ fn session_scoped_pool_key(base_pool_key: String, client_session_id: Option<&str.unwrap_or(base_pool_key)}-#[cfg(test)]fn is_session_scoped_pool_key(pool_key: &str) -> bool {pool_key.contains(":session:")}@@ -3218,6 +3417,21 @@ pub async fn close_pool_kind(pool: PoolKind) {}}+async fn close_reclaimed_agent_pool(pool: PoolKind) -> Result<(), (PoolKind, String)> {+ let client = match pool {+ PoolKind::Agent(client) => client,+ pool => return Err((pool, "Only Agent pools can be reclaimed after connection slot exhaustion".to_string())),+ };+ let result = {+ let mut client = client.lock().await;+ client.disconnect().await.map(|_| ())+ };+ match result {+ Ok(()) => Ok(()),+ Err(error) => Err((PoolKind::Agent(client), error)),+ }+}+async fn close_removed_pools(removed: Vec<(String, PoolKind)>) {for (pool_key, pool) in removed {close_pool_kind_with_timeout(pool_key, pool).await;@@ -3285,6 +3499,15 @@ fn base_pool_key_for(}}+fn is_connection_slot_exhausted_error(error: &str) -> bool {+ let lower = error.to_ascii_lowercase();+ lower.contains("remaining connection slots are reserved")+ || lower.contains("too many connections")+ || lower.contains("maximum number of connections exceeded")+ || lower.contains("max client connections reached")+ || lower.contains("ora-00018")+}+fn shares_database_pool_with_connection(db_type: &DatabaseType) -> bool {matches!(db_type, DatabaseType::Oracle)}@@ -4806,6 +5029,106 @@ mod tests {let _ = std::fs::remove_dir_all(dir);}+ #[tokio::test]+ async fn connection_slot_recovery_waits_for_agent_metadata_and_confirms_close() {+ let (state, dir) = test_app_state().await;+ let script_path = dir.join("agent.py");+ let metadata_started_path = dir.join("metadata-started");+ let session_closed_path = dir.join("session-closed");+ let metadata_started = serde_json::to_string(&metadata_started_path.to_string_lossy()).unwrap();+ let session_closed = serde_json::to_string(&session_closed_path.to_string_lossy()).unwrap();+ std::fs::write(+ &script_path,+ format!(+ r#"import json, pathlib, sys, time+metadata_started = pathlib.Path({metadata_started})+session_closed = pathlib.Path({session_closed})+print(json.dumps({{'ready': True}}), flush=True)+for line in sys.stdin:+ req = json.loads(line)+ method = req['method']+ if method == 'handshake':+ result = {{'protocolVersion': 2, 'agentProtocolVersion': 2, 'capabilities': ['multi_session']}}+ elif method == 'list_databases':+ metadata_started.write_text('started')+ time.sleep(3.2)+ result = []+ elif method == 'close_session':+ session_closed.write_text(req['params']['agentSessionId'])+ result = {{}}+ else:+ result = {{}}+ print(json.dumps({{'jsonrpc': '2.0', 'id': req['id'], 'result': result}}), flush=True)+"#+ ),+ )+ .unwrap();++ let runtime = crate::db::agent_driver::AgentRuntimeClient::spawn(+ crate::db::agent_driver::AgentLaunchSpec::new("python3")+ .with_args([script_path.to_string_lossy().to_string()]),+ "test",+ )+ .await+ .unwrap();+ runtime.increment_session_count();+ let client = std::sync::Arc::new(tokio::sync::Mutex::new(+ crate::db::agent_driver::AgentDriverClient::shared_session(runtime.clone(), "metadata-session".to_string()),+ ));+ state.connections.write().await.insert("conn:analytics".to_string(), PoolKind::Agent(client.clone()));++ let metadata_client = client.clone();+ drop(client);+ let metadata = tokio::spawn(async move {+ metadata_client.lock().await.list_databases::<Vec<String>>(Some(Duration::from_secs(6))).await+ });+ for _ in 0..100 {+ if metadata_started_path.exists() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ assert!(metadata_started_path.exists());++ let reclaim_started = Instant::now();+ assert!(!state.reclaim_idle_base_pool_for_session("conn", "conn:analytics").await);+ assert!(reclaim_started.elapsed() < Duration::from_secs(1));+ assert!(state.connections.read().await.contains_key("conn:analytics"));+ assert!(!session_closed_path.exists());++ assert_eq!(metadata.await.unwrap().unwrap(), Vec::<String>::new());+ assert!(state.reclaim_idle_base_pool_for_session("conn", "conn:analytics").await);+ assert!(!state.connections.read().await.contains_key("conn:analytics"));+ assert_eq!(std::fs::read_to_string(&session_closed_path).unwrap(), "metadata-session");+ assert_eq!(runtime.active_session_count(), 0);++ runtime.kill();+ let _ = std::fs::remove_dir_all(dir);+ }++ #[tokio::test]+ async fn connection_slot_recovery_keeps_active_metadata_pool() {+ let (state, dir) = test_app_state().await;+ state.connections.write().await.insert("conn:analytics".to_string(), agent_pool_stub());++ let _query = state.running_queries.register("active-metadata".to_string());+ state.running_queries.set_pool_key("active-metadata", "conn:analytics");++ assert!(!state.reclaim_idle_base_pool_for_session("conn", "conn:analytics").await);+ assert!(state.connections.read().await.contains_key("conn:analytics"));++ let _ = std::fs::remove_dir_all(dir);+ }++ #[test]+ fn detects_database_connection_slot_exhaustion_errors() {+ assert!(super::is_connection_slot_exhausted_error(+ "Agent RPC error (-1): FATAL: remaining connection slots are reserved for superuser manager connections"+ ));+ assert!(super::is_connection_slot_exhausted_error("ORA-00018: maximum number of sessions exceeded"));+ assert!(!super::is_connection_slot_exhausted_error("password authentication failed"));+ }+#[tokio::test]async fn pool_activity_touch_updates_existing_pool_only() {let (state, dir) = test_app_state().await;diff --git a/crates/dbx-core/src/task_supervisor.rs b/crates/dbx-core/src/task_supervisor.rsindex 2b1889f710..76f145520d 100644--- a/crates/dbx-core/src/task_supervisor.rs+++ b/crates/dbx-core/src/task_supervisor.rs@@ -44,6 +44,14 @@ impl TaskSupervisor {}}+ pub async fn stop_and_wait(&self, key: &str) {+ let task = self.tasks.lock().unwrap_or_else(|error| error.into_inner()).remove(key);+ if let Some(task) = task {+ task.abort();+ let _ = task.await;+ }+ }+pub fn stop_many<'a>(&self, keys: impl IntoIterator<Item = &'a str>) {for key in keys {self.stop(key);