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。

feat(connection): add connection attempt cancellation

Moe.8a1a7919278a
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index 1c5fa66781..fa51fcb870 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -16,7 +16,7 @@ import { Switch } from "@/components/ui/switch";
import type { ConnectionConfig, DatabaseType, HttpTunnelConfig, JdbcDriverInfo, JdbcMavenBundleInfo, ProxyTunnelConfig, SshTunnelConfig, TransportLayerConfig } from "@/types/database";
import type { MqAdminConfig, MqAuth, MqSystemKind } from "@/types/mq";
import type { NacosAdminConfig, NacosAuthConfig } from "@/types/nacos";
-import { useConnectionStore } from "@/stores/connectionStore";
+import { CONNECTION_ATTEMPT_CANCELLED_MESSAGE, useConnectionStore } from "@/stores/connectionStore";
import { REDIS_SCAN_PAGE_SIZE_DEFAULT, REDIS_SCAN_PAGE_SIZE_MIN, REDIS_SCAN_PAGE_SIZE_MAX, REDIS_SCAN_PAGE_SIZE_OPTIONS } from "@/lib/redis/redisKeyPattern";
import { useSettingsStore } from "@/stores/settingsStore";
import { useToast } from "@/composables/useToast";
@@ -2991,8 +2991,10 @@ async function save() {
emit("connectSucceeded", config.name);
})
.catch((e: any) => {
+ const message = String(e?.message || e);
+ if (message.includes(CONNECTION_ATTEMPT_CANCELLED_MESSAGE)) return;
if (config.one_time) void store.removeConnection(config.id);
- emit("connectFailed", mongodbAuthFailureHint(String(e?.message || e)));
+ emit("connectFailed", mongodbAuthFailureHint(message));
});
return;
}
diff --git a/apps/desktop/src/components/sidebar/TreeItem.vue b/apps/desktop/src/components/sidebar/TreeItem.vue
index 0a3c41d718..f71e0e7dc0 100644
--- a/apps/desktop/src/components/sidebar/TreeItem.vue
+++ b/apps/desktop/src/components/sidebar/TreeItem.vue
@@ -58,9 +58,10 @@ import {
Info,
Archive,
Square,
+ X,
} from "@lucide/vue";
import CustomContextMenu from "@/components/ui/CustomContextMenu.vue";
-import { useConnectionStore } from "@/stores/connectionStore";
+import { CONNECTION_ATTEMPT_CANCELLED_MESSAGE, useConnectionStore } from "@/stores/connectionStore";
import { useQueryStore } from "@/stores/queryStore";
import { useSettingsStore } from "@/stores/settingsStore";
import { useSavedSqlStore } from "@/stores/savedSqlStore";
@@ -512,8 +513,7 @@ function isTooltipDisabled(): boolean {
async function toggle() {
const node = props.node;
if (node.isLoading) {
- if (node.type !== "connection") return;
- node.isLoading = false;
+ return;
}
emit("search-toggle", node);
const wasExpanded = !!node.isExpanded;
@@ -651,6 +651,7 @@ async function toggle() {
} catch (e: any) {
if (!wasExpanded) node.isExpanded = false;
const errMsg = e?.message || String(e);
+ if (errMsg.includes(CONNECTION_ATTEMPT_CANCELLED_MESSAGE)) return;
toast(t("connection.connectFailed", { message: translateBackendError(t, errMsg) }), 5000);
if (errMsg.includes("driver is not installed") || errMsg.includes("is not installed")) {
window.dispatchEvent(new Event("dbx-open-driver-store"));
@@ -3469,6 +3470,16 @@ async function disconnectConnection() {
}
}
+async function cancelConnectionAttempt() {
+ if (!props.node.connectionId) return;
+ try {
+ const cancelled = await connectionStore.cancelConnecting(props.node.connectionId);
+ if (cancelled) toast(t("connection.connectCancelled"), 2000);
+ } catch (e: any) {
+ toast(t("connection.saveFailed", { message: e?.message || String(e) }), 5000);
+ }
+}
+
async function closeDatabaseConnection() {
const node = props.node;
if (node.type !== "database" || !node.connectionId || node.database == null) return;
@@ -3640,6 +3651,7 @@ const tableComment = computed(() =>
);
const paddingLeft = computed(() => treeItemPaddingLeft(props.depth));
const isConnected = computed(() => props.node.type === "connection" && !!props.node.connectionId && connectionStore.connectedIds.has(props.node.connectionId));
+const isConnecting = computed(() => props.node.type === "connection" && !!props.node.connectionId && connectionStore.connectingIds.has(props.node.connectionId));
const isConnectionReadonly = computed(() => props.node.type === "connection" && !!props.node.connectionId && (connectionStore.getConfig(props.node.connectionId)?.read_only ?? false));
const isOpenedDatabase = computed(() => isSidebarDatabaseOpened(props.node, connectionStore.isTreeNodeChildrenLoaded));
const showsDatabaseOpenIndicator = computed(() => props.node.type === "database" && (isOpenedDatabase.value || (!!props.node.connectionId && props.node.database != null && queryStore.isDatabaseOpen(props.node.connectionId, props.node.database))));
@@ -4095,7 +4107,9 @@ function treeItemMenuItems(): ContextMenuItem[] {
// 2. Connection
if (node.type === "connection") {
- if (!isConnected.value) {
+ if (isConnecting.value) {
+ items.push({ label: t("connection.cancelConnecting"), action: cancelConnectionAttempt, icon: X });
+ } else if (!isConnected.value) {
items.push({ label: t("contextMenu.openConnection"), action: toggle, icon: Plug });
} else {
items.push({ label: t("contextMenu.closeConnection"), action: disconnectConnection, icon: Unplug });
@@ -4712,11 +4726,22 @@ function treeItemMenuItems(): ContextMenuItem[] {
<Badge v-if="isConnectionReadonly" variant="secondary" class="h-4 px-1.5 text-[10px] gap-0.5"><Lock class="w-2.5 h-2.5" />{{ t("connection.readOnlyBadge") }}</Badge>
<ConnectionErrorIndicator v-if="node.type === 'connection'" :connection-id="node.connectionId" trigger-class="h-4 w-4" />
<Pin v-if="isPinned" class="w-3 h-3 shrink-0 text-primary fill-current" aria-hidden="true" />
+ <button
+ v-if="isConnecting"
+ type="button"
+ class="ml-auto flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-secondary/45 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ :aria-label="t('connection.cancelConnecting')"
+ :title="t('connection.cancelConnecting')"
+ @mousedown.stop
+ @click.stop="cancelConnectionAttempt"
+ >
+ <X class="h-3 w-3" />
+ </button>
<button
v-if="node.type === 'connection'"
type="button"
- class="ml-auto flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground/55 opacity-0 transition-colors transition-opacity hover:bg-secondary/45 hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/sidebar-row:opacity-100"
- :class="{ 'opacity-100': isConnectionSelectionChecked || connectionStore.connectionMultiSelectActive }"
+ class="flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground/55 opacity-0 transition-colors transition-opacity hover:bg-secondary/45 hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/sidebar-row:opacity-100"
+ :class="[{ 'opacity-100': isConnectionSelectionChecked || connectionStore.connectionMultiSelectActive }, isConnecting ? '' : 'ml-auto']"
:aria-label="isConnectionSelectionChecked ? t('connectionGroup.deselectConnection') : t('connectionGroup.selectConnection')"
@mousedown.stop
@click="toggleConnectionMultiSelection"
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 251319a5f5..5b38b21268 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -413,6 +413,8 @@ export default {
colorBlue: "Blue",
colorPurple: "Purple",
colorCustom: "Custom color",
+ cancelConnecting: "Cancel connecting",
+ connectCancelled: "Connection cancelled",
},
editor: {
pressToExecute: "Press {mod}+Enter to execute",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 7b0600d3f6..943fa4415f 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -406,6 +406,8 @@ export default withEnglishFallback({
colorBlue: "Azul",
colorPurple: "Morado",
colorCustom: "Color personalizado",
+ cancelConnecting: "Cancelar conexión",
+ connectCancelled: "Conexión cancelada",
},
editor: {
pressToExecute: "Presiona {mod}+Enter para ejecutar",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index f09f8cf007..05a49ee3f2 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -404,6 +404,8 @@ export default withEnglishFallback({
colorBlue: "Blu",
colorPurple: "Viola",
colorCustom: "Colore personalizzato",
+ cancelConnecting: "Annulla connessione",
+ connectCancelled: "Connessione annullata",
},
editor: {
pressToExecute: "Premi {mod}+Enter per eseguire",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 7925095211..6d7ce1a9cc 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -404,6 +404,8 @@ export default withEnglishFallback({
zookeeperCreateModeEphemeral: "エフェメラル",
zookeeperCreateModePersistentSequential: "永続順序",
zookeeperCreateModeEphemeralSequential: "エフェメラル順序",
+ cancelConnecting: "接続をキャンセル",
+ connectCancelled: "接続がキャンセルされました",
},
editor: {
pressToExecute: "{mod}+Enter で実行",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 9fe248abdf..6c22be12e9 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -405,6 +405,8 @@ export default withEnglishFallback({
colorBlue: "Azul",
colorPurple: "Roxo",
colorCustom: "Cor personalizada",
+ cancelConnecting: "Cancelar conexão",
+ connectCancelled: "Conexão cancelada",
},
editor: {
pressToExecute: "Pressione {mod}+Enter para executar",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 8d01dc901c..97bf036486 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -307,6 +307,8 @@ export default withEnglishFallback({
editTitle: "编辑连接",
testSuccess: "连接成功",
connecting: "正在连接 {name}...",
+ cancelConnecting: "取消连接",
+ connectCancelled: "连接已取消",
connectSuccess: "已连接 {name}",
connectFailed: "连接失败:{message}",
driverNotInstalled: "{driver} 驱动未安装,请在驱动管理器中安装。",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 7a093b181d..928c0539a7 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -405,6 +405,8 @@ export default withEnglishFallback({
colorBlue: "藍色",
colorPurple: "紫色",
colorCustom: "自訂顏色",
+ cancelConnecting: "取消連接",
+ connectCancelled: "連接已取消",
},
editor: {
pressToExecute: "按 {mod}+Enter 執行查詢",
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index 1016504294..2b087c77b1 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -197,16 +197,16 @@ export async function testConnection(config: ConnectionConfig): Promise<string>
return post("/api/connection/test", { config });
}
-export async function connectDb(config: ConnectionConfig): Promise<string> {
- return post("/api/connection/connect", { config });
+export async function connectDb(config: ConnectionConfig, clientAttempt?: number): Promise<string> {
+ return post("/api/connection/connect", { config, clientAttempt });
}
export async function connectionFinalProxyPort(config: ConnectionConfig): Promise<number> {
return post("/api/connection/final-proxy-port", { config });
}
-export async function disconnectDb(connectionId: string): Promise<void> {
- return post("/api/connection/disconnect", { connectionId });
+export async function disconnectDb(connectionId: string, clientAttempt?: number): Promise<void> {
+ return post("/api/connection/disconnect", { connectionId, clientAttempt });
}
export async function checkConnectionHealth(connectionId: string): Promise<void> {
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 9eb7ea0e23..5ddbd8ea5f 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -521,16 +521,16 @@ export async function testConnection(config: ConnectionConfig): Promise<string>
return invoke("test_connection", { config });
}
-export async function connectDb(config: ConnectionConfig): Promise<string> {
- return invoke("connect_db", { config });
+export async function connectDb(config: ConnectionConfig, clientAttempt?: number): Promise<string> {
+ return invoke("connect_db", { config, clientAttempt });
}
export async function connectionFinalProxyPort(config: ConnectionConfig): Promise<number> {
return invoke("connection_final_proxy_port", { config });
}
-export async function disconnectDb(connectionId: string): Promise<void> {
- return invoke("disconnect_db", { connectionId });
+export async function disconnectDb(connectionId: string, clientAttempt?: number): Promise<void> {
+ return invoke("disconnect_db", { connectionId, clientAttempt });
}
export async function checkConnectionHealth(connectionId: string): Promise<void> {
diff --git a/apps/desktop/src/stores/__tests__/connectionStore.timeout.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.timeout.spec.ts
index 06bbb5ea92..8981bda53b 100644
--- a/apps/desktop/src/stores/__tests__/connectionStore.timeout.spec.ts
+++ b/apps/desktop/src/stores/__tests__/connectionStore.timeout.spec.ts
@@ -63,7 +63,7 @@ describe("connectionStore timeout recovery", () => {
await ensure;
expect(checkConnectionHealth).toHaveBeenCalledWith(connection.id);
- expect(connectDb).toHaveBeenCalledWith(connection);
+ expect(connectDb).toHaveBeenCalledWith(connection, expect.any(Number));
expect(store.connectedIds.has(connection.id)).toBe(true);
}, 10_000);
@@ -117,4 +117,217 @@ describe("connectionStore timeout recovery", () => {
expect(error).toBeInstanceOf(Error);
expect(node.isLoading).toBe(false);
}, 10_000);
+
+ it("cancels an in-flight connection without leaving connected or loading state", async () => {
+ const connectDb = vi.fn(() => new Promise(() => undefined));
+ 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: 1 });
+ const node: TreeNode = {
+ id: connection.id,
+ label: connection.name,
+ type: "connection",
+ connectionId: connection.id,
+ isLoading: false,
+ children: [],
+ };
+ store.connections = [connection];
+ store.treeNodes = [node];
+
+ const ensure = store.ensureConnected(connection.id).catch((error) => error);
+ await vi.advanceTimersByTimeAsync(1);
+
+ expect(store.connectingIds.has(connection.id)).toBe(true);
+ expect(node.isLoading).toBe(true);
+
+ await expect(store.cancelConnecting(connection.id)).resolves.toBe(true);
+ expect(disconnectDb).toHaveBeenCalledWith(connection.id, expect.any(Number));
+ expect(store.connectingIds.has(connection.id)).toBe(false);
+ expect(store.connectedIds.has(connection.id)).toBe(false);
+ expect(store.connectionErrors[connection.id]).toBeUndefined();
+ expect(node.isLoading).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(3001);
+ const error = await ensure;
+
+ expect(error).toBeInstanceOf(Error);
+ expect(error.message).toContain(CONNECTION_ATTEMPT_CANCELLED_MESSAGE);
+ expect(store.connectingIds.has(connection.id)).toBe(false);
+ expect(store.connectedIds.has(connection.id)).toBe(false);
+ expect(store.connectionErrors[connection.id]).toBeUndefined();
+ expect(node.isLoading).toBe(false);
+ }, 10_000);
+
+ it("allows reconnecting the same connection while a scoped cancel is pending", async () => {
+ let resolveDisconnect!: () => void;
+ const pendingConnect = new Promise<string>(() => undefined);
+ let connectCallCount = 0;
+ const connectDb = vi.fn(() => {
+ connectCallCount += 1;
+ return connectCallCount === 1 ? pendingConnect : Promise.resolve("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: 1 });
+ store.connections = [connection];
+ store.treeNodes = [
+ {
+ id: connection.id,
+ label: connection.name,
+ type: "connection",
+ connectionId: connection.id,
+ isLoading: false,
+ children: [],
+ },
+ ];
+
+ const firstEnsure = store.ensureConnected(connection.id).catch((error) => error);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(connectDb).toHaveBeenCalledTimes(1);
+ const firstAttempt = connectDb.mock.calls[0]?.[1];
+
+ const cancel = store.cancelConnecting(connection.id);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(disconnectDb).toHaveBeenCalledWith(connection.id, firstAttempt);
+
+ const reconnect = store.ensureConnected(connection.id);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(connectDb).toHaveBeenCalledTimes(2);
+ expect(connectDb.mock.calls[1]?.[1]).not.toBe(firstAttempt);
+
+ resolveDisconnect();
+ await cancel;
+ await reconnect;
+
+ expect(connectDb).toHaveBeenCalledTimes(2);
+ expect(store.connectedIds.has(connection.id)).toBe(true);
+ expect(store.connectionErrors[connection.id]).toBeUndefined();
+
+ await vi.advanceTimersByTimeAsync(3001);
+ await firstEnsure;
+ }, 10_000);
+
+ it("cleans up backend state when a cancelled connection later succeeds", 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 ensure = store.ensureConnected(connection.id).catch((error) => error);
+ await vi.advanceTimersByTimeAsync(1);
+ const attempt = connectDb.mock.calls[0]?.[1];
+
+ await expect(store.cancelConnecting(connection.id)).resolves.toBe(true);
+ expect(disconnectDb).toHaveBeenCalledTimes(1);
+ expect(disconnectDb).toHaveBeenCalledWith(connection.id, attempt);
+
+ resolveConnect(connection.id);
+ await vi.advanceTimersByTimeAsync(1);
+ const error = await ensure;
+
+ expect(error).toBeInstanceOf(Error);
+ expect(error.message).toContain(CONNECTION_ATTEMPT_CANCELLED_MESSAGE);
+ expect(disconnectDb).toHaveBeenCalledTimes(2);
+ expect(disconnectDb).toHaveBeenLastCalledWith(connection.id, attempt);
+ expect(store.connectedIds.has(connection.id)).toBe(false);
+ expect(store.connectionErrors[connection.id]).toBeUndefined();
+ }, 10_000);
+
+ it("keeps errors from earlier cancelled attempts hidden after a second cancel", async () => {
+ let rejectFirstConnect!: (error: Error) => void;
+ let rejectSecondConnect!: (error: Error) => void;
+ let connectCallCount = 0;
+ const connectDb = vi.fn(() => {
+ connectCallCount += 1;
+ return new Promise<string>((_, reject) => {
+ if (connectCallCount === 1) {
+ rejectFirstConnect = reject;
+ } else {
+ rejectSecondConnect = reject;
+ }
+ });
+ });
+ 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 firstEnsure = store.ensureConnected(connection.id).catch((error) => error);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(connectDb).toHaveBeenCalledTimes(1);
+ await expect(store.cancelConnecting(connection.id)).resolves.toBe(true);
+
+ const secondEnsure = store.ensureConnected(connection.id).catch((error) => error);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(connectDb).toHaveBeenCalledTimes(2);
+ await expect(store.cancelConnecting(connection.id)).resolves.toBe(true);
+
+ rejectFirstConnect(new Error("first connection failed after cancel"));
+ const firstError = await firstEnsure;
+ expect(firstError).toBeInstanceOf(Error);
+ expect(firstError.message).toContain(CONNECTION_ATTEMPT_CANCELLED_MESSAGE);
+ expect(store.connectionErrors[connection.id]).toBeUndefined();
+
+ rejectSecondConnect(new Error("second connection failed after cancel"));
+ const secondError = await secondEnsure;
+ expect(secondError).toBeInstanceOf(Error);
+ expect(secondError.message).toContain(CONNECTION_ATTEMPT_CANCELLED_MESSAGE);
+ expect(store.connectionErrors[connection.id]).toBeUndefined();
+ }, 10_000);
});
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index 0a8c8fdec7..0e9ffad84b 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -174,6 +174,8 @@ interface PersistedTreeChildrenLoadResult {
type BeforeConnectHandler = (config: ConnectionConfig) => Promise<void>;
+export const CONNECTION_ATTEMPT_CANCELLED_MESSAGE = "Connection attempt was cancelled";
+
function redisDbLabel(db: number, _loadedKeyCount?: number, totalKeyCount?: number): string {
if (totalKeyCount == null) return `db${db}`;
return `db${db} (${totalKeyCount})`;
@@ -202,6 +204,7 @@ export const useConnectionStore = defineStore("connection", () => {
let agentDriversRefreshPromise: Promise<void> | null = null;
const loadedTreeNodeChildrenIds = ref<Set<string>>(new Set());
const connectionErrors = ref<Record<string, string>>({});
+ const connectingIds = ref<Set<string>>(new Set());
const editingConnectionId = ref<string | null>(null);
const newConnectionGroupId = ref<string | null>(null);
const completionTablesCache = ref<Record<string, SqlCompletionTable[]>>({});
@@ -274,6 +277,11 @@ export const useConnectionStore = defineStore("connection", () => {
let layoutPersistTimer: ReturnType<typeof setTimeout> | null = null;
const staleTreeRefreshIds = new Set<string>();
const connectInFlight = new Map<string, Promise<void>>();
+ const disconnectInFlight = new Map<string, Promise<void>>();
+ const cancelDisconnectInFlight = new Map<string, Promise<void>>();
+ const activeLocalConnectionAttempts = new Map<string, number>();
+ const cancelledLocalConnectionAttempts = new Map<string, Set<number>>();
+ let nextLocalConnectionAttempt = 0;
let beforeConnectHandler: BeforeConnectHandler | null = null;
let initFromDiskPromise: Promise<void> | null = null;
@@ -309,6 +317,146 @@ export const useConnectionStore = defineStore("connection", () => {
return connectionErrorMessage(error).includes(SUPERSEDED_CONNECTION_ATTEMPT_MESSAGE);
}
+ function isCancelledConnectionAttempt(error: unknown): boolean {
+ return connectionErrorMessage(error).includes(CONNECTION_ATTEMPT_CANCELLED_MESSAGE);
+ }
+
+ function beginLocalConnectionAttempt(connectionId: string): number {
+ const attempt = ++nextLocalConnectionAttempt;
+ activeLocalConnectionAttempts.set(connectionId, attempt);
+ connectingIds.value.add(connectionId);
+ const node = findNode(treeNodes.value, connectionId);
+ if (node) node.isLoading = true;
+ return attempt;
+ }
+
+ function isCurrentLocalConnectionAttempt(connectionId: string, attempt: number): boolean {
+ return activeLocalConnectionAttempts.get(connectionId) === attempt;
+ }
+
+ function isCancelledLocalConnectionAttempt(connectionId: string, attempt: number): boolean {
+ return cancelledLocalConnectionAttempts.get(connectionId)?.has(attempt) === true;
+ }
+
+ function getLocalConnectionAttempt(connectionId: string): number | undefined {
+ return activeLocalConnectionAttempts.get(connectionId);
+ }
+
+ function finishLocalConnectionAttempt(connectionId: string, attempt: number) {
+ if (isCancelledLocalConnectionAttempt(connectionId, attempt)) {
+ const attempts = cancelledLocalConnectionAttempts.get(connectionId);
+ attempts?.delete(attempt);
+ if (attempts?.size === 0) {
+ cancelledLocalConnectionAttempts.delete(connectionId);
+ }
+ }
+ if (!isCurrentLocalConnectionAttempt(connectionId, attempt)) return;
+ activeLocalConnectionAttempts.delete(connectionId);
+ connectingIds.value.delete(connectionId);
+ clearConnectionNodeLoading(connectionId);
+ }
+
+ function cancelLocalConnectionAttempt(connectionId: string): boolean {
+ const attempt = activeLocalConnectionAttempts.get(connectionId);
+ if (attempt == null) return false;
+ const attempts = cancelledLocalConnectionAttempts.get(connectionId) ?? new Set<number>();
+ attempts.add(attempt);
+ cancelledLocalConnectionAttempts.set(connectionId, attempts);
+ activeLocalConnectionAttempts.delete(connectionId);
+ connectingIds.value.delete(connectionId);
+ clearConnectionNodeLoading(connectionId);
+ connectInFlight.delete(connectionId);
+ return true;
+ }
+
+ function getDisconnectInFlight(connectionId: string): Promise<void> | undefined {
+ return disconnectInFlight.get(connectionId);
+ }
+
+ async function waitForDisconnectInFlight(connectionId: string): Promise<void> {
+ const pending = getDisconnectInFlight(connectionId);
+ if (pending) await pending;
+ }
+
+ function trackDisconnectRequest(connectionId: string, request: Promise<void>): Promise<void> {
+ const tracked = request
+ .catch((error) => {
+ console.warn("[DBX][connection:disconnect-error]", { connectionId, error });
+ })
+ .finally(() => {
+ if (disconnectInFlight.get(connectionId) === tracked) {
+ disconnectInFlight.delete(connectionId);
+ }
+ });
+ disconnectInFlight.set(connectionId, tracked);
+ return withDisconnectRequestTimeout(connectionId, request);
+ }
+
+ function startDisconnectRequest(connectionId: string): Promise<void> {
+ let request: Promise<void>;
+ try {
+ request = api.disconnectDb(connectionId);
+ } catch (error) {
+ request = Promise.reject(error);
+ }
+ return trackDisconnectRequest(connectionId, request);
+ }
+
+ function cancelDisconnectKey(connectionId: string, attempt: number): string {
+ return `${connectionId}:${attempt}`;
+ }
+
+ function startCancelDisconnectRequest(connectionId: string, attempt: number): Promise<void> {
+ const key = cancelDisconnectKey(connectionId, attempt);
+ const existing = cancelDisconnectInFlight.get(key);
+ if (existing) return existing;
+ let request: Promise<void>;
+ try {
+ request = api.disconnectDb(connectionId, attempt);
+ } catch (error) {
+ request = Promise.reject(error);
+ }
+ const tracked = withDisconnectRequestTimeout(connectionId, request)
+ .catch((error) => {
+ console.warn("[DBX][connection:cancel-disconnect-error]", { connectionId, attempt, error });
+ throw error;
+ })
+ .finally(() => {
+ if (cancelDisconnectInFlight.get(key) === tracked) {
+ cancelDisconnectInFlight.delete(key);
+ }
+ });
+ cancelDisconnectInFlight.set(key, tracked);
+ return tracked;
+ }
+
+ async function cleanupResolvedCancelledConnectionAttempt(connectionId: string, attempt: number) {
+ try {
+ // A cancel request can reach the backend before connect_db registers the
+ // attempt, so clean again if that cancelled connect later returns a pool.
+ await withDisconnectRequestTimeout(connectionId, api.disconnectDb(connectionId, attempt));
+ } catch (error) {
+ console.warn("[DBX][connection:cancel-result-cleanup-error]", { connectionId, attempt, error });
+ }
+ }
+
+ async function ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId: string, attempt: number, cleanupConnectionId: string) {
+ if (isCancelledLocalConnectionAttempt(connectionId, attempt)) {
+ await cleanupResolvedCancelledConnectionAttempt(cleanupConnectionId, attempt);
+ throw new Error(CONNECTION_ATTEMPT_CANCELLED_MESSAGE);
+ }
+ ensureLocalConnectionAttemptActive(connectionId, attempt);
+ }
+
+ function ensureLocalConnectionAttemptActive(connectionId: string, attempt: number) {
+ if (isCancelledLocalConnectionAttempt(connectionId, attempt)) {
+ throw new Error(CONNECTION_ATTEMPT_CANCELLED_MESSAGE);
+ }
+ if (!isCurrentLocalConnectionAttempt(connectionId, attempt)) {
+ throw new Error(SUPERSEDED_CONNECTION_ATTEMPT_MESSAGE);
+ }
+ }
+
function setConnectionError(connectionId: string, message: string) {
connectionErrors.value[connectionId] = message;
}
@@ -442,6 +590,10 @@ export const useConnectionStore = defineStore("connection", () => {
function recordConnectionError(connectionId: string, error: unknown): string {
const message = connectionErrorMessage(error);
+ if (isCancelledConnectionAttempt(message)) {
+ clearConnectionError(connectionId);
+ return "";
+ }
setConnectionError(connectionId, message);
maybeAppendAgentDriverUpdateHint(connectionId, message);
return message;
@@ -1318,12 +1470,15 @@ export const useConnectionStore = defineStore("connection", () => {
async function connect(config: ConnectionConfig) {
config = normalizeConnection(config);
- const pendingNode = findNode(treeNodes.value, config.id);
- if (pendingNode) pendingNode.isLoading = true;
+ if (getDisconnectInFlight(config.id)) await waitForDisconnectInFlight(config.id);
+ const localAttempt = beginLocalConnectionAttempt(config.id);
try {
await beforeConnectHandler?.(config);
- const id = await withConnectionAttemptTimeout(api.connectDb(config), config);
+ ensureLocalConnectionAttemptActive(config.id, localAttempt);
+ const id = await withConnectionAttemptTimeout(api.connectDb(config, localAttempt), config);
+ await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id);
await syncMongoLegacyDriverFallback(id, config);
+ await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id);
activeConnectionId.value = id;
connectedIds.value.add(id);
markConnectionHealthChecked(id);
@@ -1348,17 +1503,41 @@ export const useConnectionStore = defineStore("connection", () => {
}
return id;
} catch (e) {
- recordConnectionError(config.id, e);
+ if (isCancelledLocalConnectionAttempt(config.id, localAttempt)) {
+ clearConnectionError(config.id);
+ throw new Error(CONNECTION_ATTEMPT_CANCELLED_MESSAGE);
+ }
+ if (isCancelledConnectionAttempt(e) || isSupersededConnectionAttempt(e)) {
+ clearConnectionError(config.id);
+ } else {
+ recordConnectionError(config.id, e);
+ }
throw e;
} finally {
- const node = findNode(treeNodes.value, config.id);
- if (node) node.isLoading = false;
+ finishLocalConnectionAttempt(config.id, localAttempt);
}
}
+ async function cancelConnecting(connectionId: string): Promise<boolean> {
+ const localAttempt = getLocalConnectionAttempt(connectionId);
+ if (localAttempt == null) return false;
+ const disconnectRequest = startCancelDisconnectRequest(connectionId, localAttempt);
+ const cancelled = cancelLocalConnectionAttempt(connectionId);
+ if (!cancelled) return false;
+ clearConnectionError(connectionId);
+ connectedIds.value.delete(connectionId);
+ clearConnectionHealthCheck(connectionId);
+ if (activeConnectionId.value === connectionId) activeConnectionId.value = null;
+ invalidateCompletionCache(connectionId);
+ await disconnectRequest;
+ return true;
+ }
+
async function disconnect(connectionId: string) {
+ const disconnectRequest = startDisconnectRequest(connectionId);
+ cancelLocalConnectionAttempt(connectionId);
const shouldRemoveOneTimeConnection = getConfig(connectionId)?.one_time === true;
- await withDisconnectRequestTimeout(connectionId, api.disconnectDb(connectionId));
+ await disconnectRequest;
clearConnectionError(connectionId);
const { useQueryStore } = await import("@/stores/queryStore");
const queryStore = useQueryStore();
@@ -1440,15 +1619,20 @@ export const useConnectionStore = defineStore("connection", () => {
recordConnectionError(connectionId, error);
throw error;
}
+ if (getDisconnectInFlight(connectionId)) await waitForDisconnectInFlight(connectionId);
const existingConnect = connectInFlight.get(connectionId);
if (existingConnect) {
await existingConnect;
return;
}
+ const localAttempt = beginLocalConnectionAttempt(connectionId);
const connectPromise = (async () => {
await beforeConnectHandler?.(config);
- await withConnectionAttemptTimeout(api.connectDb(config), config);
+ ensureLocalConnectionAttemptActive(connectionId, localAttempt);
+ const id = await withConnectionAttemptTimeout(api.connectDb(config, localAttempt), config);
+ await ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId, localAttempt, id);
await syncMongoLegacyDriverFallback(connectionId, config);
+ await ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId, localAttempt, id);
connectedIds.value.add(connectionId);
markConnectionHealthChecked(connectionId);
activeConnectionId.value = connectionId;
@@ -1458,6 +1642,14 @@ export const useConnectionStore = defineStore("connection", () => {
try {
await connectPromise;
} catch (e) {
+ if (isCancelledLocalConnectionAttempt(connectionId, localAttempt)) {
+ clearConnectionError(connectionId);
+ throw new Error(CONNECTION_ATTEMPT_CANCELLED_MESSAGE);
+ }
+ if (isCancelledConnectionAttempt(e)) {
+ clearConnectionError(connectionId);
+ throw e;
+ }
if (isSupersededConnectionAttempt(e) && connectedIds.value.has(connectionId)) {
clearConnectionError(connectionId);
return;
@@ -1469,6 +1661,7 @@ export const useConnectionStore = defineStore("connection", () => {
if (connectInFlight.get(connectionId) === connectPromise) {
connectInFlight.delete(connectionId);
}
+ finishLocalConnectionAttempt(connectionId, localAttempt);
}
}
@@ -4015,6 +4208,7 @@ export const useConnectionStore = defineStore("connection", () => {
refreshDatabaseTreeNode,
refreshObjectListTreeNode,
connectedIds,
+ connectingIds,
connectionErrors,
setConnectionError,
clearConnectionError,
@@ -4046,6 +4240,7 @@ export const useConnectionStore = defineStore("connection", () => {
startCreatingConnectionInGroup,
stopCreatingConnectionInGroup,
connect,
+ cancelConnecting,
disconnect,
closeDatabaseConnection,
ensureConnected,
diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rs
index cd11e529a9..729fc7cd70 100644
--- a/crates/dbx-core/src/connection.rs
+++ b/crates/dbx-core/src/connection.rs
@@ -161,7 +161,7 @@ pub struct AppState {
pub connections: Arc<RwLock<HashMap<String, PoolKind>>>,
keepalive_tasks: Arc<RwLock<HashMap<String, JoinHandle<()>>>>,
pool_activity: Arc<RwLock<HashMap<String, PoolActivity>>>,
- connection_attempts: RwLock<HashMap<String, u64>>,
+ connection_attempts: RwLock<HashMap<String, ConnectionAttemptState>>,
pub configs: RwLock<HashMap<String, ConnectionConfig>>,
pub running_queries: RunningQueries,
pub tunnels: TunnelManager,
@@ -185,6 +185,12 @@ struct PoolActivity {
last_used_at: Instant,
}
+#[derive(Clone, Copy)]
+struct ConnectionAttemptState {
+ server_attempt: u64,
+ client_attempt: Option<u64>,
+}
+
impl PoolActivity {
fn now() -> Self {
Self { last_used_at: Instant::now() }
@@ -553,9 +559,17 @@ impl AppState {
}
pub async fn begin_connection_attempt(&self, connection_id: &str) -> u64 {
+ self.begin_connection_attempt_with_client_attempt(connection_id, None).await
+ }
+
+ pub async fn begin_connection_attempt_with_client_attempt(
+ &self,
+ connection_id: &str,
+ client_attempt: Option<u64>,
+ ) -> u64 {
let mut attempts = self.connection_attempts.write().await;
- let next = attempts.get(connection_id).copied().unwrap_or(0).wrapping_add(1);
- attempts.insert(connection_id.to_string(), next);
+ let next = attempts.get(connection_id).map(|state| state.server_attempt).unwrap_or(0).wrapping_add(1);
+ attempts.insert(connection_id.to_string(), ConnectionAttemptState { server_attempt: next, client_attempt });
next
}
@@ -563,11 +577,34 @@ impl AppState {
self.begin_connection_attempt(connection_id).await;
}
+ pub async fn supersede_connection_attempt_if_client_attempt(
+ &self,
+ connection_id: &str,
+ client_attempt: u64,
+ ) -> bool {
+ let mut attempts = self.connection_attempts.write().await;
+ let Some(current) = attempts.get(connection_id).copied() else {
+ return false;
+ };
+ if current.client_attempt != Some(client_attempt) {
+ return false;
+ }
+ attempts.insert(
+ connection_id.to_string(),
+ ConnectionAttemptState { server_attempt: current.server_attempt.wrapping_add(1), client_attempt: None },
+ );
+ true
+ }
+
async fn connection_attempt_is_current(&self, connection_id: &str, attempt: u64) -> bool {
- self.connection_attempts.read().await.get(connection_id).copied() == Some(attempt)
+ self.connection_attempts.read().await.get(connection_id).map(|state| state.server_attempt) == Some(attempt)
}
- async fn ensure_current_connection_attempt(&self, connection_id: &str, attempt: Option<u64>) -> Result<(), String> {
+ pub async fn ensure_current_connection_attempt(
+ &self,
+ connection_id: &str,
+ attempt: Option<u64>,
+ ) -> Result<(), String> {
let Some(attempt) = attempt else {
return Ok(());
};
@@ -594,6 +631,20 @@ impl AppState {
Ok(())
}
+ async fn discard_stale_connection_attempt_pool(
+ &self,
+ connection_id: &str,
+ pool_key: String,
+ pool: PoolKind,
+ config: &ConnectionConfig,
+ ) {
+ if matches!(pool, PoolKind::MessageQueue) {
+ self.mq_registry.drop_connection(connection_id).await;
+ }
+ self.reset_connection_transport_for_config(connection_id, config).await;
+ close_pool_kind_with_timeout(pool_key, pool).await;
+ }
+
async fn start_keepalive_task(&self, pool_key: &str, pool: &PoolKind, config: &ConnectionConfig) {
let interval_secs = config.keepalive_interval_secs;
let idle_timeout_secs = config.idle_timeout_secs;
@@ -782,8 +833,17 @@ impl AppState {
let db_config = database_connection_config(&config, database);
validate_h2_file_connection(&db_config)?;
+ self.ensure_current_connection_attempt(connection_id, connection_attempt).await?;
let (host, port) = self.connection_host_port(connection_id, &db_config).await?;
+ if let Err(err) = self.ensure_current_connection_attempt(connection_id, connection_attempt).await {
+ self.reset_connection_transport_for_config(connection_id, &db_config).await;
+ return Err(err);
+ }
probe_connection_endpoint(&db_config, &host, port).await?;
+ if let Err(err) = self.ensure_current_connection_attempt(connection_id, connection_attempt).await {
+ self.reset_connection_transport_for_config(connection_id, &db_config).await;
+ return Err(err);
+ }
let url = connection_url_for_endpoint(&db_config, &host, port);
let connect_timeout = std::time::Duration::from_secs(db_config.effective_connect_timeout_secs());
let idle_timeout = std::time::Duration::from_secs(db_config.idle_timeout_secs);
@@ -935,9 +995,21 @@ impl AppState {
Ok(()) => {
// Re-check: another task may have created the pool while we were connecting.
if self.connections.read().await.contains_key(&pool_key) {
+ close_pool_kind_with_timeout(pool_key.clone(), PoolKind::MongoDb(client)).await;
return Ok(pool_key);
}
- self.ensure_current_connection_attempt(connection_id, connection_attempt).await?;
+ if let Err(err) =
+ self.ensure_current_connection_attempt(connection_id, connection_attempt).await
+ {
+ self.discard_stale_connection_attempt_pool(
+ connection_id,
+ pool_key.clone(),
+ PoolKind::MongoDb(client),
+ &db_config,
+ )
+ .await;
+ return Err(err);
+ }
self.insert_connection_pool(pool_key.clone(), PoolKind::MongoDb(client), &db_config)
.await;
return Ok(pool_key);
@@ -1133,6 +1205,11 @@ impl AppState {
self.mq_registry.drop_connection(connection_id).await;
return Err(err);
}
+ if let Err(err) = self.ensure_current_connection_attempt(connection_id, connection_attempt).await {
+ self.mq_registry.drop_connection(connection_id).await;
+ self.reset_connection_transport_for_config(connection_id, &db_config).await;
+ return Err(err);
+ }
PoolKind::MessageQueue
}
#[cfg(not(feature = "mq-admin"))]
@@ -1145,7 +1222,7 @@ impl AppState {
};
if let Err(err) = self.ensure_current_connection_attempt(connection_id, connection_attempt).await {
- close_pool_kind_with_timeout(pool_key.clone(), pool).await;
+ self.discard_stale_connection_attempt_pool(connection_id, pool_key.clone(), pool, &db_config).await;
return Err(err);
}
self.insert_connection_pool(pool_key.clone(), pool, &db_config).await;
diff --git a/crates/dbx-web/src/routes/connection.rs b/crates/dbx-web/src/routes/connection.rs
index cf6e8b89b2..b770169c49 100644
--- a/crates/dbx-web/src/routes/connection.rs
+++ b/crates/dbx-web/src/routes/connection.rs
@@ -13,12 +13,14 @@ use crate::state::WebState;
#[serde(rename_all = "camelCase")]
pub struct ConnectRequest {
pub config: ConnectionConfig,
+ pub client_attempt: Option<u64>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DisconnectRequest {
pub connection_id: String,
+ pub client_attempt: Option<u64>,
}
#[derive(Deserialize)]
@@ -67,7 +69,7 @@ pub async fn connect_db(
let config = body.config;
let app = &state.app;
let connection_id = config.id.clone();
- let attempt = app.begin_connection_attempt(&connection_id).await;
+ let attempt = app.begin_connection_attempt_with_client_attempt(&connection_id, body.client_attempt).await;
app.remove_connection_pools_detached(&connection_id).await;
app.reset_connection_transport_for_config(&connection_id, &config).await;
@@ -102,7 +104,15 @@ pub async fn disconnect_db(
) -> Result<Json<()>, AppError> {
let app = &state.app;
- app.supersede_connection_attempt(&body.connection_id).await;
+ let should_disconnect = if let Some(client_attempt) = body.client_attempt {
+ app.supersede_connection_attempt_if_client_attempt(&body.connection_id, client_attempt).await
+ } else {
+ app.supersede_connection_attempt(&body.connection_id).await;
+ true
+ };
+ if !should_disconnect {
+ return Ok(Json(()));
+ }
app.remove_connection_pools_detached(&body.connection_id).await;
app.nacos_registry.drop_connection(&body.connection_id).await;
#[cfg(feature = "mq-admin")]
@@ -419,7 +429,9 @@ mod tests {
let first = state.app.mq_registry.get_or_build(&initial).await.unwrap();
let updated = mq_config("mq-conn", &spawn_pulsar_clusters_server().await);
- let result = connect_db(State(state.clone()), Json(ConnectRequest { config: updated.clone() })).await;
+ let result =
+ connect_db(State(state.clone()), Json(ConnectRequest { config: updated.clone(), client_attempt: None }))
+ .await;
assert!(result.is_ok());
let second = state.app.mq_registry.get_or_build(&updated).await.unwrap();
@@ -519,8 +531,11 @@ mod tests {
connections.insert("conn2".to_string(), PoolKind::Sqlite(conn2_pool));
}
- let result =
- disconnect_db(State(state.clone()), Json(DisconnectRequest { connection_id: "conn".to_string() })).await;
+ let result = disconnect_db(
+ State(state.clone()),
+ Json(DisconnectRequest { connection_id: "conn".to_string(), client_attempt: None }),
+ )
+ .await;
assert!(result.is_ok());
let connections = state.app.connections.read().await;
@@ -530,6 +545,39 @@ mod tests {
let _ = std::fs::remove_dir_all(dir);
}
+ #[tokio::test]
+ async fn disconnect_db_ignores_stale_client_attempt_cancel() {
+ let (state, dir) = test_web_state().await;
+ let conn_path = dir.join("conn.db");
+ std::fs::File::create(&conn_path).unwrap();
+ let conn_pool = dbx_core::db::sqlite::connect_path(&conn_path.to_string_lossy()).await.unwrap();
+ state.app.begin_connection_attempt_with_client_attempt("conn", Some(1)).await;
+ let current_attempt = state.app.begin_connection_attempt_with_client_attempt("conn", Some(2)).await;
+ state.app.connections.write().await.insert("conn".to_string(), PoolKind::Sqlite(conn_pool));
+
+ let result = disconnect_db(
+ State(state.clone()),
+ Json(DisconnectRequest { connection_id: "conn".to_string(), client_attempt: Some(1) }),
+ )
+ .await;
+ assert!(result.is_ok());
+
+ assert!(state.app.connections.read().await.contains_key("conn"));
+ assert!(state.app.ensure_current_connection_attempt("conn", Some(current_attempt)).await.is_ok());
+
+ let result = disconnect_db(
+ State(state.clone()),
+ Json(DisconnectRequest { connection_id: "conn".to_string(), client_attempt: Some(2) }),
+ )
+ .await;
+ assert!(result.is_ok());
+
+ assert!(!state.app.connections.read().await.contains_key("conn"));
+ assert!(state.app.ensure_current_connection_attempt("conn", Some(current_attempt)).await.is_err());
+
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
#[tokio::test]
async fn disconnect_db_keeps_connection_config_for_reconnect() {
let (state, dir) = test_web_state().await;
@@ -546,8 +594,11 @@ mod tests {
configs.insert("conn".to_string(), sqlite_config("conn", &conn_path.to_string_lossy()));
}
- let result =
- disconnect_db(State(state.clone()), Json(DisconnectRequest { connection_id: "conn".to_string() })).await;
+ let result = disconnect_db(
+ State(state.clone()),
+ Json(DisconnectRequest { connection_id: "conn".to_string(), client_attempt: None }),
+ )
+ .await;
assert!(result.is_ok());
let configs = state.app.configs.read().await;
@@ -565,8 +616,11 @@ mod tests {
state.app.connections.write().await.insert(config.id.clone(), PoolKind::MessageQueue);
let first = state.app.mq_registry.get_or_build(&config).await.unwrap();
- let result =
- disconnect_db(State(state.clone()), Json(DisconnectRequest { connection_id: config.id.clone() })).await;
+ let result = disconnect_db(
+ State(state.clone()),
+ Json(DisconnectRequest { connection_id: config.id.clone(), client_attempt: None }),
+ )
+ .await;
assert!(result.is_ok());
assert!(!state.app.connections.read().await.contains_key(&config.id));
@@ -588,8 +642,11 @@ mod tests {
configs.insert(draft_id.to_string(), sqlite_config(draft_id, &conn_path.to_string_lossy()));
}
- let result =
- disconnect_db(State(state.clone()), Json(DisconnectRequest { connection_id: draft_id.to_string() })).await;
+ let result = disconnect_db(
+ State(state.clone()),
+ Json(DisconnectRequest { connection_id: draft_id.to_string(), client_attempt: None }),
+ )
+ .await;
assert!(result.is_ok());
let configs = state.app.configs.read().await;
diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rs
index 0cad1ac121..46a8df72d8 100644
--- a/src-tauri/src/commands/connection.rs
+++ b/src-tauri/src/commands/connection.rs
@@ -807,11 +807,15 @@ pub async fn test_connection(state: State<'_, Arc<AppState>>, config: Connection
}
#[tauri::command]
-pub async fn connect_db(state: State<'_, Arc<AppState>>, config: ConnectionConfig) -> Result<String, String> {
+pub async fn connect_db(
+ state: State<'_, Arc<AppState>>,
+ config: ConnectionConfig,
+ client_attempt: Option<u64>,
+) -> Result<String, String> {
let config = config.canonicalized();
let id = config.id.clone();
let db_config = metadata_connection_config(&config);
- let attempt = state.begin_connection_attempt(&id).await;
+ let attempt = state.begin_connection_attempt_with_client_attempt(&id, client_attempt).await;
let mut connected_config = config.clone();
let mut connected_db_config = db_config.clone();
@@ -819,7 +823,15 @@ pub async fn connect_db(state: State<'_, Arc<AppState>>, config: ConnectionConfi
state.reset_connection_transport_for_config(&id, &db_config).await;
let (host, port) = state.connection_host_port(&id, &db_config).await?;
+ if let Err(err) = state.ensure_current_connection_attempt(&id, Some(attempt)).await {
+ state.reset_connection_transport_for_config(&id, &db_config).await;
+ return Err(err);
+ }
probe_connection_endpoint(&db_config, &host, port).await?;
+ if let Err(err) = state.ensure_current_connection_attempt(&id, Some(attempt)).await {
+ state.reset_connection_transport_for_config(&id, &db_config).await;
+ return Err(err);
+ }
let url = connection_url_for_endpoint(&db_config, &host, port);
let connect_timeout = std::time::Duration::from_secs(db_config.effective_connect_timeout_secs());
let idle_timeout = std::time::Duration::from_secs(db_config.idle_timeout_secs);
@@ -885,14 +897,17 @@ pub async fn connect_db(state: State<'_, Arc<AppState>>, config: ConnectionConfi
if mongo_uses_legacy_driver(&db_config) {
let mut client =
state.agent_manager.spawn(&db_config.db_type, Some(MONGO_LEGACY_DRIVER_PROFILE)).await?;
+ state.ensure_current_connection_attempt(&id, Some(attempt)).await?;
client
.connect(mongo_legacy_connect_params(&db_config, &host, port))
.await
.map_err(|err| mongo_legacy_error_with_auth_hint(&err))?;
+ state.ensure_current_connection_attempt(&id, Some(attempt)).await?;
PoolKind::Agent(std::sync::Arc::new(tokio::sync::Mutex::new(client)))
} else {
let native_err = match db::mongo_driver::connect(&url, connect_timeout, idle_timeout).await {
Ok(client) => {
+ state.ensure_current_connection_attempt(&id, Some(attempt)).await?;
match db::mongo_driver::test_connection(
&client,
connect_timeout,
@@ -901,7 +916,8 @@ pub async fn connect_db(state: State<'_, Arc<AppState>>, config: ConnectionConfi
.await
{
Ok(()) => {
- state
+ state.ensure_current_connection_attempt(&id, Some(attempt)).await?;
+ if let Err(err) = state
.insert_connection_pool_for_attempt(
&id,
attempt,
@@ -909,7 +925,11 @@ pub async fn connect_db(state: State<'_, Arc<AppState>>, config: ConnectionConfi
PoolKind::MongoDb(client),
&db_config,
)
- .await?;
+ .await
+ {
+ state.reset_connection_transport_for_config(&id, &db_config).await;
+ return Err(err);
+ }
state.configs.write().await.insert(id.clone(), config);
return Ok(id);
}
@@ -922,12 +942,14 @@ pub async fn connect_db(state: State<'_, Arc<AppState>>, config: ConnectionConfi
log::info!("Native MongoDB driver failed ({native_err}), falling back to agent driver");
let mut client =
state.agent_manager.spawn(&db_config.db_type, Some(MONGO_LEGACY_DRIVER_PROFILE)).await?;
+ state.ensure_current_connection_attempt(&id, Some(attempt)).await?;
client.connect(mongo_legacy_connect_params(&db_config, &host, port)).await.map_err(|err| {
format!(
"{native_err}\n\nFallback with MongoDB (Legacy) driver failed: {}",
mongo_legacy_error_with_auth_hint(&err)
)
})?;
+ state.ensure_current_connection_attempt(&id, Some(attempt)).await?;
mark_mongo_legacy_driver(&mut connected_config);
connected_db_config = metadata_connection_config(&connected_config);
persist_mongo_legacy_driver_profile(state.inner(), &connected_config).await?;
@@ -1062,10 +1084,18 @@ pub async fn connect_db(state: State<'_, Arc<AppState>>, config: ConnectionConfi
return Err(err);
}
};
+ if let Err(err) = state.ensure_current_connection_attempt(&id, Some(attempt)).await {
+ state.mq_registry.drop_connection(&id).await;
+ return Err(err);
+ }
if let Err(err) = adapter.test_connection().await {
state.mq_registry.drop_connection(&id).await;
return Err(err);
}
+ if let Err(err) = state.ensure_current_connection_attempt(&id, Some(attempt)).await {
+ state.mq_registry.drop_connection(&id).await;
+ return Err(err);
+ }
PoolKind::MessageQueue
}
#[cfg(not(feature = "mq-admin"))]
@@ -1086,7 +1116,12 @@ pub async fn connect_db(state: State<'_, Arc<AppState>>, config: ConnectionConfi
db_type => return Err(format!("Unsupported database type: {db_type:?}")),
};
- state.insert_connection_pool_for_attempt(&id, attempt, id.clone(), pool, &connected_db_config).await?;
+ if let Err(err) =
+ state.insert_connection_pool_for_attempt(&id, attempt, id.clone(), pool, &connected_db_config).await
+ {
+ state.reset_connection_transport_for_config(&id, &connected_db_config).await;
+ return Err(err);
+ }
state.configs.write().await.insert(id.clone(), connected_config);
Ok(id)
@@ -1111,8 +1146,20 @@ pub async fn connection_final_proxy_port(
}
#[tauri::command]
-pub async fn disconnect_db(state: State<'_, Arc<AppState>>, connection_id: String) -> Result<(), String> {
- state.supersede_connection_attempt(&connection_id).await;
+pub async fn disconnect_db(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ client_attempt: Option<u64>,
+) -> Result<(), String> {
+ let should_disconnect = if let Some(client_attempt) = client_attempt {
+ state.supersede_connection_attempt_if_client_attempt(&connection_id, client_attempt).await
+ } else {
+ state.supersede_connection_attempt(&connection_id).await;
+ true
+ };
+ if !should_disconnect {
+ return Ok(());
+ }
state.remove_connection_pools_detached(&connection_id).await;
drop_nacos_adapters_for_connection_ids(state.inner(), std::slice::from_ref(&connection_id)).await;
drop_mq_adapters_for_connection_ids(state.inner(), std::slice::from_ref(&connection_id)).await;