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
SSH 隧道连接优化 (#517)
rarnu51e62d4c60c6
diff --git a/crates/dbx-core/src/db/ssh_tunnel.rs b/crates/dbx-core/src/db/ssh_tunnel.rsindex 057e9dbf70..4e3c5ad348 100644--- a/crates/dbx-core/src/db/ssh_tunnel.rs+++ b/crates/dbx-core/src/db/ssh_tunnel.rs@@ -8,9 +8,17 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};use tokio::net::TcpListener;use tokio::sync::Mutex;use tokio::task::JoinHandle;+use tokio::time::Duration;use super::file_validator::validate_file_path;+/// Initial delay between SSH reconnect attempts.+const INITIAL_RECONNECT_DELAY: Duration = Duration::from_secs(5);+/// Maximum delay for exponential backoff.+const MAX_RECONNECT_DELAY: Duration = Duration::from_secs(60);+/// Maximum number of consecutive reconnect attempts before giving up.+const MAX_RECONNECT_ATTEMPTS: u32 = 10;+struct SshClient;impl client::Handler for SshClient {@@ -33,8 +41,9 @@ async fn connect_and_authenticate(ssh_key_passphrase: &str,connect_timeout_secs: u64,) -> Result<Handle<SshClient>, String> {- let config = Arc::new(Config { nodelay: true, ..Default::default() });- let connect_timeout = std::time::Duration::from_secs(connect_timeout_secs);+ let config =+ Arc::new(Config { nodelay: true, keepalive_interval: Some(Duration::from_secs(30)), ..Default::default() });+ let connect_timeout = Duration::from_secs(connect_timeout_secs);let mut session =tokio::time::timeout(connect_timeout, client::connect(config, (ssh_host, ssh_port), SshClient {}))@@ -79,16 +88,27 @@ async fn connect_and_authenticate(Ok(session)}-async fn forward_loop(session: Handle<SshClient>, listener: TcpListener, remote_host: String, remote_port: u16) {+/// Accept connections on the local listener and forward them through the SSH session.+/// Returns when the SSH session dies (listener error or session.is_closed()).+async fn forward_loop(session: &Handle<SshClient>, listener: &TcpListener, remote_host: &str, remote_port: u16) {loop {let (mut stream, peer_addr) = match listener.accept().await {Ok(v) => v,- Err(_) => break,+ Err(e) => {+ log::error!("SSH tunnel listener error: {e}");+ break;+ }};+ // Check session health before opening a new channel+ if session.is_closed() {+ log::warn!("SSH session closed, exiting forward loop");+ break;+ }+let mut channel = match session.channel_open_direct_tcpip(- &remote_host,+ remote_host,remote_port.into(),peer_addr.ip().to_string(),peer_addr.port().into(),@@ -98,6 +118,10 @@ async fn forward_loop(session: Handle<SshClient>, listener: TcpListener, remote_Ok(c) => c,Err(e) => {log::error!("SSH direct-tcpip failed: {e}");+ if session.is_closed() {+ log::warn!("SSH session closed after channel open failure");+ break;+ }continue;}};@@ -139,6 +163,76 @@ async fn forward_loop(session: Handle<SshClient>, listener: TcpListener, remote_}}+/// Main tunnel task: runs the forward loop and automatically reconnects+/// the SSH session when it drops. The local TcpListener survives across+/// reconnections so the tunnel appears continuously available to clients.+/// Uses exponential backoff for reconnect attempts and gives up after+/// MAX_RECONNECT_ATTEMPTS to avoid log storms from permanent failures.+async fn tunnel_reconnect_loop(+ mut session: Handle<SshClient>,+ ssh_host: String,+ ssh_port: u16,+ ssh_user: String,+ ssh_password: String,+ ssh_key_path: String,+ ssh_key_passphrase: String,+ connect_timeout_secs: u64,+ listener: TcpListener,+ remote_host: String,+ remote_port: u16,+) {+ loop {+ log::info!("SSH tunnel active: {}:{} -> {}:{}", ssh_host, ssh_port, remote_host, remote_port);++ forward_loop(&session, &listener, &remote_host, remote_port).await;++ log::warn!("SSH tunnel connection lost ({}:{}), reconnecting...", ssh_host, ssh_port);++ // Reconnect with exponential backoff+ let mut delay = INITIAL_RECONNECT_DELAY;+ let mut attempts: u32 = 0;++ loop {+ if attempts >= MAX_RECONNECT_ATTEMPTS {+ log::error!(+ "SSH tunnel ({ssh_host}:{ssh_port}): max reconnect attempts ({MAX_RECONNECT_ATTEMPTS}) exhausted, giving up"+ );+ return;+ }++ tokio::time::sleep(delay).await;++ match connect_and_authenticate(+ &ssh_host,+ ssh_port,+ &ssh_user,+ &ssh_password,+ &ssh_key_path,+ &ssh_key_passphrase,+ connect_timeout_secs,+ )+ .await+ {+ Ok(new_session) => {+ session = new_session;+ log::info!("SSH tunnel reconnected to {}:{} (attempt {})", ssh_host, ssh_port, attempts + 1);+ break;+ }+ Err(e) => {+ attempts += 1;+ log::error!(+ "SSH reconnect failed ({}:{}, attempt {attempts}/{MAX_RECONNECT_ATTEMPTS}): {e}",+ ssh_host,+ ssh_port,+ );+ // Exponential backoff: double the delay, cap at MAX_RECONNECT_DELAY+ delay = std::cmp::min(delay * 2, MAX_RECONNECT_DELAY);+ }+ }+ }+ }+}+pub struct TunnelManager {tunnels: Mutex<HashMap<String, (JoinHandle<()>, u16)>>,}@@ -148,6 +242,7 @@ impl TunnelManager {Self { tunnels: Mutex::new(HashMap::new()) }}+ #[allow(clippy::too_many_arguments)]pub async fn start_tunnel(&self,connection_id: &str,@@ -164,6 +259,11 @@ impl TunnelManager {) -> Result<u16, String> {let local_port = portpicker::pick_unused_port().ok_or("No available port")?;+ let bind_addr = if expose_to_lan { "0.0.0.0" } else { "127.0.0.1" };+ let listener =+ TcpListener::bind((bind_addr, local_port)).await.map_err(|e| format!("Failed to bind local port: {e}"))?;++ // Initial connection: fail fast on bad credentialslet session = connect_and_authenticate(ssh_host,ssh_port,@@ -175,12 +275,19 @@ impl TunnelManager {).await?;- let bind_addr = if expose_to_lan { "0.0.0.0" } else { "127.0.0.1" };- let listener =- TcpListener::bind((bind_addr, local_port)).await.map_err(|e| format!("Failed to bind local port: {e}"))?;-- let remote_host = remote_host.to_string();- let handle = tokio::spawn(forward_loop(session, listener, remote_host, remote_port));+ let handle = tokio::spawn(tunnel_reconnect_loop(+ session,+ ssh_host.to_string(),+ ssh_port,+ ssh_user.to_string(),+ ssh_password.to_string(),+ ssh_key_path.to_string(),+ ssh_key_passphrase.to_string(),+ connect_timeout_secs,+ listener,+ remote_host.to_string(),+ remote_port,+ ));self.tunnels.lock().await.insert(connection_id.to_string(), (handle, local_port));