Skip to content

Commit ccd6845

Browse files
authored
perf(plugins): memoize channel catalog discovery (#114324)
1 parent 885121b commit ccd6845

3 files changed

Lines changed: 188 additions & 32 deletions

File tree

‎src/gateway/config-reload.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
loadInstalledPluginIndexInstallRecords,
2929
loadInstalledPluginIndexInstallRecordsSync,
3030
} from "../plugins/installed-plugin-index-records.js";
31+
import { clearPluginMetadataLifecycleCaches } from "../plugins/plugin-metadata-lifecycle.js";
3132
import { bumpSkillsSnapshotVersion } from "../skills/runtime/refresh-state.js";
3233
import { createConfigAppliedRevisionTracker } from "./config-applied-revision.js";
3334
import { diffConfigPaths, diffGatewayReloadPaths } from "./config-diff.js";
@@ -1249,6 +1250,7 @@ export function startGatewayConfigReloader(opts: {
12491250
// The signal carries a metadata change while config bytes stay identical.
12501251
// Clear both metadata and config-echo caches before scheduling the shared diff path.
12511252
clearLoadInstalledPluginIndexInstallRecordsCache();
1253+
clearPluginMetadataLifecycleCaches();
12521254
startupInternalWriteHash = null;
12531255
lastAppliedWriteHash = null;
12541256
scheduleExternalRefresh();

‎src/plugins/channel-catalog-registry.test.ts‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ async function loadWithMocks(params: {
3434
loadRecords?: (env: NodeJS.ProcessEnv | undefined) => Record<string, PluginInstallRecord>;
3535
}): Promise<{
3636
module: typeof import("./channel-catalog-registry.js");
37+
lifecycle: typeof import("./plugin-metadata-lifecycle.js");
3738
discoverSpy: ReturnType<typeof vi.fn>;
3839
loadRecordsSpy: ReturnType<typeof vi.fn>;
3940
}> {
@@ -51,7 +52,8 @@ async function loadWithMocks(params: {
5152
import.meta.url,
5253
`./channel-catalog-registry.js?case=${++loadCase}`,
5354
);
54-
return { module, discoverSpy, loadRecordsSpy };
55+
const lifecycle = await import("./plugin-metadata-lifecycle.js");
56+
return { module, lifecycle, discoverSpy, loadRecordsSpy };
5557
}
5658

5759
function firstDiscoverOptions(discoverSpy: ReturnType<typeof vi.fn>): Record<string, unknown> {
@@ -91,6 +93,55 @@ function createChannelCandidate(params: {
9193
}
9294

9395
describe("listChannelCatalogEntries", () => {
96+
it("reuses one discovery result for repeated calls in the same scope", async () => {
97+
const { module, discoverSpy, loadRecordsSpy } = await loadWithMocks({});
98+
99+
module.listChannelCatalogEntries({ env: ENV });
100+
module.listChannelCatalogEntries({ env: ENV });
101+
102+
expect(discoverSpy).toHaveBeenCalledTimes(1);
103+
expect(loadRecordsSpy).toHaveBeenCalledTimes(1);
104+
});
105+
106+
it("clears the discovery memo through the plugin metadata lifecycle owner", async () => {
107+
const { module, lifecycle, discoverSpy } = await loadWithMocks({});
108+
109+
module.listChannelCatalogEntries({ origin: "bundled", env: ENV });
110+
lifecycle.clearPluginMetadataLifecycleCaches();
111+
module.listChannelCatalogEntries({ origin: "bundled", env: ENV });
112+
113+
expect(discoverSpy).toHaveBeenCalledTimes(2);
114+
});
115+
116+
it("does not share discovery across differing input scopes", async () => {
117+
const { module, discoverSpy } = await loadWithMocks({});
118+
const installRecords = {};
119+
const baseline = {
120+
env: ENV,
121+
workspaceDir: "/tmp/workspace-a",
122+
extraPaths: ["/tmp/plugins/a"],
123+
installRecords,
124+
};
125+
const otherInstallRecords: Record<string, PluginInstallRecord> = {};
126+
127+
module.listChannelCatalogEntries(baseline);
128+
module.listChannelCatalogEntries({ ...baseline, workspaceDir: "/tmp/workspace-b" });
129+
module.listChannelCatalogEntries({
130+
...baseline,
131+
env: { HOME: "/tmp/openclaw-other-home" },
132+
});
133+
module.listChannelCatalogEntries({ ...baseline, extraPaths: ["/tmp/plugins/b"] });
134+
module.listChannelCatalogEntries({ ...baseline, installRecords: otherInstallRecords });
135+
module.listChannelCatalogEntries({ ...baseline, installRecords: otherInstallRecords });
136+
otherInstallRecords.telegram = {
137+
source: "npm",
138+
spec: "@openclaw/[email protected]",
139+
} as PluginInstallRecord;
140+
module.listChannelCatalogEntries({ ...baseline, installRecords: otherInstallRecords });
141+
142+
expect(discoverSpy).toHaveBeenCalledTimes(6);
143+
});
144+
94145
it("forwards lazily loaded install records to discovery when origin is unspecified", async () => {
95146
const { module, discoverSpy, loadRecordsSpy } = await loadWithMocks({});
96147

Lines changed: 134 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
// Maintains channel catalog entries advertised by plugins.
22
import { normalizeOptionalString as resolveOptionalString } from "@openclaw/normalization-core/string-coerce";
3+
import { resolveIsNixMode } from "../config/paths.js";
34
import type { PluginInstallRecord } from "../config/types.plugins.js";
5+
import { resolveCompatibilityHostVersion } from "../version.js";
46
import { discoverOpenClawPlugins, type PluginDiscoveryResult } from "./discovery.js";
57
import { loadInstalledPluginIndexInstallRecordsSync } from "./installed-plugin-index-record-reader.js";
68
import type { PluginPackageChannel, PluginPackageInstall } from "./manifest.js";
9+
import { resolvePluginDiscoveryContext } from "./plugin-control-plane-context.js";
10+
import { registerPluginMetadataProcessMemoLifecycleClear } from "./plugin-metadata-lifecycle.js";
711
import type { PluginOrigin } from "./plugin-origin.types.js";
812

913
export type PluginChannelCatalogEntry = {
@@ -16,31 +20,53 @@ export type PluginChannelCatalogEntry = {
1620
install?: PluginPackageInstall;
1721
};
1822

23+
type ChannelCatalogParams = {
24+
origin?: PluginOrigin;
25+
workspaceDir?: string;
26+
env?: NodeJS.ProcessEnv;
27+
extraPaths?: string[];
28+
/**
29+
* Optional override. When omitted and `origin !== "bundled"`, the persisted
30+
* plugin install ledger is loaded synchronously so that npm-installed
31+
* channels stored outside the discovery roots are visible to the catalog.
32+
* Bundled-only callers skip the load to avoid the disk read.
33+
*/
34+
installRecords?: Record<string, PluginInstallRecord>;
35+
discovery?: PluginDiscoveryResult;
36+
};
37+
38+
const defaultInstallRecordsIdentity = Symbol("default-install-records");
39+
const noInstallRecordsIdentity = Symbol("no-install-records");
40+
41+
type ChannelCatalogDiscoveryMemo = {
42+
scopeKey: string;
43+
installRecordsIdentity:
44+
| Record<string, PluginInstallRecord>
45+
| typeof defaultInstallRecordsIdentity
46+
| typeof noInstallRecordsIdentity;
47+
installRecordsFingerprint?: string;
48+
discovery: PluginDiscoveryResult;
49+
};
50+
51+
let channelCatalogDiscoveryMemo: ChannelCatalogDiscoveryMemo | undefined;
52+
53+
function clearChannelCatalogDiscoveryMemo(): void {
54+
channelCatalogDiscoveryMemo = undefined;
55+
}
56+
57+
// Catalog discovery is process-stable. Same-process registry writes and Gateway
58+
// refreshes clear this hook; external install/uninstall/doctor flows are restart-backed,
59+
// so request-time ledger freshness polling is intentionally absent.
60+
registerPluginMetadataProcessMemoLifecycleClear(clearChannelCatalogDiscoveryMemo);
61+
1962
export function listChannelCatalogEntries(
20-
params: {
21-
origin?: PluginOrigin;
22-
workspaceDir?: string;
23-
env?: NodeJS.ProcessEnv;
24-
extraPaths?: string[];
25-
/**
26-
* Optional override. When omitted and `origin !== "bundled"`, the persisted
27-
* plugin install ledger is loaded synchronously so that npm-installed
28-
* channels stored outside the discovery roots are visible to the catalog.
29-
* Bundled-only callers skip the load to avoid the disk read.
30-
*/
31-
installRecords?: Record<string, PluginInstallRecord>;
32-
discovery?: PluginDiscoveryResult;
33-
} = {},
63+
params: ChannelCatalogParams = {},
3464
): PluginChannelCatalogEntry[] {
35-
const installRecords = resolveInstallRecords(params);
36-
const discovery =
37-
params.discovery ??
38-
discoverOpenClawPlugins({
39-
workspaceDir: params.workspaceDir,
40-
env: params.env,
41-
extraPaths: params.extraPaths,
42-
...(installRecords && Object.keys(installRecords).length > 0 ? { installRecords } : {}),
43-
});
65+
// Preserve the ledger-read behavior for callers supplying an exact discovery.
66+
if (params.discovery) {
67+
resolveInstallRecords(params);
68+
}
69+
const discovery = params.discovery ?? resolveMemoizedChannelCatalogDiscovery(params);
4470
return discovery.candidates.flatMap((candidate) => {
4571
if (params.origin && candidate.origin !== params.origin) {
4672
return [];
@@ -69,6 +95,78 @@ export function listChannelCatalogEntries(
6995
});
7096
}
7197

98+
function resolveMemoizedChannelCatalogDiscovery(params: ChannelCatalogParams) {
99+
const installRecordsKey = resolveInstallRecordsKey(params);
100+
const scopeKey = resolveChannelCatalogDiscoveryScopeKey(params);
101+
if (
102+
installRecordsKey.cacheable &&
103+
channelCatalogDiscoveryMemo?.scopeKey === scopeKey &&
104+
channelCatalogDiscoveryMemo.installRecordsIdentity === installRecordsKey.identity &&
105+
channelCatalogDiscoveryMemo.installRecordsFingerprint === installRecordsKey.fingerprint
106+
) {
107+
return channelCatalogDiscoveryMemo.discovery;
108+
}
109+
110+
const resolvedInstallRecords = resolveInstallRecords(params);
111+
const discovery = discoverOpenClawPlugins({
112+
workspaceDir: params.workspaceDir,
113+
env: params.env,
114+
extraPaths: params.extraPaths,
115+
...(resolvedInstallRecords.installRecords &&
116+
Object.keys(resolvedInstallRecords.installRecords).length > 0
117+
? { installRecords: resolvedInstallRecords.installRecords }
118+
: {}),
119+
});
120+
if (resolvedInstallRecords.cacheable && installRecordsKey.cacheable) {
121+
channelCatalogDiscoveryMemo = {
122+
scopeKey,
123+
installRecordsIdentity: installRecordsKey.identity,
124+
...(installRecordsKey.fingerprint !== undefined
125+
? { installRecordsFingerprint: installRecordsKey.fingerprint }
126+
: {}),
127+
discovery,
128+
};
129+
}
130+
return discovery;
131+
}
132+
133+
function resolveChannelCatalogDiscoveryScopeKey(params: ChannelCatalogParams): string {
134+
const env = params.env ?? process.env;
135+
return JSON.stringify({
136+
workspaceDir: resolveOptionalString(params.workspaceDir) ?? null,
137+
discovery: resolvePluginDiscoveryContext({
138+
workspaceDir: params.workspaceDir,
139+
env,
140+
loadPaths: params.extraPaths,
141+
}),
142+
compatibilityHostVersion: resolveCompatibilityHostVersion(env),
143+
bundledSourceOverlaysDisabled: env.OPENCLAW_DISABLE_BUNDLED_SOURCE_OVERLAYS ?? "",
144+
nixMode: resolveIsNixMode(env),
145+
});
146+
}
147+
148+
function resolveInstallRecordsKey(params: ChannelCatalogParams): {
149+
identity: ChannelCatalogDiscoveryMemo["installRecordsIdentity"];
150+
fingerprint?: string;
151+
cacheable: boolean;
152+
} {
153+
if (params.installRecords) {
154+
try {
155+
const fingerprint = JSON.stringify(params.installRecords);
156+
return fingerprint === undefined
157+
? { identity: params.installRecords, cacheable: false }
158+
: { identity: params.installRecords, fingerprint, cacheable: true };
159+
} catch {
160+
return { identity: params.installRecords, cacheable: false };
161+
}
162+
}
163+
return {
164+
identity:
165+
params.origin === "bundled" ? noInstallRecordsIdentity : defaultInstallRecordsIdentity,
166+
cacheable: true,
167+
};
168+
}
169+
72170
function resolveChannelCatalogPluginId(
73171
candidate: PluginDiscoveryResult["candidates"][number],
74172
): string | undefined {
@@ -80,20 +178,25 @@ function resolveChannelCatalogPluginId(
80178
);
81179
}
82180

83-
function resolveInstallRecords(params: {
84-
origin?: PluginOrigin;
85-
env?: NodeJS.ProcessEnv;
181+
function resolveInstallRecords(params: ChannelCatalogParams): {
86182
installRecords?: Record<string, PluginInstallRecord>;
87-
}): Record<string, PluginInstallRecord> | undefined {
183+
cacheable: boolean;
184+
} {
88185
if (params.installRecords) {
89-
return params.installRecords;
186+
return { installRecords: params.installRecords, cacheable: true };
90187
}
91188
if (params.origin === "bundled") {
92-
return undefined;
189+
return { cacheable: true };
93190
}
94191
try {
95-
return loadInstalledPluginIndexInstallRecordsSync(params.env ? { env: params.env } : {});
192+
return {
193+
installRecords: loadInstalledPluginIndexInstallRecordsSync(
194+
params.env ? { env: params.env } : {},
195+
),
196+
cacheable: true,
197+
};
96198
} catch {
97-
return undefined;
199+
// Retry transient ledger failures instead of memoizing an incomplete catalog.
200+
return { cacheable: false };
98201
}
99202
}

0 commit comments

Comments
 (0)