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(connection): allow immediate reconnect after canceling high-latency connection
Moe.51693bf296d2
diff --git a/.gitignore b/.gitignoreindex 2daf81360e..b93f20db09 100644--- a/.gitignore+++ b/.gitignore@@ -61,4 +61,5 @@ portable/DBX_*_x64-portable.zip.agents/skills.pnpm-store/*-.dbx-web\ No newline at end of file+.dbx-web+_devdiff --git a/apps/desktop/src/stores/__tests__/connectionStore.timeout.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.timeout.spec.tsindex 8981bda53b..fb9d7e919f 100644--- a/apps/desktop/src/stores/__tests__/connectionStore.timeout.spec.ts+++ b/apps/desktop/src/stores/__tests__/connectionStore.timeout.spec.ts@@ -127,6 +127,7 @@ describe("connectionStore timeout recovery", () => {connectDb,deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),disconnectDb,+ listInstalledAgents: vi.fn().mockResolvedValue([]),saveConnections: vi.fn().mockResolvedValue(undefined),saveSidebarLayout: vi.fn().mockResolvedValue(undefined),}));@@ -189,6 +190,7 @@ describe("connectionStore timeout recovery", () => {connectDb,deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),disconnectDb,+ listInstalledAgents: vi.fn().mockResolvedValue([]),saveConnections: vi.fn().mockResolvedValue(undefined),saveSidebarLayout: vi.fn().mockResolvedValue(undefined),}));@@ -234,6 +236,204 @@ describe("connectionStore timeout recovery", () => {await firstEnsure;}, 10_000);+ it("starts a fresh root metadata load after canceling a pending connection", async () => {+ let connectCallCount = 0;+ const connectDb = vi.fn(() => {+ connectCallCount += 1;+ return connectCallCount === 1 ? new Promise<string>(() => undefined) : Promise.resolve("pg-1");+ });+ const disconnectDb = vi.fn().mockResolvedValue(undefined);+ const listDatabases = vi.fn().mockResolvedValue([{ name: "app" }]);++ vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));+ vi.doMock("@/lib/backend/api", () => ({+ connectDb,+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),+ disconnectDb,+ listDatabases,+ loadSchemaCache: vi.fn().mockResolvedValue(null),+ saveConnections: vi.fn().mockResolvedValue(undefined),+ saveSchemaCache: vi.fn().mockResolvedValue(undefined),+ saveSidebarLayout: vi.fn().mockResolvedValue(undefined),+ }));++ const { useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();+ const connection = postgresConnection({ connect_timeout_secs: 10 });+ store.connections = [connection];+ store.treeNodes = [+ {+ id: connection.id,+ label: connection.name,+ type: "connection",+ connectionId: connection.id,+ isLoading: false,+ children: [],+ },+ ];++ void store.loadDatabases(connection.id).catch(() => undefined);+ await vi.advanceTimersByTimeAsync(1);+ expect(connectDb).toHaveBeenCalledTimes(1);+ const firstAttempt = connectDb.mock.calls[0]?.[1];++ await expect(store.cancelConnecting(connection.id)).resolves.toBe(true);+ expect(disconnectDb).toHaveBeenCalledWith(connection.id, firstAttempt);+ expect(store.treeNodes[0]?.isLoading).toBe(false);++ await store.loadDatabases(connection.id);++ expect(connectDb).toHaveBeenCalledTimes(2);+ expect(connectDb.mock.calls[1]?.[1]).not.toBe(firstAttempt);+ expect(listDatabases).toHaveBeenCalledTimes(1);+ expect(store.connectedIds.has(connection.id)).toBe(true);+ expect(store.treeNodes[0]?.isExpanded).toBe(true);+ }, 10_000);++ it("allows reconnecting the same connection while a scoped disconnect is pending", async () => {+ let resolveDisconnect!: () => void;+ const connectDb = vi.fn().mockResolvedValue("pg-1");+ const disconnectDb = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ resolveDisconnect = resolve;+ }),+ );++ vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));+ vi.doMock("@/lib/backend/api", () => ({+ connectDb,+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),+ disconnectDb,+ saveConnections: vi.fn().mockResolvedValue(undefined),+ saveSidebarLayout: vi.fn().mockResolvedValue(undefined),+ }));++ const { useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();+ const connection = postgresConnection({ connect_timeout_secs: 10 });+ store.connections = [connection];+ store.treeNodes = [+ {+ id: connection.id,+ label: connection.name,+ type: "connection",+ connectionId: connection.id,+ isLoading: true,+ isExpanded: true,+ children: [],+ },+ ];++ await store.connect(connection);+ expect(store.connectedIds.has(connection.id)).toBe(true);+ const firstAttempt = connectDb.mock.calls[0]?.[1];++ const disconnect = store.disconnect(connection.id);+ expect(disconnectDb).toHaveBeenCalledWith(connection.id, firstAttempt);+ expect(store.connectedIds.has(connection.id)).toBe(false);+ expect(store.treeNodes[0]?.isLoading).toBe(false);+ expect(store.treeNodes[0]?.isExpanded).toBe(false);++ await store.connect(connection);+ expect(connectDb).toHaveBeenCalledTimes(2);+ expect(connectDb.mock.calls[1]?.[1]).not.toBe(firstAttempt);+ expect(store.connectedIds.has(connection.id)).toBe(true);++ resolveDisconnect();+ await disconnect;++ expect(store.connectedIds.has(connection.id)).toBe(true);+ expect(store.connectionErrors[connection.id]).toBeUndefined();+ }, 10_000);++ it("keeps a newer reconnect error when an older scoped disconnect finishes later", async () => {+ let resolveDisconnect!: () => void;+ let connectCallCount = 0;+ const connectDb = vi.fn(() => {+ connectCallCount += 1;+ return connectCallCount === 1 ? Promise.resolve("pg-1") : Promise.reject(new Error("reconnect failed"));+ });+ const disconnectDb = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ resolveDisconnect = resolve;+ }),+ );++ vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));+ vi.doMock("@/lib/backend/api", () => ({+ connectDb,+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),+ disconnectDb,+ listInstalledAgents: vi.fn().mockResolvedValue([]),+ saveConnections: vi.fn().mockResolvedValue(undefined),+ saveSidebarLayout: vi.fn().mockResolvedValue(undefined),+ }));++ const { useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();+ const connection = postgresConnection({ connect_timeout_secs: 10 });+ store.connections = [connection];++ await store.connect(connection);+ const firstAttempt = connectDb.mock.calls[0]?.[1];++ const disconnect = store.disconnect(connection.id);+ expect(disconnectDb).toHaveBeenCalledWith(connection.id, firstAttempt);++ await expect(store.connect(connection)).rejects.toThrow("reconnect failed");+ expect(store.connectionErrors[connection.id]).toBe("reconnect failed");++ resolveDisconnect();+ await disconnect;++ expect(store.connectedIds.has(connection.id)).toBe(false);+ expect(store.connectionErrors[connection.id]).toBe("reconnect failed");+ }, 10_000);++ it("scopes a normal disconnect to the active connection attempt when one is running", async () => {+ let resolveConnect!: (connectionId: string) => void;+ const connectDb = vi.fn(+ () =>+ new Promise<string>((resolve) => {+ resolveConnect = resolve;+ }),+ );+ const disconnectDb = vi.fn().mockResolvedValue(undefined);++ vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));+ vi.doMock("@/lib/backend/api", () => ({+ connectDb,+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),+ disconnectDb,+ saveConnections: vi.fn().mockResolvedValue(undefined),+ saveSidebarLayout: vi.fn().mockResolvedValue(undefined),+ }));++ const { CONNECTION_ATTEMPT_CANCELLED_MESSAGE, useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();+ const connection = postgresConnection({ connect_timeout_secs: 10 });+ store.connections = [connection];++ const connect = store.connect(connection).catch((error) => error);+ await vi.advanceTimersByTimeAsync(1);+ const activeAttempt = connectDb.mock.calls[0]?.[1];++ await store.disconnect(connection.id);+ expect(disconnectDb).toHaveBeenCalledWith(connection.id, activeAttempt);+ expect(store.connectedIds.has(connection.id)).toBe(false);++ resolveConnect(connection.id);+ await vi.advanceTimersByTimeAsync(1);+ const error = await connect;++ expect(error).toBeInstanceOf(Error);+ expect(error.message).toContain(CONNECTION_ATTEMPT_CANCELLED_MESSAGE);+ expect(disconnectDb).toHaveBeenLastCalledWith(connection.id, activeAttempt);+ expect(store.connectedIds.has(connection.id)).toBe(false);+ }, 10_000);+it("cleans up backend state when a cancelled connection later succeeds", async () => {let resolveConnect!: (connectionId: string) => void;const connectDb = vi.fn(diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.tsindex f760c2bbc7..4345ebbb6b 100644--- a/apps/desktop/src/stores/connectionStore.ts+++ b/apps/desktop/src/stores/connectionStore.ts@@ -305,9 +305,12 @@ export const useConnectionStore = defineStore("connection", () => {};const connectInFlight = new Map<string, Promise<void>>();const disconnectInFlight = new Map<string, Promise<void>>();+ const disconnectInFlightScoped = new Map<string, boolean>();const cancelDisconnectInFlight = new Map<string, Promise<void>>();const activeLocalConnectionAttempts = new Map<string, number>();const cancelledLocalConnectionAttempts = new Map<string, Set<number>>();+ const successfulLocalConnectionAttempts = new Map<string, number>();+ const connectionStateRevisions = new Map<string, number>();let nextLocalConnectionAttempt = 0;let beforeConnectHandler: BeforeConnectHandler | null = null;let initFromDiskPromise: Promise<void> | null = null;@@ -379,6 +382,7 @@ export const useConnectionStore = defineStore("connection", () => {function beginLocalConnectionAttempt(connectionId: string): number {const attempt = ++nextLocalConnectionAttempt;+ bumpConnectionStateRevision(connectionId);activeLocalConnectionAttempts.set(connectionId, attempt);connectingIds.value.add(connectionId);const node = findNode(treeNodes.value, connectionId);@@ -386,6 +390,24 @@ export const useConnectionStore = defineStore("connection", () => {return attempt;}+ function markSuccessfulLocalConnectionAttempt(connectionId: string, attempt: number) {+ successfulLocalConnectionAttempts.set(connectionId, attempt);+ }++ function forgetSuccessfulLocalConnectionAttempt(connectionId: string) {+ successfulLocalConnectionAttempts.delete(connectionId);+ }++ function bumpConnectionStateRevision(connectionId: string): number {+ const revision = (connectionStateRevisions.get(connectionId) ?? 0) + 1;+ connectionStateRevisions.set(connectionId, revision);+ return revision;+ }++ function isCurrentConnectionStateRevision(connectionId: string, revision: number): boolean {+ return connectionStateRevisions.get(connectionId) === revision;+ }+function isCurrentLocalConnectionAttempt(connectionId: string, attempt: number): boolean {return activeLocalConnectionAttempts.get(connectionId) === attempt;}@@ -421,41 +443,54 @@ export const useConnectionStore = defineStore("connection", () => {activeLocalConnectionAttempts.delete(connectionId);connectingIds.value.delete(connectionId);clearConnectionNodeLoading(connectionId);+ clearConnectionRootMetadataLoad(connectionId);connectInFlight.delete(connectionId);return true;}- function getDisconnectInFlight(connectionId: string): Promise<void> | undefined {- return disconnectInFlight.get(connectionId);+ function clearConnectionRootMetadataLoad(connectionId: string) {+ metadataLoadCoordinator.clear({+ kind: "connection-databases",+ connectionId,+ driverProfile: metadataDriverProfile(getConfig(connectionId)),+ });}- async function waitForDisconnectInFlight(connectionId: string): Promise<void> {- const pending = getDisconnectInFlight(connectionId);+ function getBlockingDisconnectInFlight(connectionId: string): Promise<void> | undefined {+ return disconnectInFlightScoped.get(connectionId) ? undefined : disconnectInFlight.get(connectionId);+ }++ async function waitForBlockingDisconnectInFlight(connectionId: string): Promise<void> {+ const pending = getBlockingDisconnectInFlight(connectionId);if (pending) await pending;}- function trackDisconnectRequest(connectionId: string, request: Promise<void>): Promise<void> {- const tracked = request+ function trackDisconnectRequest(connectionId: string, request: Promise<void>, scoped: boolean): Promise<void> {+ const bounded = withDisconnectRequestTimeout(connectionId, request);+ const tracked = bounded.catch((error) => {console.warn("[DBX][connection:disconnect-error]", { connectionId, error });}).finally(() => {if (disconnectInFlight.get(connectionId) === tracked) {disconnectInFlight.delete(connectionId);+ disconnectInFlightScoped.delete(connectionId);}});disconnectInFlight.set(connectionId, tracked);- return withDisconnectRequestTimeout(connectionId, request);+ disconnectInFlightScoped.set(connectionId, scoped);+ return bounded;}function startDisconnectRequest(connectionId: string): Promise<void> {+ const clientAttempt = activeLocalConnectionAttempts.get(connectionId) ?? successfulLocalConnectionAttempts.get(connectionId);let request: Promise<void>;try {- request = api.disconnectDb(connectionId);+ request = api.disconnectDb(connectionId, clientAttempt);} catch (error) {request = Promise.reject(error);}- return trackDisconnectRequest(connectionId, request);+ return trackDisconnectRequest(connectionId, request, clientAttempt != null);}function cancelDisconnectKey(connectionId: string, attempt: number): string {@@ -1696,7 +1731,7 @@ export const useConnectionStore = defineStore("connection", () => {async function connect(config: ConnectionConfig) {config = normalizeConnection(config);- if (getDisconnectInFlight(config.id)) await waitForDisconnectInFlight(config.id);+ if (getBlockingDisconnectInFlight(config.id)) await waitForBlockingDisconnectInFlight(config.id);const localAttempt = beginLocalConnectionAttempt(config.id);try {await beforeConnectHandler?.(config);@@ -1707,6 +1742,8 @@ export const useConnectionStore = defineStore("connection", () => {await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id);activeConnectionId.value = id;connectedIds.value.add(id);+ if (id !== config.id) markSuccessfulLocalConnectionAttempt(config.id, localAttempt);+ markSuccessfulLocalConnectionAttempt(id, localAttempt);markConnectionHealthChecked(id);clearConnectionError(config.id);if (id !== config.id) clearConnectionError(id);@@ -1760,11 +1797,26 @@ export const useConnectionStore = defineStore("connection", () => {}async function disconnect(connectionId: string) {+ const stateRevision = bumpConnectionStateRevision(connectionId);const disconnectRequest = startDisconnectRequest(connectionId);cancelLocalConnectionAttempt(connectionId);const shouldRemoveOneTimeConnection = getConfig(connectionId)?.one_time === true;- await disconnectRequest;- clearConnectionError(connectionId);++ connectedIds.value.delete(connectionId);+ forgetSuccessfulLocalConnectionAttempt(connectionId);+ clearConnectionHealthCheck(connectionId);+ const node = findNode(treeNodes.value, connectionId);+ if (node) {+ node.isLoading = false;+ node.isExpanded = false;+ node.children = [];+ }+ clearConnectionRootMetadataLoad(connectionId);+ clearLoadedChildrenCache(connectionId);+ if (activeConnectionId.value === connectionId) {+ activeConnectionId.value = null;+ }+ invalidateCompletionCache(connectionId);const { useQueryStore } = await import("@/stores/queryStore");const queryStore = useQueryStore();switch (settingsStore.editorSettings.disconnectTabHandlingMode) {@@ -1778,20 +1830,11 @@ export const useConnectionStore = defineStore("connection", () => {queryStore.rollbackConnectionTransactions(connectionId);break;}- connectedIds.value.delete(connectionId);- clearConnectionHealthCheck(connectionId);- const node = findNode(treeNodes.value, connectionId);- if (node) {- node.isLoading = false;- node.isExpanded = false;- node.children = [];- }- clearLoadedChildrenCache(connectionId);- if (activeConnectionId.value === connectionId) {- activeConnectionId.value = null;+ await disconnectRequest;+ if (isCurrentConnectionStateRevision(connectionId, stateRevision)) {+ clearConnectionError(connectionId);}- invalidateCompletionCache(connectionId);- if (shouldRemoveOneTimeConnection) {+ if (shouldRemoveOneTimeConnection && isCurrentConnectionStateRevision(connectionId, stateRevision)) {await removeConnection(connectionId);}}@@ -1845,7 +1888,7 @@ export const useConnectionStore = defineStore("connection", () => {recordConnectionError(connectionId, error);throw error;}- if (getDisconnectInFlight(connectionId)) await waitForDisconnectInFlight(connectionId);+ if (getBlockingDisconnectInFlight(connectionId)) await waitForBlockingDisconnectInFlight(connectionId);const existingConnect = connectInFlight.get(connectionId);if (existingConnect) {await existingConnect;@@ -1860,6 +1903,7 @@ export const useConnectionStore = defineStore("connection", () => {await syncMongoLegacyDriverFallback(connectionId, config);await ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId, localAttempt, id);connectedIds.value.add(connectionId);+ markSuccessfulLocalConnectionAttempt(connectionId, localAttempt);markConnectionHealthChecked(connectionId);activeConnectionId.value = connectionId;clearConnectionError(connectionId);