Skip to content

armgit / dbx

Public Imported from GitHub
0

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。

fix(redis): bound visible database picker metadata waits

Xsyl.way8dfe53610055
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index ab2b2ad6df..88dfba94be 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -76,6 +76,7 @@ import type { PluginCenterFocus } from "@/lib/plugins/pluginCenterNavigation";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { isWindows } from "@/lib/backend/platform";
import { applyMeilisearchBasePathToExternalConfig, applyParsedConnectionUrl, normalizeMongoConnectionString, parseConnectionUrl } from "@/lib/connection/connectionUrl";
+import { loadVisibleDatabasesPickerNames } from "@/lib/connection/visibleDatabasesPickerLoad";
import { hasXuguConnectionDatabase } from "@/lib/connection/xuguDatabase";
import {
DEFAULT_MANUAL_TRANSACTION_TIMEOUT_SECS,
@@ -5702,12 +5703,15 @@ async function preloadVisibleDatabaseNames() {
id: draftId,
one_time: true,
};
- await api.connectDb(draftConfig);
- visibleDatabaseNames.value = await loadVisibleDatabaseNames(draftId, draftConfig);
+ visibleDatabaseNames.value = await loadVisibleDatabasesPickerNames({
+ connect: () => api.connectDb(draftConfig),
+ listNames: () => loadVisibleDatabaseNames(draftId, draftConfig),
+ disconnect: () => api.disconnectDb(draftId),
+ queryTimeoutSecs: form.value.query_timeout_secs,
+ });
} catch {
// silently fail
} finally {
- await api.disconnectDb(draftId).catch(() => undefined);
isLoadingVisibleDatabases.value = false;
}
}
@@ -5727,8 +5731,12 @@ async function openVisibleDatabasesPicker() {
id: draftId,
one_time: true,
};
- await api.connectDb(draftConfig);
- const names = await loadVisibleDatabaseNames(draftId, draftConfig);
+ const names = await loadVisibleDatabasesPickerNames({
+ connect: () => api.connectDb(draftConfig),
+ listNames: () => loadVisibleDatabaseNames(draftId, draftConfig),
+ disconnect: () => api.disconnectDb(draftId),
+ queryTimeoutSecs: form.value.query_timeout_secs,
+ });
visibleDatabaseNames.value = names;
visibleDatabaseShowSystem.value = false;
const configuredSchemas = visibleSchemaObjectSelection.value;
@@ -5744,7 +5752,6 @@ async function openVisibleDatabasesPicker() {
testResult.value = { ok: false, message: visibleDatabaseError.value };
showVisibleDatabasesDialog.value = true;
} finally {
- await api.disconnectDb(draftId).catch(() => undefined);
isLoadingVisibleDatabases.value = false;
}
}
diff --git a/apps/desktop/src/lib/__tests__/connection/visibleDatabasesPickerLoad.spec.ts b/apps/desktop/src/lib/__tests__/connection/visibleDatabasesPickerLoad.spec.ts
new file mode 100644
index 0000000000..8bd0c78f1c
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/connection/visibleDatabasesPickerLoad.spec.ts
@@ -0,0 +1,70 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { loadVisibleDatabasesPickerNames } from "@/lib/connection/visibleDatabasesPickerLoad";
+
+describe("loadVisibleDatabasesPickerNames", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("returns the listed names and always releases the draft connection", async () => {
+ const disconnect = vi.fn(async () => {});
+
+ const names = await loadVisibleDatabasesPickerNames({
+ connect: vi.fn(async () => {}),
+ listNames: vi.fn(async () => ["0", "1", "2"]),
+ disconnect,
+ queryTimeoutSecs: 10,
+ });
+
+ expect(names).toEqual(["0", "1", "2"]);
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps the listed names when releasing the draft fails", async () => {
+ const disconnect = vi.fn(async () => {
+ throw new Error("Redis connection failed: connection reset");
+ });
+
+ await expect(
+ loadVisibleDatabasesPickerNames({
+ connect: vi.fn(async () => {}),
+ listNames: vi.fn(async () => ["0"]),
+ disconnect,
+ queryTimeoutSecs: 10,
+ }),
+ ).resolves.toEqual(["0"]);
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ // #12426:服务端接受了连接探测,但 CONFIG/INFO 一直不回答时,选择器必须结束等待。
+ it("stops waiting and reports a timeout when the list request never answers", async () => {
+ vi.useFakeTimers();
+ const disconnect = vi.fn(async () => {});
+ const pending = loadVisibleDatabasesPickerNames({
+ connect: vi.fn(async () => {}),
+ listNames: () => new Promise<string[]>(() => {}),
+ disconnect,
+ });
+ const assertion = expect(pending).rejects.toThrow(/timed out/i);
+
+ await vi.advanceTimersByTimeAsync(40_000);
+ await assertion;
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it("bounds the draft connect step too", async () => {
+ vi.useFakeTimers();
+ const listNames = vi.fn(async () => ["0"]);
+ const pending = loadVisibleDatabasesPickerNames({
+ connect: () => new Promise<void>(() => {}),
+ listNames,
+ disconnect: vi.fn(async () => {}),
+ queryTimeoutSecs: 0,
+ });
+ const assertion = expect(pending).rejects.toThrow(/timed out/i);
+
+ await vi.advanceTimersByTimeAsync(61_000);
+ await assertion;
+ expect(listNames).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/lib/connection/visibleDatabasesPickerLoad.ts b/apps/desktop/src/lib/connection/visibleDatabasesPickerLoad.ts
new file mode 100644
index 0000000000..ff8bf82a20
--- /dev/null
+++ b/apps/desktop/src/lib/connection/visibleDatabasesPickerLoad.ts
@@ -0,0 +1,35 @@
+import { metadataLoadBudgetMs, waitForMetadata } from "@/lib/metadata/metadataLoadBudget";
+
+export interface VisibleDatabasesPickerDraft {
+ /** Opens the one-time draft connection the picker lists its objects from. */
+ connect: () => Promise<unknown>;
+ /** Reads the visible object names (databases or schemas) through that draft. */
+ listNames: () => Promise<string[]>;
+ /** Releases the draft connection; best-effort, it never blocks the dialog. */
+ disconnect: () => Promise<void>;
+ /** Effective query timeout of the draft, used to derive the local load budget. */
+ queryTimeoutSecs?: number | undefined;
+}
+
+/**
+ * Loads the names shown by the connection dialog's "visible objects" picker.
+ *
+ * Every step is bounded by the local metadata load budget, and releasing the draft
+ * connection is best-effort. A server (or a proxy in front of it) that answers the
+ * connection probe but stays silent for `CONFIG`/`INFO` used to leave the picker
+ * spinning with the rest of the dialog disabled, because nothing along this path
+ * cancelled the wait (#12426).
+ */
+export async function loadVisibleDatabasesPickerNames(draft: VisibleDatabasesPickerDraft): Promise<string[]> {
+ const budgetMs = metadataLoadBudgetMs(draft.queryTimeoutSecs);
+ try {
+ await waitForMetadata(draft.connect(), budgetMs);
+ return await waitForMetadata(draft.listNames(), budgetMs);
+ } finally {
+ try {
+ void draft.disconnect().catch(() => undefined);
+ } catch {
+ // A synchronous teardown failure must not replace the load result.
+ }
+ }
+}
diff --git a/crates/dbx-driver-redis/src/lib.rs b/crates/dbx-driver-redis/src/lib.rs
index 841d128774..84466888ee 100644
--- a/crates/dbx-driver-redis/src/lib.rs
+++ b/crates/dbx-driver-redis/src/lib.rs
@@ -1469,13 +1469,47 @@ where
}
pub async fn list_databases<C>(con: &mut C) -> Result<Vec<RedisDatabaseInfo>, String>
+where
+ C: ConnectionLike + Send + Sync + Unpin,
+{
+ list_databases_with_timeout(con, connection_timeout()).await
+}
+
+/// Lists the logical databases of a standalone Redis connection.
+///
+/// Both metadata probes are bounded. A server (or a proxy in front of it) that accepts the
+/// connection and answers `PING` but never replies to `CONFIG GET databases` / `INFO keyspace`
+/// used to keep the caller waiting forever: the connection dialog's database picker stayed in
+/// its loading state with the rest of the dialog disabled (#12426). A probe that never answers
+/// now reports a timeout — the call stops there instead of issuing another command, because a
+/// multiplexed connection cannot answer later requests while a reply is still outstanding.
+pub async fn list_databases_with_timeout<C>(con: &mut C, timeout: Duration) -> Result<Vec<RedisDatabaseInfo>, String>
where
C: ConnectionLike + Send + Sync + Unpin,
{
let configured_count =
- redis::cmd("CONFIG").arg("GET").arg("databases").query_async(con).await.ok().and_then(parse_database_count);
+ match tokio::time::timeout(timeout, redis::cmd("CONFIG").arg("GET").arg("databases").query_async(con)).await {
+ Ok(Ok(value)) => parse_database_count(value),
+ // Renamed or denied CONFIG keeps the DBX default, as before.
+ Ok(Err(_)) => None,
+ Err(_) => {
+ return Err(format!(
+ "Redis database list timed out ({}s): the server did not answer CONFIG GET databases",
+ timeout.as_secs()
+ ))
+ }
+ };
- let keyspace_db_infos = list_keyspace_databases(con).await.unwrap_or_default();
+ let keyspace_db_infos = match tokio::time::timeout(timeout, list_keyspace_databases(con)).await {
+ Ok(Ok(infos)) => infos,
+ Ok(Err(_)) => Vec::new(),
+ Err(_) => {
+ return Err(format!(
+ "Redis database list timed out ({}s): the server did not answer INFO keyspace",
+ timeout.as_secs()
+ ))
+ }
+ };
let database_count = configured_count.unwrap_or(DEFAULT_REDIS_DATABASES);
let max_db = keyspace_db_infos.iter().map(|db| db.db).max().map(|db| db + 1).unwrap_or(0);
let visible_count = database_count.max(max_db).max(1);
@@ -6470,6 +6504,138 @@ mod tests {
assert!(error.contains("connection timed out"));
}
+ #[derive(Clone, Copy)]
+ enum MetadataReply {
+ Answer,
+ Deny,
+ /// Accept the command and keep the socket open without ever answering it.
+ Silent,
+ }
+
+ /// Minimal RESP server for the standalone database-list probes: it answers the
+ /// connection handshake and `PING`, and follows the script for the two metadata
+ /// commands.
+ async fn database_list_mock(
+ config: MetadataReply,
+ info: MetadataReply,
+ ) -> (std::net::SocketAddr, tokio::task::JoinHandle<()>) {
+ use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move {
+ while let Ok((stream, _)) = listener.accept().await {
+ let (reader, mut writer) = stream.into_split();
+ let mut reader = BufReader::new(reader);
+ loop {
+ let mut line = String::new();
+ if reader.read_line(&mut line).await.unwrap_or(0) == 0 {
+ break;
+ }
+ let count: usize = line.trim().strip_prefix('*').unwrap().parse().unwrap();
+ let mut args = Vec::new();
+ for _ in 0..count {
+ line.clear();
+ reader.read_line(&mut line).await.unwrap();
+ let len: usize = line.trim().strip_prefix('$').unwrap().parse().unwrap();
+ let mut arg = vec![0; len + 2];
+ reader.read_exact(&mut arg).await.unwrap();
+ arg.truncate(len);
+ args.push(arg);
+ }
+ let command = args[0].to_ascii_uppercase();
+ match command.as_slice() {
+ b"PING" => writer.write_all(b"+PONG\r\n").await.unwrap(),
+ b"CONFIG" => match config {
+ MetadataReply::Answer => {
+ writer.write_all(b"*2\r\n$9\r\ndatabases\r\n$1\r\n4\r\n").await.unwrap();
+ }
+ MetadataReply::Deny => {
+ writer
+ .write_all(b"-NOPERM this user has no permissions to run the 'config' command\r\n")
+ .await
+ .unwrap();
+ }
+ MetadataReply::Silent => {
+ tokio::time::sleep(Duration::from_secs(30)).await;
+ break;
+ }
+ },
+ b"INFO" => match info {
+ MetadataReply::Answer => {
+ let keyspace = b"# Keyspace\r\ndb2:keys=5,expires=0,avg_ttl=0\r\n";
+ writer.write_all(format!("${}\r\n", keyspace.len()).as_bytes()).await.unwrap();
+ writer.write_all(keyspace).await.unwrap();
+ writer.write_all(b"\r\n").await.unwrap();
+ }
+ MetadataReply::Deny => {
+ writer
+ .write_all(b"-NOPERM this user has no permissions to run the 'info' command\r\n")
+ .await
+ .unwrap();
+ }
+ MetadataReply::Silent => {
+ tokio::time::sleep(Duration::from_secs(30)).await;
+ break;
+ }
+ },
+ _ => writer.write_all(b"+OK\r\n").await.unwrap(),
+ }
+ }
+ }
+ });
+ (address, server)
+ }
+
+ #[tokio::test]
+ async fn database_list_uses_the_configured_count_with_keyspace_counts() {
+ let (address, server) = database_list_mock(MetadataReply::Answer, MetadataReply::Answer).await;
+ let mut con = super::connect(&format!("redis://{address}"), Duration::from_secs(3)).await.unwrap();
+
+ let databases = super::list_databases_with_timeout(&mut con, Duration::from_millis(200)).await.unwrap();
+
+ assert_eq!(databases.len(), 4);
+ assert_eq!(databases[2].keys, Some(5));
+ assert_eq!(databases[0].keys, None);
+ server.abort();
+ }
+
+ // 既有的降级路径:CONFIG 被改名/拒绝时用 DBX 默认值,键数量仍来自 INFO keyspace。
+ #[tokio::test]
+ async fn database_list_degrades_when_the_config_probe_is_denied() {
+ let (address, server) = database_list_mock(MetadataReply::Deny, MetadataReply::Answer).await;
+ let mut con = super::connect(&format!("redis://{address}"), Duration::from_secs(3)).await.unwrap();
+
+ let databases = super::list_databases_with_timeout(&mut con, Duration::from_millis(200)).await.unwrap();
+
+ assert_eq!(databases.len(), 16);
+ assert_eq!(databases[2].keys, Some(5));
+ server.abort();
+ }
+
+ // #12426:服务端/代理不回答 CONFIG 时返回超时错误,而不是让选择器一直等待。
+ #[tokio::test]
+ async fn database_list_reports_a_timeout_when_the_config_probe_stays_silent() {
+ let (address, server) = database_list_mock(MetadataReply::Silent, MetadataReply::Answer).await;
+ let mut con = super::connect(&format!("redis://{address}"), Duration::from_secs(3)).await.unwrap();
+
+ let error = super::list_databases_with_timeout(&mut con, Duration::from_millis(200)).await.unwrap_err();
+
+ assert!(error.contains("CONFIG GET databases"), "{error}");
+ server.abort();
+ }
+
+ // #12426:INFO keyspace 一直不回答时返回超时错误,而不是无限等待。
+ #[tokio::test]
+ async fn database_list_reports_a_timeout_when_the_keyspace_probe_stays_silent() {
+ let (address, server) = database_list_mock(MetadataReply::Answer, MetadataReply::Silent).await;
+ let mut con = super::connect(&format!("redis://{address}"), Duration::from_secs(3)).await.unwrap();
+
+ let error = super::list_databases_with_timeout(&mut con, Duration::from_millis(200)).await.unwrap_err();
+
+ assert!(error.contains("INFO keyspace"), "{error}");
+ server.abort();
+ }
+
struct SentinelMockReply {
command: &'static str,
response: Vec<u8>,