feat(connection): notify sidebar when keepalive loses connection

This commit is contained in:
Abeautifulsnow authored and GitHub committed 2026-09-30 19:49:52 +08:00
1 parent 3ffff92c8f
commit dc503877f9
13 files changed
+864 -27

No files matched your search

+39
View File
@@ -371,6 +371,9 @@ let updateCheckTimer: ReturnType<typeof setInterval> | undefined;
const needsAuth = ref(!isDesktop && (startupProps.startupAuthentication?.required ?? true));
const authenticated = ref(isDesktop || (startupProps.startupAuthentication?.authenticated ?? false));
const setupRequired = ref(!isDesktop && (startupProps.startupAuthentication?.setup_required ?? false));
// Mirrors the template gate above the app shell. The backend liveness stream is registered
// against it so the web runtime only opens an authenticated subscription.
const appReady = computed(() => !setupRequired.value && (!needsAuth.value || authenticated.value));
const showConnectionDialog = ref(false);
const connectionDialogPrefill = ref<ConnectionDeepLinkDraft | null>(null);
@@ -4078,6 +4081,40 @@ function runUpdateNotificationChecks() {
void componentUpdates.refresh();
}
// Backend-confirmed connection liveness losses (#4339). Registered through the forwarded
// `api` layer rather than the Tauri-only `listen` helpers so both runtimes subscribe, and
// keyed off `appReady` so the web runtime never opens the SSE stream before it is
// authenticated (the whole /api surface sits behind the auth middleware).
let connectionLivenessUnlisten: (() => void) | null = null;
let connectionLivenessSubscribing = false;
async function syncConnectionLivenessSubscription(active: boolean): Promise<void> {
if (!active) {
connectionLivenessUnlisten?.();
connectionLivenessUnlisten = null;
return;
}
if (connectionLivenessUnlisten || connectionLivenessSubscribing) return;
connectionLivenessSubscribing = true;
try {
const unlisten = await api.subscribeConnectionLiveness((message) => {
void connectionStore.handleConnectionLivenessMessage(message);
});
if (!appReady.value) {
// Auth flipped off while the subscription was being established.
unlisten();
return;
}
connectionLivenessUnlisten = unlisten;
} catch (error) {
console.error("[DBX] subscribeConnectionLiveness error:", error);
} finally {
connectionLivenessSubscribing = false;
}
}
watch(appReady, (ready) => void syncConnectionLivenessSubscription(ready), { immediate: true });
onMounted(async () => {
clearStartupPreloadRetry();
markStartupPhase("app-mounted");
@@ -4182,6 +4219,8 @@ onMounted(async () => {
onUnmounted(() => {
disposeUpdater();
updatePreparation?.dispose();
connectionLivenessUnlisten?.();
connectionLivenessUnlisten = null;
detachedEventUnlisteners.forEach((unlisten) => unlisten());
detachedEventUnlisteners = [];
cleanupTauriListeners();
+2
View File
@@ -75,6 +75,8 @@ export const sessionCredentialStatus = forward("sessionCredentialStatus");
export const forgetSessionCredential = forward("forgetSessionCredential");
export const replaceNacosSessionCredential = forward("replaceNacosSessionCredential");
export const checkConnectionHealth = forward("checkConnectionHealth");
export const connectionIsOpen = forward("connectionIsOpen");
export const subscribeConnectionLiveness = forward("subscribeConnectionLiveness");
export const prewarmConnection = forward("prewarmConnection");
export const connectionIdentifierQuote = forward("connectionIdentifierQuote");
export const closeDatabaseConnection = forward("closeDatabaseConnection");
+26
View File
@@ -249,6 +249,7 @@ import type { DataCompareFromTablesOptions, DataCompareFromTablesPreparation, Da
import { apiUrl, apiWebSocketUrl } from "@/lib/common/webPath";
import type {
ActivePluginSession,
ConnectionLivenessMessage,
PluginBinaryEvent,
PluginConnectionActionResult,
PluginEvent,
@@ -556,6 +557,17 @@ export async function checkConnectionHealth(connectionId: string): Promise<void>
return post("/api/connection/check-health", { connectionId });
}
/**
* Read-only counterpart of `checkConnectionHealth`: reports whether the connection still has a
* pool, without probing or mutating anything (#4339).
*
* Liveness events must be confirmed through this, never through `checkConnectionHealth`: the
* latter removes unhealthy pools and is the path `ensureConnected` uses to trigger a reconnect.
*/
export async function connectionIsOpen(connectionId: string): Promise<boolean> {
return post("/api/connection/is-open", { connectionId });
}
export async function prewarmConnection(connectionId: string, database?: string, catalog?: string, clientSessionId?: string): Promise<void> {
return post("/api/connection/prewarm", { connectionId, database, catalog, clientSessionId });
}
@@ -785,6 +797,20 @@ export async function subscribePluginEvents(onEvent: (event: PluginEvent) => voi
return () => source.close();
}
/**
* Subscribe to backend connection-liveness messages (#4339).
*
* The SSE payload is one `ConnectionLivenessMessage`: the plugin stream's `{ kind }` wrapper
* multiplexes two streams, whereas here `kind` is the message's own discriminator.
*/
export async function subscribeConnectionLiveness(onEvent: (event: ConnectionLivenessMessage) => void): Promise<() => void> {
const source = new EventSource(apiUrl("/api/connection/liveness-events"));
source.onmessage = (message) => {
onEvent(JSON.parse(message.data) as ConnectionLivenessMessage);
};
return () => source.close();
}
async function pluginAssetPayload(path: string): Promise<PluginUiAssetPayload> {
const response = await fetch(apiUrl(path));
if (!response.ok) throw new Error(await response.text());
+22
View File
@@ -122,6 +122,7 @@ import type { QueryEditability } from "@/lib/sql/sqlAnalysis";
import { isTerminalTransferProgress } from "@/lib/backend/transferProgress";
import type {
ActivePluginSession,
ConnectionLivenessMessage,
PluginBinaryEvent,
PluginConnectionActionResult,
PluginEvent,
@@ -1563,6 +1564,17 @@ export async function checkConnectionHealth(connectionId: string): Promise<void>
return invokeBackend("check_connection_health", { connectionId });
}
/**
* Read-only counterpart of `checkConnectionHealth`: reports whether the connection still has a
* pool, without probing or mutating anything (#4339).
*
* Liveness events must be confirmed through this, never through `checkConnectionHealth`: the
* latter removes unhealthy pools and is the path `ensureConnected` uses to trigger a reconnect.
*/
export async function connectionIsOpen(connectionId: string): Promise<boolean> {
return invokeBackend("connection_is_open", { connectionId });
}
export async function prewarmConnection(connectionId: string, database?: string, catalog?: string, clientSessionId?: string): Promise<void> {
return invokeBackend("prewarm_connection", { connectionId, database, catalog, clientSessionId });
}
@@ -2853,6 +2865,16 @@ export async function subscribePluginEvents(onEvent: (event: PluginEvent) => voi
};
}
/**
* Subscribe to backend connection-liveness messages (#4339).
*
* The listener receives the message unwrapped; the web transport's SSE handler parses the same
* shape, so the store can stay transport-agnostic.
*/
export async function subscribeConnectionLiveness(onEvent: (event: ConnectionLivenessMessage) => void): Promise<UnlistenFn> {
return listen<ConnectionLivenessMessage>("dbx-connection-liveness", (event) => onEvent(event.payload));
}
export async function listJdbcDrivers(): Promise<JdbcDriverInfo[]> {
return invoke("list_jdbc_drivers");
}
@@ -0,0 +1,163 @@
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
const connectionIsOpen = vi.hoisted(() => vi.fn());
function installLocalStorage() {
const data = new Map<string, string>();
vi.stubGlobal("localStorage", {
getItem: vi.fn((key: string) => data.get(key) ?? null),
setItem: vi.fn((key: string, value: string) => data.set(key, value)),
removeItem: vi.fn((key: string) => data.delete(key)),
});
}
/**
* Backend connection-liveness messages (#4339).
*
* The backend publishes `lost` only once a connection has no pools left, but the message is
* asynchronous: it can be delivered after the user already reconnected. The store therefore
* confirms with the read-only `connectionIsOpen` before it touches the sidebar, and must never
* confirm with `checkConnectionHealth` (which removes pools and reconnects).
*
* `resync` is sent when the transport dropped messages; those are unrecoverable, so the store
* re-checks everything it still shows as connected.
*/
describe("connectionStore keepalive liveness", () => {
beforeEach(() => {
vi.resetModules();
vi.unstubAllGlobals();
installLocalStorage();
setActivePinia(createPinia());
i18n.global.locale.value = "en";
connectionIsOpen.mockReset();
vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
vi.doMock("@/lib/backend/api", () => ({
connectionIsOpen,
disconnectDb: vi.fn().mockResolvedValue(undefined),
checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
listInstalledAgents: vi.fn().mockResolvedValue([]),
loadSchemaCache: vi.fn().mockResolvedValue(null),
saveConnections: vi.fn().mockResolvedValue(undefined),
saveSchemaCache: vi.fn().mockResolvedValue(undefined),
saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
}));
});
async function loadStore() {
const { useConnectionStore } = await import("@/stores/connectionStore");
return useConnectionStore();
}
it("flips the sidebar offline only once the read-only confirm reports no pool", async () => {
connectionIsOpen.mockResolvedValue(false);
const store = await loadStore();
store.connectedIds.add("c1");
await store.handleConnectionLivenessMessage({ kind: "lost", connectionId: "c1", failureKind: "probe_failed" });
expect(connectionIsOpen).toHaveBeenCalledWith("c1");
expect(store.connectedIds.has("c1")).toBe(false);
});
it("keeps the connection when the confirm reports it open again", async () => {
// A reconnect that finished before the message was delivered: the pool is back, so a late
// message must not grey out a connection the user is actively using.
connectionIsOpen.mockResolvedValue(true);
const store = await loadStore();
store.connectedIds.add("c1");
await store.handleConnectionLivenessMessage({ kind: "lost", connectionId: "c1", failureKind: "timed_out" });
expect(store.connectedIds.has("c1")).toBe(true);
});
it("ignores messages for connections this frontend does not consider connected", async () => {
const store = await loadStore();
await store.handleConnectionLivenessMessage({
kind: "lost",
connectionId: "never-connected",
failureKind: "probe_failed",
});
expect(connectionIsOpen).not.toHaveBeenCalled();
expect(store.connectedIds.size).toBe(0);
});
it("leaves the sidebar untouched when the confirm itself fails", async () => {
// A failed confirm says nothing about the connection, so the status must not be guessed.
connectionIsOpen.mockRejectedValue(new Error("ipc unavailable"));
const store = await loadStore();
store.connectedIds.add("c1");
await store.handleConnectionLivenessMessage({ kind: "lost", connectionId: "c1", failureKind: "probe_failed" });
expect(store.connectedIds.has("c1")).toBe(true);
});
it("re-checks every connected connection on a resync instead of keeping a dropped loss", async () => {
// The transport dropped messages, so the ids whose loss was dropped are unknown: the store
// has to re-check the whole connected set, or one sidebar stays green indefinitely.
const store = await loadStore();
store.connectedIds.add("dead");
store.connectedIds.add("alive");
connectionIsOpen.mockImplementation((connectionId: string) => Promise.resolve(connectionId === "alive"));
await store.handleConnectionLivenessMessage({ kind: "resync" });
expect(connectionIsOpen).toHaveBeenCalledWith("dead");
expect(connectionIsOpen).toHaveBeenCalledWith("alive");
expect(store.connectedIds.has("dead")).toBe(false);
expect(store.connectedIds.has("alive")).toBe(true);
});
it("does not query the backend on a resync when nothing is connected", async () => {
const store = await loadStore();
await store.handleConnectionLivenessMessage({ kind: "resync" });
expect(connectionIsOpen).not.toHaveBeenCalled();
});
it("drops a stale confirm that lands after a newer connection attempt", async () => {
// The revision guard: a `lost` message captured before a newer connect/disconnect attempt
// must not grey out the connection that attempt produced. Only `disconnect` (and the
// connect path it mirrors) advances the generation, so the test drives it for real.
let resolveConfirm: (open: boolean) => void = () => {};
connectionIsOpen.mockImplementation(
() =>
new Promise<boolean>((resolve) => {
resolveConfirm = resolve;
}),
);
vi.doMock("@/stores/settingsStore", () => ({
useSettingsStore: () => ({ editorSettings: { disconnectTabHandlingMode: "keep-tabs" } }),
}));
vi.doMock("@/stores/queryStore", () => ({
useQueryStore: () => ({
closeConnectionTabs: vi.fn(),
releaseConnectionTabs: vi.fn(),
flushPendingPersist: vi.fn().mockResolvedValue(undefined),
}),
}));
const store = await loadStore();
store.connectedIds.add("c1");
const pending = store.handleConnectionLivenessMessage({
kind: "lost",
connectionId: "c1",
failureKind: "probe_failed",
});
// The user drops and re-establishes the connection while the probe is still in flight.
await store.disconnect("c1");
store.connectedIds.add("c1");
resolveConfirm(false);
await pending;
expect(store.connectedIds.has("c1")).toBe(true);
});
});
@@ -12,6 +12,7 @@ import type {
CompletionAssistantObjectKind,
CompletionAssistantRequest,
ConnectionConfig,
ConnectionLivenessMessage,
DatabaseType,
DatabaseConnectionInfo,
DatabaseStorageInfo,
@@ -4676,6 +4677,60 @@ export const useConnectionStore = defineStore("connection", () => {
clearConnectionPrewarmState(connectionId);
}
/**
* Re-check one connection against the backend and grey it out when it has no pool left.
*
* The confirmation is the read-only `api.connectionIsOpen`, never `checkConnectionHealth`:
* the latter removes unhealthy pools and is the path `ensureConnected` uses to reconnect, so
* confirming with it would turn a background probe into a reconnect and an error banner.
*
* A failed confirm says nothing about the connection, so it leaves the sidebar untouched.
*/
async function confirmConnectionLiveness(connectionId: string): Promise<void> {
if (!connectionId || !connectedIds.value.has(connectionId)) return;
const stateRevision = connectionStateRevision(connectionId);
let open: boolean;
try {
open = await api.connectionIsOpen(connectionId);
} catch (error) {
console.warn("[DBX] connection liveness confirm failed:", error);
return;
}
if (open) return;
// A late confirm must not undo an explicit disconnect or a newer reconnect.
if (!isCurrentConnectionStateRevision(connectionId, stateRevision)) return;
if (!connectedIds.value.has(connectionId)) return;
markConnectionOffline(connectionId);
}
/**
* Apply a message from the backend connection-liveness channel (#4339).
*
* `lost` is published only once the connection has no pools left, but it is asynchronous, so
* it is confirmed before the sidebar changes: a message generated before a reconnect but
* delivered after it confirms as "open" and is dropped.
*
* `resync` is sent when the transport skipped messages. Those are gone for good, so every
* connection this frontend still shows as connected is re-checked. Without it a dropped loss
* would leave its sidebar green until the user happened to touch that connection — the very
* bug this channel exists to fix.
*/
async function handleConnectionLivenessMessage(message: ConnectionLivenessMessage): Promise<void> {
if (!message) return;
if (message.kind === "resync") {
// Sequential on purpose: resync only happens after a transport lag, and one probe in
// flight at a time keeps a large connected set from stampeding the backend.
// Snapshot the ids: the confirm below removes entries from this set as it flips them.
for (const connectionId of Array.from(connectedIds.value)) {
await confirmConnectionLiveness(connectionId);
}
return;
}
// Defensive against a newer backend sending a kind this build does not know.
if (message.kind !== "lost") return;
await confirmConnectionLiveness(message.connectionId);
}
/**
* 断开连接。
*
@@ -10181,6 +10236,7 @@ export const useConnectionStore = defineStore("connection", () => {
disconnect,
hasDisconnectInFlight,
markConnectionOffline,
handleConnectionLivenessMessage,
metadataGenerationFor,
disconnectAndForgetConnectionPassword,
hasSessionCredential,
+20
View File
@@ -190,6 +190,26 @@ export interface ConnectionTestResult {
databaseInfo?: DatabaseConnectionInfo;
}
/**
* Why the backend declared a connection's pools dead while the app was idle (#4339).
* A stable enum by design: raw driver/network error text must not reach a background
* UI notification.
*/
export type ConnectionLivenessFailureKind = "probe_failed" | "timed_out";
/**
* A message on the backend connection-liveness channel (#4339).
*
* Mirrors the Rust `ConnectionLivenessMessage`, and both transports deliver this exact shape:
* the desktop shell forwards it unwrapped and the web SSE stream sends the object itself, so
* there is no envelope beyond the message's own `kind` discriminator.
*
* `resync` means the transport skipped messages, so the frontend must re-check every
* connection it still shows as connected — without it, a dropped `lost` would leave a
* sidebar green indefinitely.
*/
export type ConnectionLivenessMessage = { kind: "lost"; connectionId: string; failureKind: ConnectionLivenessFailureKind } | { kind: "resync" };
export type TransportLayerConfig = ({ type: "ssh" } & SshTunnelConfig) | ({ type: "proxy" } & ProxyTunnelConfig) | ({ type: "http_tunnel" } & HttpTunnelConfig);
/**