feat(plugins): improve connection lifecycle and session tabs
This commit is contained in:
1 parent
6be8d5544e
commit
1321dc9b9d
25 files changed
+849
-44
No files matched your search
+33
-1
@@ -1,6 +1,16 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { InstalledPlugin, PluginConnectionProviderContribution, PluginFormFieldValue } from "@/types/database";
|
||||
import { buildPluginConnectionConfig, createFrontendPluginRegistry, initialPluginFormValues, parsePluginConnectionProviderOptionValue, pluginConnectionActionsForDialog, pluginConnectionFormValues, pluginConnectionProviderIcon, pluginConnectionProviderOptionValue } from "./frontendPlugin";
|
||||
import {
|
||||
buildPluginConnectionConfig,
|
||||
createFrontendPluginRegistry,
|
||||
initialPluginFormValues,
|
||||
parsePluginConnectionProviderOptionValue,
|
||||
pluginConnectionActionsForDialog,
|
||||
pluginConnectionConnectTimeoutDefault,
|
||||
pluginConnectionFormValues,
|
||||
pluginConnectionProviderIcon,
|
||||
pluginConnectionProviderOptionValue,
|
||||
} from "./frontendPlugin";
|
||||
|
||||
function installedPlugin(id: string, contributions: InstalledPlugin["manifest"]["contributions"] = []): InstalledPlugin {
|
||||
return {
|
||||
@@ -70,6 +80,28 @@ describe("FrontendPluginRegistry", () => {
|
||||
expect(transient.save_password).toBe(false);
|
||||
});
|
||||
|
||||
it("materializes the provider's connect_timeout_secs default into the typed timeout", () => {
|
||||
const provider = connectionProvider({
|
||||
fields: [{ key: "connect_timeout_secs", label: "Connect timeout", type: "number", default: 30 }],
|
||||
});
|
||||
expect(pluginConnectionConnectTimeoutDefault(provider)).toBe(30);
|
||||
expect(buildPluginConnectionConfig("example.plugin", provider, {}).connect_timeout_secs).toBe(30);
|
||||
// An advanced-form value the user tuned is mirrored into the typed field too.
|
||||
expect(buildPluginConnectionConfig("example.plugin", provider, { connect_timeout_secs: 60 }).connect_timeout_secs).toBe(60);
|
||||
|
||||
// Once the provider declares the field, its resolved value is the single
|
||||
// source of truth: a stale typed value from before the declaration is
|
||||
// healed to the declared default.
|
||||
const existing = buildPluginConnectionConfig("example.plugin", connectionProvider({ fields: [] }), {});
|
||||
existing.connect_timeout_secs = 7;
|
||||
expect(buildPluginConnectionConfig("example.plugin", provider, {}, existing).connect_timeout_secs).toBe(30);
|
||||
|
||||
// Providers without the well-known field keep the generic 10s default.
|
||||
const generic = connectionProvider({ fields: [] });
|
||||
expect(pluginConnectionConnectTimeoutDefault(generic)).toBeUndefined();
|
||||
expect(buildPluginConnectionConfig("example.plugin", generic, {}).connect_timeout_secs).toBe(10);
|
||||
});
|
||||
|
||||
it("round-trips plugin connection provider picker values", () => {
|
||||
const value = pluginConnectionProviderOptionValue("example/plugin", "ssh:main");
|
||||
expect(parsePluginConnectionProviderOptionValue(value)).toEqual({ pluginId: "example/plugin", providerId: "ssh:main" });
|
||||
|
||||
@@ -105,6 +105,22 @@ export function pluginConnectionProviderIcon(entry: PluginContributionEntry<Plug
|
||||
return entry.contribution.icon || entry.plugin.manifest.icon;
|
||||
}
|
||||
|
||||
/**
|
||||
* Well-known provider field key whose declared default seeds the typed
|
||||
* `ConnectionConfig.connect_timeout_secs`. A plugin knows its own transport
|
||||
* (SSH handshakes on slow links need far more than the generic 10s), so a
|
||||
* declared default wins over the global timeout unless the user explicitly
|
||||
* picks a per-connection value in the dialog's Advanced tab.
|
||||
*/
|
||||
export const PLUGIN_CONNECT_TIMEOUT_FIELD_KEY = "connect_timeout_secs";
|
||||
|
||||
export function pluginConnectionConnectTimeoutDefault(contribution: PluginConnectionProviderContribution): number | undefined {
|
||||
const field = contribution.fields.find((candidate) => candidate.key === PLUGIN_CONNECT_TIMEOUT_FIELD_KEY && effectiveFieldBinding(candidate) === "config");
|
||||
const value = field?.default;
|
||||
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return undefined;
|
||||
return Math.min(300, Math.max(1, Math.trunc(value)));
|
||||
}
|
||||
|
||||
export function pluginConnectionActionsForDialog(contribution: PluginConnectionProviderContribution, editing: boolean): PluginConnectionAction[] {
|
||||
const actions: PluginConnectionAction[] = [
|
||||
...(contribution.actions || []).map((action) => ({ ...action, kind: "custom" as const })),
|
||||
@@ -159,7 +175,7 @@ export function buildPluginConnectionConfig(pluginId: string, contribution: Plug
|
||||
plugin_connection_type: contribution.database_type,
|
||||
connection_secrets: connectionSecrets,
|
||||
transport_layers: existing?.transport_layers || [],
|
||||
connect_timeout_secs: existing?.connect_timeout_secs || 10,
|
||||
connect_timeout_secs: existing?.connect_timeout_secs || pluginConnectionConnectTimeoutDefault(contribution) || 10,
|
||||
query_timeout_secs: existing?.query_timeout_secs || 60,
|
||||
idle_timeout_secs: existing?.idle_timeout_secs || 60,
|
||||
keepalive_interval_secs: existing?.keepalive_interval_secs || 30,
|
||||
@@ -198,6 +214,17 @@ export function buildPluginConnectionConfig(pluginId: string, contribution: Plug
|
||||
config.database = value === undefined || value === "" ? undefined : String(value);
|
||||
}
|
||||
}
|
||||
// A config-bound connect_timeout_secs field is the plugin's own handshake
|
||||
// timeout (the SSH plugin lets advanced users tune it). Mirror the resolved
|
||||
// value into the typed field so the host RPC deadline never fires before the
|
||||
// plugin's own timeout. Only applies while the provider declares the field —
|
||||
// a stale external_config key from an older manifest must not leak through.
|
||||
if (pluginConnectionConnectTimeoutDefault(contribution) !== undefined) {
|
||||
const pluginConnectTimeout = externalConfig[PLUGIN_CONNECT_TIMEOUT_FIELD_KEY];
|
||||
if (typeof pluginConnectTimeout === "number" && Number.isFinite(pluginConnectTimeout) && pluginConnectTimeout > 0) {
|
||||
config.connect_timeout_secs = Math.min(300, Math.max(1, Math.trunc(pluginConnectTimeout)));
|
||||
}
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,55 @@ describe("PluginHostBridge", () => {
|
||||
expect(messages[0]).toMatchObject({ source: "dbx-host", type: "init", locale: "zh-CN", context: { connectionId: "connection" } });
|
||||
});
|
||||
|
||||
it("runs onReinit before the init message when the iframe reloads", async () => {
|
||||
const messages: unknown[] = [];
|
||||
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
|
||||
const bridge = new PluginHostBridge(plugin(), workbench, {}, () => target, {
|
||||
invoke: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
sendBinary: vi.fn(),
|
||||
readAsset: vi.fn(),
|
||||
});
|
||||
const ready = () => bridge.handleWindowMessage({ source: target, data: { source: "dbx-plugin", version: 1, type: "ready" } } as MessageEvent);
|
||||
|
||||
const order: string[] = [];
|
||||
bridge.onReinit = () =>
|
||||
new Promise<void>((resolve) => {
|
||||
order.push("reinit");
|
||||
setTimeout(resolve, 5);
|
||||
});
|
||||
const originalPost = target.postMessage.bind(target);
|
||||
(target as { postMessage: (m: unknown) => void }).postMessage = (message: unknown) => {
|
||||
if ((message as { type?: string }).type === "init") order.push("init");
|
||||
originalPost(message);
|
||||
};
|
||||
|
||||
expect(ready()).toBe(true);
|
||||
await vi.waitFor(() => expect(messages).toHaveLength(1));
|
||||
expect(order).toEqual(["reinit", "init"]);
|
||||
});
|
||||
|
||||
it("initializes only once when ready is repeated for the same bridge", async () => {
|
||||
const messages: unknown[] = [];
|
||||
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
|
||||
const bridge = new PluginHostBridge(plugin(), workbench, {}, () => target, {
|
||||
invoke: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
sendBinary: vi.fn(),
|
||||
readAsset: vi.fn(),
|
||||
});
|
||||
const onReinit = vi.fn();
|
||||
bridge.onReinit = onReinit;
|
||||
const ready = () => bridge.handleWindowMessage({ source: target, data: { source: "dbx-plugin", version: 1, type: "ready" } } as MessageEvent);
|
||||
|
||||
ready();
|
||||
await vi.waitFor(() => expect(messages).toHaveLength(1));
|
||||
ready();
|
||||
|
||||
expect(onReinit).toHaveBeenCalledTimes(1);
|
||||
expect(messages).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("snapshots nested Vue reactive context values before sending them to the plugin", () => {
|
||||
const messages: unknown[] = [];
|
||||
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
|
||||
@@ -135,6 +184,69 @@ describe("PluginHostBridge", () => {
|
||||
expect(messages[0]).toMatchObject({ id: "2", error: "Plugin has not declared permission 'host.workbench'" });
|
||||
});
|
||||
|
||||
it("passes forceNew through host.openWorkbench and defaults it to false", async () => {
|
||||
const messages: unknown[] = [];
|
||||
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
|
||||
const openWorkbench = vi.fn();
|
||||
const bridge = new PluginHostBridge(plugin(["host.workbench"]), workbench, {}, () => target, {
|
||||
invoke: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
sendBinary: vi.fn(),
|
||||
readAsset: vi.fn(),
|
||||
openWorkbench,
|
||||
});
|
||||
const request = (id: string, params: unknown) =>
|
||||
bridge.handleWindowMessage({
|
||||
source: target,
|
||||
data: { source: "dbx-plugin", version: 1, type: "request", id, method: "host.openWorkbench", params },
|
||||
} as MessageEvent);
|
||||
|
||||
request("new", { contributionId: "sample.other", context: { connectionId: "c1" }, forceNew: true });
|
||||
await vi.waitFor(() => expect(messages).toHaveLength(1));
|
||||
expect(openWorkbench).toHaveBeenNthCalledWith(1, "sample", "sample.other", { connectionId: "c1" }, { forceNew: true });
|
||||
expect(messages[0]).toMatchObject({ id: "new", result: null });
|
||||
|
||||
request("default", { contributionId: "sample.other" });
|
||||
await vi.waitFor(() => expect(messages).toHaveLength(2));
|
||||
expect(openWorkbench).toHaveBeenNthCalledWith(2, "sample", "sample.other", undefined, { forceNew: false });
|
||||
});
|
||||
|
||||
it("reopens a plugin connection through host.reopenConnection", async () => {
|
||||
const messages: unknown[] = [];
|
||||
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
|
||||
const reopenConnection = vi.fn().mockResolvedValue(undefined);
|
||||
const bridge = new PluginHostBridge(plugin(), workbench, {}, () => target, {
|
||||
invoke: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
sendBinary: vi.fn(),
|
||||
readAsset: vi.fn(),
|
||||
reopenConnection,
|
||||
});
|
||||
const request = (id: string, params: unknown) =>
|
||||
bridge.handleWindowMessage({
|
||||
source: target,
|
||||
data: { source: "dbx-plugin", version: 1, type: "request", id, method: "host.reopenConnection", params },
|
||||
} as MessageEvent);
|
||||
|
||||
request("reopen", { connectionId: "9f1c2a34-0000-4000-8000-abcdef012345" });
|
||||
await vi.waitFor(() => expect(messages).toHaveLength(1));
|
||||
expect(reopenConnection).toHaveBeenCalledWith("sample", "9f1c2a34-0000-4000-8000-abcdef012345");
|
||||
expect(messages[0]).toMatchObject({ id: "reopen", result: { ok: true } });
|
||||
|
||||
// Missing/invalid connectionId is rejected before reaching the host.
|
||||
request("missing", {});
|
||||
await vi.waitFor(() => expect(messages).toHaveLength(2));
|
||||
expect(messages[1]).toMatchObject({ id: "missing" });
|
||||
expect((messages[1] as { error?: string }).error).toContain("connectionId");
|
||||
|
||||
// Host-side failures (connection missing, not plugin-backed, connect
|
||||
// failed) surface as the request error so the plugin can show them.
|
||||
reopenConnection.mockRejectedValueOnce(new Error("Connection is not plugin-backed"));
|
||||
request("not-plugin", { connectionId: "mysql-1" });
|
||||
await vi.waitFor(() => expect(messages).toHaveLength(3));
|
||||
expect(messages[2]).toMatchObject({ id: "not-plugin", error: "Connection is not plugin-backed" });
|
||||
});
|
||||
|
||||
it("opens only the owning plugin filesystem with explicit permission", async () => {
|
||||
const messages: unknown[] = [];
|
||||
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
|
||||
|
||||
@@ -38,8 +38,10 @@ export interface PluginHostBridgeApi {
|
||||
notify(pluginId: string, method: string, params?: unknown): Promise<void>;
|
||||
sendBinary(pluginId: string, channel: string, dataBase64: string): Promise<void>;
|
||||
readAsset(pluginId: string, path: string): Promise<PluginUiAssetPayload>;
|
||||
openWorkbench?(pluginId: string, contributionId: string, context?: PluginWorkbenchContext): Promise<void> | void;
|
||||
openWorkbench?(pluginId: string, contributionId: string, context?: PluginWorkbenchContext, options?: { forceNew?: boolean }): Promise<void> | void;
|
||||
openFilesystem?(pluginId: string, providerId: string, context?: PluginWorkbenchContext): Promise<void> | void;
|
||||
/** Explicit user-triggered reconnect of an owned plugin connection (full flow, interactive password prompt allowed). */
|
||||
reopenConnection?(pluginId: string, connectionId: string): Promise<void>;
|
||||
closeTab?(): Promise<void> | void;
|
||||
/** Persist plugin bytes through the host's native save dialog. Resolves null when the user cancels. */
|
||||
saveFile?(pluginId: string, request: PluginSaveFileRequest, data: Uint8Array): Promise<PluginSaveFileResult | null>;
|
||||
@@ -63,6 +65,9 @@ export class PluginHostBridge {
|
||||
private locale: string;
|
||||
private theme?: PluginBridgeTheme;
|
||||
|
||||
/** Invoked once before each iframe load generation sends its init message. */
|
||||
onReinit?: () => Promise<void> | void;
|
||||
|
||||
constructor(
|
||||
private readonly plugin: InstalledPlugin,
|
||||
private readonly workbench: PluginWorkbenchContribution,
|
||||
@@ -82,7 +87,7 @@ export class PluginHostBridge {
|
||||
if (!target || event.source !== target || !isRecord(event.data)) return false;
|
||||
if (event.data.source !== PLUGIN_MESSAGE_SOURCE || event.data.version !== BRIDGE_VERSION) return false;
|
||||
if (event.data.type === "ready") {
|
||||
this.sendInit();
|
||||
void this.handleReady();
|
||||
return true;
|
||||
}
|
||||
if (event.data.type === "shortcut" && event.data.shortcut === "closeTab") {
|
||||
@@ -94,7 +99,52 @@ export class PluginHostBridge {
|
||||
return true;
|
||||
}
|
||||
|
||||
private handleReady(): void {
|
||||
this.requestInit("ready");
|
||||
}
|
||||
|
||||
sendInit(): void {
|
||||
this.requestInit("load");
|
||||
}
|
||||
|
||||
private requestInit(signal: "load" | "ready"): void {
|
||||
if ((this.initSignals.load && this.initSignals.ready) || (signal === "load" && this.initSignals.load)) {
|
||||
this.initGeneration += 1;
|
||||
this.initSignals = { load: false, ready: false };
|
||||
this.initStarted = false;
|
||||
}
|
||||
if (this.initSignals[signal]) return;
|
||||
this.initSignals[signal] = true;
|
||||
if (this.initStarted) return;
|
||||
this.initStarted = true;
|
||||
const generation = this.initGeneration;
|
||||
const reinit = this.onReinit;
|
||||
if (!reinit) {
|
||||
if (!this.disposed && generation === this.initGeneration) this.postInit();
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
await reinit();
|
||||
} catch (error) {
|
||||
console.warn("[DBX][plugin-bridge:reinit]", error);
|
||||
}
|
||||
// A newer load generation supersedes this one; never post a stale init.
|
||||
if (!this.disposed && generation === this.initGeneration) this.postInit();
|
||||
})();
|
||||
}
|
||||
|
||||
/** Stop future posts (queued inits after an async reinit) for a torn-down bridge. */
|
||||
dispose(): void {
|
||||
this.disposed = true;
|
||||
}
|
||||
|
||||
private disposed = false;
|
||||
private initGeneration = 0;
|
||||
private initSignals = { load: false, ready: false };
|
||||
private initStarted = false;
|
||||
|
||||
private postInit(): void {
|
||||
this.post({
|
||||
source: HOST_MESSAGE_SOURCE,
|
||||
version: BRIDGE_VERSION,
|
||||
@@ -186,9 +236,15 @@ export class PluginHostBridge {
|
||||
this.requirePermission("host.workbench");
|
||||
if (!this.api.openWorkbench) throw new Error("Host workbench navigation is unavailable");
|
||||
const input = requireRecord(params, "host.openWorkbench params");
|
||||
await this.api.openWorkbench(this.plugin.manifest.id, requireProtocolName(input.contributionId, "workbench contribution"), isRecord(input.context) ? input.context : undefined);
|
||||
await this.api.openWorkbench(this.plugin.manifest.id, requireProtocolName(input.contributionId, "workbench contribution"), isRecord(input.context) ? input.context : undefined, { forceNew: input.forceNew === true });
|
||||
return null;
|
||||
}
|
||||
if (method === "host.reopenConnection") {
|
||||
if (!this.api.reopenConnection) throw new Error("Connection reopen is unavailable");
|
||||
const input = requireRecord(params, "host.reopenConnection params");
|
||||
await this.api.reopenConnection(this.plugin.manifest.id, requireProtocolName(input.connectionId, "connectionId"));
|
||||
return { ok: true };
|
||||
}
|
||||
if (method === "host.openFilesystem") {
|
||||
this.requirePermission("host.filesystem");
|
||||
if (!this.api.openFilesystem) throw new Error("Host filesystem navigation is unavailable");
|
||||
@@ -498,8 +554,9 @@ export function pluginSdkSource(initialTheme?: PluginBridgeTheme): string {
|
||||
const asset = await request('ui.readAsset', { path });
|
||||
return URL.createObjectURL(new Blob([decode(asset.dataBase64)], { type: asset.contentType }));
|
||||
},
|
||||
openWorkbench: (contributionId, childContext) => request('host.openWorkbench', { contributionId, context: childContext }),
|
||||
openWorkbench: (contributionId, childContext, options) => request('host.openWorkbench', { contributionId, context: childContext, forceNew: !!(options && options.forceNew) }),
|
||||
openFilesystem: (providerId, childContext) => request('host.openFilesystem', { providerId, context: childContext }),
|
||||
reopenConnection: (connectionId) => request('host.reopenConnection', { connectionId }),
|
||||
saveFile: (options = {}, data) => {
|
||||
if (data === undefined) return request('host.saveFile', options);
|
||||
if (typeof data === 'string') return request('host.saveFile', { ...(options || {}), dataBase64: data });
|
||||
|
||||
Reference in new issue
Block a user