Skip to content

Commit ad0d87d

Browse files
committed
perf: cache startup package metadata
1 parent 5b063c2 commit ad0d87d

15 files changed

Lines changed: 439 additions & 23 deletions

‎src/channels/bundled-channel-catalog-read.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ type BundledChannelCatalogEntry = {
1919
};
2020

2121
const OFFICIAL_CHANNEL_CATALOG_RELATIVE_PATH = path.join("dist", "channel-catalog.json");
22+
const officialCatalogFileCache = new Map<string, ChannelCatalogEntryLike[] | null>();
2223

2324
function listPackageRoots(): string[] {
2425
return [
@@ -38,15 +39,28 @@ function readBundledExtensionCatalogEntriesSync(): PluginPackageChannel[] {
3839
function readOfficialCatalogFileSync(): ChannelCatalogEntryLike[] {
3940
for (const packageRoot of listPackageRoots()) {
4041
const candidate = path.join(packageRoot, OFFICIAL_CHANNEL_CATALOG_RELATIVE_PATH);
42+
const cached = officialCatalogFileCache.get(candidate);
43+
if (cached !== undefined) {
44+
if (cached) {
45+
return cached;
46+
}
47+
continue;
48+
}
4149
if (!fs.existsSync(candidate)) {
50+
officialCatalogFileCache.set(candidate, null);
4251
continue;
4352
}
4453
try {
4554
const payload = JSON.parse(fs.readFileSync(candidate, "utf8")) as {
4655
entries?: unknown;
4756
};
48-
return Array.isArray(payload.entries) ? (payload.entries as ChannelCatalogEntryLike[]) : [];
57+
const entries = Array.isArray(payload.entries)
58+
? (payload.entries as ChannelCatalogEntryLike[])
59+
: [];
60+
officialCatalogFileCache.set(candidate, entries);
61+
return entries;
4962
} catch {
63+
officialCatalogFileCache.set(candidate, null);
5064
continue;
5165
}
5266
}

‎src/channels/plugins/catalog.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ type ExternalCatalogEntry = {
7070

7171
const ENV_CATALOG_PATHS = ["OPENCLAW_PLUGIN_CATALOG_PATHS", "OPENCLAW_MPM_CATALOG_PATHS"];
7272
const OFFICIAL_CHANNEL_CATALOG_RELATIVE_PATH = path.join("dist", "channel-catalog.json");
73+
const officialCatalogEntriesByPath = new Map<string, ExternalCatalogEntry[] | null>();
7374

7475
type ManifestKey = typeof MANIFEST_KEY;
7576

@@ -145,6 +146,32 @@ function loadCatalogEntriesFromPaths(paths: Iterable<string>): ExternalCatalogEn
145146
return entries;
146147
}
147148

149+
function loadOfficialCatalogEntriesFromPaths(paths: Iterable<string>): ExternalCatalogEntry[] {
150+
const entries: ExternalCatalogEntry[] = [];
151+
for (const resolvedPath of paths) {
152+
const cached = officialCatalogEntriesByPath.get(resolvedPath);
153+
if (cached !== undefined) {
154+
if (cached) {
155+
entries.push(...cached);
156+
}
157+
continue;
158+
}
159+
if (!fs.existsSync(resolvedPath)) {
160+
officialCatalogEntriesByPath.set(resolvedPath, null);
161+
continue;
162+
}
163+
try {
164+
const payload = JSON.parse(fs.readFileSync(resolvedPath, "utf-8")) as unknown;
165+
const parsed = parseCatalogEntries(payload);
166+
officialCatalogEntriesByPath.set(resolvedPath, parsed);
167+
entries.push(...parsed);
168+
} catch {
169+
officialCatalogEntriesByPath.set(resolvedPath, null);
170+
}
171+
}
172+
return entries;
173+
}
174+
148175
function resolveOfficialCatalogPaths(options: CatalogOptions): string[] {
149176
if (options.officialCatalogPaths && options.officialCatalogPaths.length > 0) {
150177
return options.officialCatalogPaths.map((entry) => entry.trim()).filter(Boolean);
@@ -170,7 +197,11 @@ function resolveOfficialCatalogPaths(options: CatalogOptions): string[] {
170197

171198
function loadOfficialCatalogEntries(options: CatalogOptions): ChannelPluginCatalogEntry[] {
172199
const builtInEntries = parseCatalogEntries(officialExternalChannelCatalog);
173-
const fileEntries = loadCatalogEntriesFromPaths(resolveOfficialCatalogPaths(options));
200+
const officialPaths = resolveOfficialCatalogPaths(options);
201+
const fileEntries =
202+
options.officialCatalogPaths && options.officialCatalogPaths.length > 0
203+
? loadCatalogEntriesFromPaths(officialPaths)
204+
: loadOfficialCatalogEntriesFromPaths(officialPaths);
174205
return [...builtInEntries, ...fileEntries]
175206
.map((entry) => buildExternalCatalogEntry(entry))
176207
.filter((entry): entry is ChannelPluginCatalogEntry => Boolean(entry));

‎src/cli/startup-metadata.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import path from "node:path";
33
import { fileURLToPath } from "node:url";
44

55
const STARTUP_METADATA_FILE = "cli-startup-metadata.json";
6+
const startupMetadataByPath = new Map<string, Record<string, unknown> | null>();
67

78
function resolveStartupMetadataPathCandidates(moduleUrl: string): string[] {
89
const moduleDir = path.dirname(fileURLToPath(moduleUrl));
@@ -14,15 +15,28 @@ function resolveStartupMetadataPathCandidates(moduleUrl: string): string[] {
1415

1516
export function readCliStartupMetadata(moduleUrl: string): Record<string, unknown> | null {
1617
for (const metadataPath of resolveStartupMetadataPathCandidates(moduleUrl)) {
18+
const cached = startupMetadataByPath.get(metadataPath);
19+
if (cached !== undefined) {
20+
if (cached) {
21+
return cached;
22+
}
23+
continue;
24+
}
1725
try {
18-
return JSON.parse(fs.readFileSync(metadataPath, "utf8")) as Record<string, unknown>;
26+
const parsed = JSON.parse(fs.readFileSync(metadataPath, "utf8")) as Record<string, unknown>;
27+
startupMetadataByPath.set(metadataPath, parsed);
28+
return parsed;
1929
} catch {
2030
// Try the next bundled/source layout before falling back to dynamic startup work.
31+
startupMetadataByPath.set(metadataPath, null);
2132
}
2233
}
2334
return null;
2435
}
2536

2637
export const __testing = {
2738
resolveStartupMetadataPathCandidates,
39+
clearStartupMetadataCache(): void {
40+
startupMetadataByPath.clear();
41+
},
2842
};

‎src/infra/openclaw-root.test.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,13 +108,18 @@ vi.mock("./openclaw-root.fs.runtime.js", () => ({
108108
describe("resolveOpenClawPackageRoot", () => {
109109
let resolveOpenClawPackageRoot: typeof import("./openclaw-root.js").resolveOpenClawPackageRoot;
110110
let resolveOpenClawPackageRootSync: typeof import("./openclaw-root.js").resolveOpenClawPackageRootSync;
111+
let clearOpenClawPackageRootCaches: typeof import("./openclaw-root.js").__testing.clearOpenClawPackageRootCaches;
111112

112113
beforeAll(async () => {
113-
({ resolveOpenClawPackageRoot, resolveOpenClawPackageRootSync } =
114-
await import("./openclaw-root.js"));
114+
({
115+
resolveOpenClawPackageRoot,
116+
resolveOpenClawPackageRootSync,
117+
__testing: { clearOpenClawPackageRootCaches },
118+
} = await import("./openclaw-root.js"));
115119
});
116120

117121
beforeEach(() => {
122+
clearOpenClawPackageRootCaches();
118123
state.entries.clear();
119124
state.realpaths.clear();
120125
state.realpathErrors.clear();

‎src/infra/openclaw-root.ts‎

Lines changed: 70 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,41 @@ import { fileURLToPath } from "node:url";
33
import { openClawRootFs, openClawRootFsSync } from "./openclaw-root.fs.runtime.js";
44

55
const CORE_PACKAGE_NAMES = new Set(["openclaw"]);
6+
const packageNameCache = new Map<string, string | null>();
7+
const packageRootCache = new Map<string, string | null>();
8+
const argv1CandidateCache = new Map<string, string[]>();
69

710
function parsePackageName(raw: string): string | null {
811
const parsed = JSON.parse(raw) as { name?: unknown };
912
return typeof parsed.name === "string" ? parsed.name : null;
1013
}
1114

1215
async function readPackageName(dir: string): Promise<string | null> {
16+
const packageJsonPath = path.join(path.resolve(dir), "package.json");
17+
if (packageNameCache.has(packageJsonPath)) {
18+
return packageNameCache.get(packageJsonPath) ?? null;
19+
}
1320
try {
14-
return parsePackageName(await openClawRootFs.readFile(path.join(dir, "package.json"), "utf-8"));
21+
const name = parsePackageName(await openClawRootFs.readFile(packageJsonPath, "utf-8"));
22+
packageNameCache.set(packageJsonPath, name);
23+
return name;
1524
} catch {
25+
packageNameCache.set(packageJsonPath, null);
1626
return null;
1727
}
1828
}
1929

2030
function readPackageNameSync(dir: string): string | null {
31+
const packageJsonPath = path.join(path.resolve(dir), "package.json");
32+
if (packageNameCache.has(packageJsonPath)) {
33+
return packageNameCache.get(packageJsonPath) ?? null;
34+
}
2135
try {
22-
return parsePackageName(
23-
openClawRootFsSync.readFileSync(path.join(dir, "package.json"), "utf-8"),
24-
);
36+
const name = parsePackageName(openClawRootFsSync.readFileSync(packageJsonPath, "utf-8"));
37+
packageNameCache.set(packageJsonPath, name);
38+
return name;
2539
} catch {
40+
packageNameCache.set(packageJsonPath, null);
2641
return null;
2742
}
2843
}
@@ -60,6 +75,11 @@ function* iterAncestorDirs(startDir: string, maxDepth: number): Generator<string
6075
}
6176

6277
function candidateDirsFromArgv1(argv1: string): string[] {
78+
const cacheKey = path.resolve(argv1);
79+
const cached = argv1CandidateCache.get(cacheKey);
80+
if (cached) {
81+
return [...cached];
82+
}
6383
const normalized = path.resolve(argv1);
6484
const candidates = [path.dirname(normalized)];
6585

@@ -81,21 +101,30 @@ function candidateDirsFromArgv1(argv1: string): string[] {
81101
const nodeModulesDir = parts.slice(0, binIndex).join(path.sep);
82102
candidates.push(path.join(nodeModulesDir, binName));
83103
}
84-
return candidates;
104+
const deduped = dedupeCandidates(candidates);
105+
argv1CandidateCache.set(cacheKey, deduped);
106+
return [...deduped];
85107
}
86108

87109
export async function resolveOpenClawPackageRoot(opts: {
88110
cwd?: string;
89111
argv1?: string;
90112
moduleUrl?: string;
91113
}): Promise<string | null> {
92-
for (const candidate of buildCandidates(opts)) {
114+
const candidates = buildCandidates(opts);
115+
const cacheKey = createPackageRootCacheKey(candidates);
116+
if (packageRootCache.has(cacheKey)) {
117+
return packageRootCache.get(cacheKey) ?? null;
118+
}
119+
for (const candidate of candidates) {
93120
const found = await findPackageRoot(candidate);
94121
if (found) {
122+
packageRootCache.set(cacheKey, found);
95123
return found;
96124
}
97125
}
98126

127+
packageRootCache.set(cacheKey, null);
99128
return null;
100129
}
101130

@@ -104,13 +133,20 @@ export function resolveOpenClawPackageRootSync(opts: {
104133
argv1?: string;
105134
moduleUrl?: string;
106135
}): string | null {
107-
for (const candidate of buildCandidates(opts)) {
136+
const candidates = buildCandidates(opts);
137+
const cacheKey = createPackageRootCacheKey(candidates);
138+
if (packageRootCache.has(cacheKey)) {
139+
return packageRootCache.get(cacheKey) ?? null;
140+
}
141+
for (const candidate of candidates) {
108142
const found = findPackageRootSync(candidate);
109143
if (found) {
144+
packageRootCache.set(cacheKey, found);
110145
return found;
111146
}
112147
}
113148

149+
packageRootCache.set(cacheKey, null);
114150
return null;
115151
}
116152

@@ -131,5 +167,31 @@ function buildCandidates(opts: { cwd?: string; argv1?: string; moduleUrl?: strin
131167
candidates.push(opts.cwd);
132168
}
133169

134-
return candidates;
170+
return dedupeCandidates(candidates);
171+
}
172+
173+
function dedupeCandidates(candidates: readonly string[]): string[] {
174+
const seen = new Set<string>();
175+
const deduped: string[] = [];
176+
for (const candidate of candidates) {
177+
const resolved = path.resolve(candidate);
178+
if (seen.has(resolved)) {
179+
continue;
180+
}
181+
seen.add(resolved);
182+
deduped.push(resolved);
183+
}
184+
return deduped;
185+
}
186+
187+
function createPackageRootCacheKey(candidates: readonly string[]): string {
188+
return candidates.join("\0");
135189
}
190+
191+
export const __testing = {
192+
clearOpenClawPackageRootCaches(): void {
193+
packageNameCache.clear();
194+
packageRootCache.clear();
195+
argv1CandidateCache.clear();
196+
},
197+
};

‎src/plugins/bundled-dir.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,24 @@ describe("resolveBundledPluginsDir", () => {
358358
expect(fs.readdirSync(bundledDir ?? "")).toEqual([]);
359359
});
360360

361+
it("separates tilde override cache entries by OPENCLAW_HOME", () => {
362+
const homeA = makeRepoRoot("openclaw-bundled-dir-home-a-");
363+
const homeB = makeRepoRoot("openclaw-bundled-dir-home-b-");
364+
seedBundledPluginTree(homeA, "bundled", "memory-core");
365+
seedBundledPluginTree(homeB, "bundled", "discord");
366+
const envBase = {
367+
OPENCLAW_BUNDLED_PLUGINS_DIR: "~/bundled",
368+
OPENCLAW_TEST_TRUST_BUNDLED_PLUGINS_DIR: "1",
369+
VITEST: "true",
370+
} satisfies NodeJS.ProcessEnv;
371+
372+
const bundledA = resolveBundledPluginsDir({ ...envBase, OPENCLAW_HOME: homeA });
373+
const bundledB = resolveBundledPluginsDir({ ...envBase, OPENCLAW_HOME: homeB });
374+
375+
expect(fs.realpathSync(bundledA ?? "")).toBe(fs.realpathSync(path.join(homeA, "bundled")));
376+
expect(fs.realpathSync(bundledB ?? "")).toBe(fs.realpathSync(path.join(homeB, "bundled")));
377+
});
378+
361379
it("ignores an existing override under an argv1-derived fake package root", () => {
362380
const installedRoot = createOpenClawRoot({
363381
prefix: "openclaw-bundled-dir-argv-override-reject-",

‎src/plugins/bundled-dir.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { resolveUserPath } from "../utils.js";
99
const DISABLED_BUNDLED_PLUGINS_DIR = path.join(os.tmpdir(), "openclaw-empty-bundled-plugins");
1010
const TEST_TRUST_BUNDLED_PLUGINS_DIR_ENV = "OPENCLAW_TEST_TRUST_BUNDLED_PLUGINS_DIR";
1111
let bundledPluginsDirOverrideForTest: string | undefined;
12+
const bundledPluginsDirCache = new Map<string, string | undefined>();
1213

1314
export type SourceCheckoutDependencyDiagnostic = {
1415
source: string;
@@ -192,7 +193,25 @@ function resolveBundledDirFromPackageRoot(packageRoot: string): string | undefin
192193
return undefined;
193194
}
194195

195-
export function resolveBundledPluginsDir(env: NodeJS.ProcessEnv = process.env): string | undefined {
196+
function createBundledPluginsDirCacheKey(env: NodeJS.ProcessEnv): string {
197+
return JSON.stringify({
198+
disabled: env.OPENCLAW_DISABLE_BUNDLED_PLUGINS ?? "",
199+
override: env.OPENCLAW_BUNDLED_PLUGINS_DIR ?? "",
200+
trustOverride: env[TEST_TRUST_BUNDLED_PLUGINS_DIR_ENV] ?? "",
201+
processTrustOverride: process.env[TEST_TRUST_BUNDLED_PLUGINS_DIR_ENV] ?? "",
202+
vitest: env.VITEST ?? "",
203+
processVitest: process.env.VITEST ?? "",
204+
nodeEnv: process.env.NODE_ENV ?? "",
205+
argv1: process.argv[1] ?? "",
206+
execPath: process.execPath,
207+
openClawHome: env.OPENCLAW_HOME ?? "",
208+
home: env.HOME ?? "",
209+
userProfile: env.USERPROFILE ?? "",
210+
testOverride: bundledPluginsDirOverrideForTest ?? "",
211+
});
212+
}
213+
214+
function resolveBundledPluginsDirUncached(env: NodeJS.ProcessEnv): string | undefined {
196215
if (areBundledPluginsDisabled(env)) {
197216
return resolveDisabledBundledPluginsDir();
198217
}
@@ -278,9 +297,20 @@ export function resolveBundledPluginsDir(env: NodeJS.ProcessEnv = process.env):
278297
return undefined;
279298
}
280299

300+
export function resolveBundledPluginsDir(env: NodeJS.ProcessEnv = process.env): string | undefined {
301+
const cacheKey = createBundledPluginsDirCacheKey(env);
302+
if (bundledPluginsDirCache.has(cacheKey)) {
303+
return bundledPluginsDirCache.get(cacheKey);
304+
}
305+
const resolved = resolveBundledPluginsDirUncached(env);
306+
bundledPluginsDirCache.set(cacheKey, resolved);
307+
return resolved;
308+
}
309+
281310
export function setBundledPluginsDirOverrideForTest(dir: string | undefined): void {
282311
if (process.env.VITEST !== "true" && process.env.NODE_ENV !== "test") {
283312
throw new Error("setBundledPluginsDirOverrideForTest is only available in tests");
284313
}
285314
bundledPluginsDirOverrideForTest = dir;
315+
bundledPluginsDirCache.clear();
286316
}

0 commit comments

Comments
 (0)