feat(connection): notify sidebar when keepalive loses connection
This commit is contained in:
1 parent
3ffff92c8f
commit
dc503877f9
13 files changed
+864
-27
No files matched your search
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user