perf(execution): prewarm tab session pools and report perceived wait
This commit is contained in:
17 files changed
+558
-29
No files matched your search
@@ -0,0 +1,114 @@
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ConnectionConfig } from "@/types/database";
|
||||
|
||||
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)),
|
||||
});
|
||||
}
|
||||
|
||||
function postgresConnection(): ConnectionConfig {
|
||||
return {
|
||||
id: "pg-1",
|
||||
name: "Postgres",
|
||||
db_type: "postgres",
|
||||
host: "127.0.0.1",
|
||||
port: 5432,
|
||||
username: "postgres",
|
||||
password: "",
|
||||
database: "app",
|
||||
} as ConnectionConfig;
|
||||
}
|
||||
|
||||
function installApiMocks(prewarmConnection: ReturnType<typeof vi.fn>) {
|
||||
vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
|
||||
vi.doMock("@/lib/backend/api", () => ({
|
||||
checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
|
||||
deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
|
||||
getColumns: vi.fn().mockResolvedValue([]),
|
||||
listInstalledAgents: vi.fn().mockResolvedValue([]),
|
||||
listObjects: vi.fn().mockResolvedValue([]),
|
||||
listTables: vi.fn().mockResolvedValue([]),
|
||||
loadSchemaCache: vi.fn().mockResolvedValue(null),
|
||||
prewarmConnection,
|
||||
saveConnections: vi.fn().mockResolvedValue(undefined),
|
||||
saveSchemaCache: vi.fn().mockResolvedValue(undefined),
|
||||
saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
}
|
||||
|
||||
async function createStore() {
|
||||
const { useConnectionStore } = await import("@/stores/connectionStore");
|
||||
const store = useConnectionStore();
|
||||
const connection = postgresConnection();
|
||||
store.connections = [connection];
|
||||
store.connectedIds.add(connection.id);
|
||||
return store;
|
||||
}
|
||||
|
||||
describe("connectionStore driver prewarm", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.unstubAllGlobals();
|
||||
installLocalStorage();
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("warms the driver once per pool target and skips unconnected connections", async () => {
|
||||
const prewarmConnection = vi.fn().mockResolvedValue(undefined);
|
||||
installApiMocks(prewarmConnection);
|
||||
const store = await createStore();
|
||||
|
||||
store.warmConnection("pg-1", { database: "app" });
|
||||
store.warmConnection("pg-1", { database: "app" });
|
||||
store.warmConnection("pg-1", { database: "app", clientSessionId: "tab-1" });
|
||||
store.warmConnection("unknown", { database: "app" });
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(prewarmConnection).toHaveBeenCalledTimes(2);
|
||||
expect(prewarmConnection).toHaveBeenCalledWith("pg-1", "app", undefined, undefined);
|
||||
expect(prewarmConnection).toHaveBeenCalledWith("pg-1", "app", undefined, "tab-1");
|
||||
});
|
||||
|
||||
it("does not surface warm-up failures and retries with a fresh attempt", async () => {
|
||||
const prewarmConnection = vi.fn().mockRejectedValueOnce(new Error("driver unavailable")).mockResolvedValue(undefined);
|
||||
installApiMocks(prewarmConnection);
|
||||
const store = await createStore();
|
||||
|
||||
expect(() => store.warmConnection("pg-1", { database: "app" })).not.toThrow();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
store.warmConnection("pg-1", { database: "app" });
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(prewarmConnection).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("forgets warm-up bookkeeping when a connection is torn down", async () => {
|
||||
const prewarmConnection = vi.fn().mockResolvedValue(undefined);
|
||||
installApiMocks(prewarmConnection);
|
||||
const store = await createStore();
|
||||
const waitForCall = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
store.warmConnection("pg-1", { database: "app", clientSessionId: "tab-1" });
|
||||
await waitForCall();
|
||||
expect(prewarmConnection).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Inside the TTL window the second request is deduplicated.
|
||||
store.warmConnection("pg-1", { database: "app", clientSessionId: "tab-1" });
|
||||
await waitForCall();
|
||||
expect(prewarmConnection).toHaveBeenCalledTimes(1);
|
||||
|
||||
// The pool is gone after a teardown, so the next warm-up must run again
|
||||
// instead of trusting the stale timestamp.
|
||||
store.markConnectionOffline("pg-1");
|
||||
store.connectedIds.add("pg-1");
|
||||
store.warmConnection("pg-1", { database: "app", clientSessionId: "tab-1" });
|
||||
await waitForCall();
|
||||
expect(prewarmConnection).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -209,6 +209,9 @@ const ACTIVE_CONNECTION_STORAGE_KEY = "dbx-active-connection";
|
||||
const SIDEBAR_TABLE_NAME_FILTERS_STORAGE_KEY = "dbx-sidebar-table-name-filters";
|
||||
const CONNECTION_HEALTH_CHECK_TTL_MS = 2000;
|
||||
const CONNECTION_HEALTH_CHECK_TIMEOUT_MS = 5000;
|
||||
/** How long a successful driver/pool warm-up is trusted before the next tab
|
||||
* activation warms the same pool target again. */
|
||||
const CONNECTION_PREWARM_TTL_MS = 30_000;
|
||||
const METADATA_LOAD_MIN_TIMEOUT_MS = 15_000;
|
||||
const METADATA_LOAD_DISABLED_QUERY_TIMEOUT_MS = 60_000;
|
||||
const DISCONNECT_REQUEST_TIMEOUT_MS = 5_000;
|
||||
@@ -495,6 +498,11 @@ export const useConnectionStore = defineStore("connection", () => {
|
||||
const databaseCompatibilityModes = ref<Record<string, string>>({});
|
||||
const databaseCompatibilityRefreshes = new Map<string, Promise<void>>();
|
||||
const lastConnectionHealthCheckAt = ref<Record<string, number>>({});
|
||||
/** Per pool-target timestamp of the last successful driver/pool warm-up (see
|
||||
* `warmConnection`). Fire-and-forget: a skipped warm-up only means the pool is
|
||||
* created by the first real request instead. */
|
||||
const lastConnectionPrewarmAt = ref<Record<string, number>>({});
|
||||
const connectionPrewarmInFlight = new Map<string, Promise<void>>();
|
||||
const agentDrivers = ref<AgentDriverInstallState[]>([]);
|
||||
let agentDriversRefreshPromise: Promise<void> | null = null;
|
||||
let localAgentDriversRefreshPromise: Promise<void> | null = null;
|
||||
@@ -1318,6 +1326,58 @@ export const useConnectionStore = defineStore("connection", () => {
|
||||
return typeof checkedAt === "number" && Date.now() - checkedAt < CONNECTION_HEALTH_CHECK_TTL_MS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Forgets warm-up bookkeeping for a connection. The backend pool is gone once a
|
||||
* connection is torn down, so a remembered timestamp must not make
|
||||
* `warmConnection` skip a warm-up that the next execution would then pay for.
|
||||
*/
|
||||
function clearConnectionPrewarmState(connectionId: string) {
|
||||
const prefix = `${connectionId}\u0000`;
|
||||
for (const key of Object.keys(lastConnectionPrewarmAt.value)) {
|
||||
if (key.startsWith(prefix)) delete lastConnectionPrewarmAt.value[key];
|
||||
}
|
||||
for (const key of connectionPrewarmInFlight.keys()) {
|
||||
if (key.startsWith(prefix)) connectionPrewarmInFlight.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
function connectionPrewarmKey(connectionId: string, target: { database?: string; catalog?: string; clientSessionId?: string }) {
|
||||
return [connectionId, target.database ?? "", target.catalog ?? "", target.clientSessionId ?? ""].join("\u0000");
|
||||
}
|
||||
|
||||
/**
|
||||
* Warm the driver and connection pool for a connection a tab is about to use.
|
||||
*
|
||||
* Opening a SQL editor tab used to do nothing until the user pressed Run, so
|
||||
* the first execution paid pool creation, tunnel setup, and — for externally
|
||||
* driven databases such as Oracle — JDBC driver/agent startup. Those seconds
|
||||
* were visible in the loading indicator but are outside the statement timer,
|
||||
* which is why the summary could read "23ms" after a multi-second wait.
|
||||
* Warming in the background moves that cost off the critical path. Failures
|
||||
* are ignored here because the real request reports them with full context.
|
||||
*/
|
||||
function warmConnection(connectionId: string, target: { database?: string; catalog?: string; clientSessionId?: string } = {}) {
|
||||
if (!connectionId || !connectedIds.value.has(connectionId)) return;
|
||||
const key = connectionPrewarmKey(connectionId, target);
|
||||
const warmedAt = lastConnectionPrewarmAt.value[key];
|
||||
if (typeof warmedAt === "number" && Date.now() - warmedAt < CONNECTION_PREWARM_TTL_MS) return;
|
||||
if (connectionPrewarmInFlight.has(key)) return;
|
||||
const promise = api
|
||||
.prewarmConnection(connectionId, target.database, target.catalog, target.clientSessionId)
|
||||
.then(() => {
|
||||
lastConnectionPrewarmAt.value[key] = Date.now();
|
||||
})
|
||||
.catch(() => {
|
||||
// A failed warm-up is not a user-facing error: the next real request
|
||||
// rebuilds the pool and surfaces any genuine failure itself.
|
||||
})
|
||||
.finally(() => {
|
||||
connectionPrewarmInFlight.delete(key);
|
||||
});
|
||||
connectionPrewarmInFlight.set(key, promise);
|
||||
void promise;
|
||||
}
|
||||
|
||||
function clearConnectionNodeLoading(connectionId: string) {
|
||||
const node = findConnectionNode(connectionId);
|
||||
if (node) node.isLoading = false;
|
||||
@@ -4382,6 +4442,7 @@ export const useConnectionStore = defineStore("connection", () => {
|
||||
clearPrimaryVisibleObjectNames(connectionId);
|
||||
clearConnectionIdentifierQuote(connectionId);
|
||||
clearConnectionHealthCheck(connectionId);
|
||||
clearConnectionPrewarmState(connectionId);
|
||||
if (activeConnectionId.value === connectionId) activeConnectionId.value = null;
|
||||
invalidateCompletionCache(connectionId);
|
||||
cancelObjectDdlLoadsForConnection(connectionId);
|
||||
@@ -4403,6 +4464,7 @@ export const useConnectionStore = defineStore("connection", () => {
|
||||
node.isLoading = false;
|
||||
}
|
||||
clearConnectionHealthCheck(connectionId);
|
||||
clearConnectionPrewarmState(connectionId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4426,6 +4488,7 @@ export const useConnectionStore = defineStore("connection", () => {
|
||||
clearConnectionIdentifierQuote(connectionId);
|
||||
forgetSuccessfulLocalConnectionAttempt(connectionId);
|
||||
clearConnectionHealthCheck(connectionId);
|
||||
clearConnectionPrewarmState(connectionId);
|
||||
const node = findConnectionNode(connectionId);
|
||||
if (node) {
|
||||
node.isLoading = false;
|
||||
@@ -9714,6 +9777,7 @@ export const useConnectionStore = defineStore("connection", () => {
|
||||
hasSessionCredential,
|
||||
closeDatabaseConnection,
|
||||
ensureConnected,
|
||||
warmConnection,
|
||||
loadConnectedConnectionRootForSidebarSearch,
|
||||
isTreeNodeChildrenLoaded,
|
||||
canUseLoadedTreeNodeToggle,
|
||||
|
||||
Reference in new issue
Block a user