Skip to content

Commit f1d2c5b

Browse files
authored
improve(cli): cut ordinary gateway status startup memory (#133114)
* perf(cli): checkpoint lazy gateway status config * perf(cli): keep gateway status off full config IO
1 parent be5e79c commit f1d2c5b

10 files changed

Lines changed: 333 additions & 115 deletions
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { readBestEffortConfig, resolveGatewayPort } from "../../config/config.js";
2+
import { createConfigIO } from "../../config/io.js";
3+
import { mergeGatewayServiceEnv } from "../../daemon/service-env-merge.js";
4+
import { resolveGatewayService } from "../../daemon/service.js";
5+
import { parseTcpPortFromArgs } from "../../infra/tcp-port.js";
6+
7+
export async function resolveGatewayLifecycleContext(
8+
service = resolveGatewayService(),
9+
requireEffective = false,
10+
) {
11+
const command = requireEffective
12+
? await service.readCommand(process.env, { requireEffective: true })
13+
: await service.readCommand(process.env).catch(() => null);
14+
if (requireEffective && !command) {
15+
throw new Error(
16+
"Updated gateway service could not be inspected; run `openclaw gateway status --deep`.",
17+
);
18+
}
19+
const env = mergeGatewayServiceEnv(process.env, command);
20+
const config = await createConfigIO({
21+
env,
22+
observe: false,
23+
pluginValidation: "skip",
24+
suppressFutureVersionWarning: true,
25+
})
26+
.readBestEffortConfig()
27+
.catch(() => undefined);
28+
const port = parseTcpPortFromArgs(command?.programArguments) ?? resolveGatewayPort(config, env);
29+
return { port, env, command };
30+
}
31+
32+
export async function resolveGatewayConfigPorts() {
33+
const config = await readBestEffortConfig({ observe: false }).catch(() => undefined);
34+
return { explicit: config?.gateway?.port, fallback: resolveGatewayPort(config, process.env) };
35+
}

‎src/cli/daemon-cli/lifecycle.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import {
4848
appendGatewayLifecycleAudit,
4949
createGatewayLifecycleMutationAudit,
5050
} from "./lifecycle-audit.js";
51+
import { resolveGatewayConfigPorts, resolveGatewayLifecycleContext } from "./lifecycle-context.js";
5152
import {
5253
runServiceRestart,
5354
runServiceStart,
@@ -69,11 +70,7 @@ import {
6970
waitForGatewayHealthyListener,
7071
waitForGatewayHealthyRestart,
7172
} from "./restart-health.js";
72-
import {
73-
resolveGatewayLifecycleContext,
74-
resolveGatewayConfigPorts,
75-
renderGatewayServiceStartHints,
76-
} from "./shared.js";
73+
import { renderGatewayServiceStartHints } from "./shared.js";
7774
import { repairLoadedGatewayServiceForStart } from "./start-repair.js";
7875
import type { DaemonLifecycleOptions } from "./types.js";
7976

‎src/cli/daemon-cli/shared.ts‎

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
// Shared Gateway service CLI helpers: status styles, env filtering, port parsing, and hints.
22
import { colorize, isRich, theme } from "../../../packages/terminal-core/src/theme.js";
3-
import { readBestEffortConfig, resolveGatewayPort } from "../../config/config.js";
4-
import { createConfigIO } from "../../config/io.js";
53
import { resolveIsNixMode } from "../../config/paths.js";
64
import {
75
resolveGatewayLaunchAgentLabel,
@@ -14,9 +12,6 @@ import {
1412
buildPlatformRuntimeLogHints,
1513
buildPlatformServiceStartHints,
1614
} from "../../daemon/runtime-hints.js";
17-
import { mergeGatewayServiceEnv } from "../../daemon/service-env-merge.js";
18-
import { resolveGatewayService } from "../../daemon/service.js";
19-
import { parseTcpPortFromArgs } from "../../infra/tcp-port.js";
2015
import { formatCliCommand } from "../command-format.js";
2116
import { parsePort } from "../shared/parse-port.js";
2217
import { createDaemonActionContext } from "./response.js";
@@ -225,33 +220,3 @@ export function filterContainerGenericHints(
225220
!hint.includes("systemd user services are unavailable; install/enable systemd"),
226221
);
227222
}
228-
229-
export async function resolveGatewayLifecycleContext(
230-
service = resolveGatewayService(),
231-
requireEffective = false,
232-
) {
233-
const command = requireEffective
234-
? await service.readCommand(process.env, { requireEffective: true })
235-
: await service.readCommand(process.env).catch(() => null);
236-
if (requireEffective && !command) {
237-
throw new Error(
238-
"Updated gateway service could not be inspected; run `openclaw gateway status --deep`.",
239-
);
240-
}
241-
const env = mergeGatewayServiceEnv(process.env, command);
242-
const config = await createConfigIO({
243-
env,
244-
observe: false,
245-
pluginValidation: "skip",
246-
suppressFutureVersionWarning: true,
247-
})
248-
.readBestEffortConfig()
249-
.catch(() => undefined);
250-
const port = parseTcpPortFromArgs(command?.programArguments) ?? resolveGatewayPort(config, env);
251-
return { port, env, command };
252-
}
253-
254-
export async function resolveGatewayConfigPorts() {
255-
const config = await readBestEffortConfig({ observe: false }).catch(() => undefined);
256-
return { explicit: config?.gateway?.port, fallback: resolveGatewayPort(config, process.env) };
257-
}

‎src/cli/daemon-cli/status.gather.test.ts‎

Lines changed: 157 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ type PortConnections = Awaited<
2121
ReturnType<typeof import("../../infra/ports-inspect.js").inspectPortConnections>
2222
>;
2323

24+
const readFile = fs.readFile.bind(fs);
25+
let readFileSpy: ReturnType<typeof vi.spyOn>;
26+
2427
const callGatewayStatusProbe = vi.fn<
2528
(opts?: unknown) => Promise<{
2629
ok: boolean;
@@ -180,6 +183,19 @@ let cliLoadedConfig: Record<string, unknown> = {
180183
};
181184

182185
vi.mock("../../config/config.js", () => ({
186+
getRuntimeConfig: () => cliLoadedConfig,
187+
loadConfig: () => cliLoadedConfig,
188+
}));
189+
190+
vi.mock("../../config/paths.js", async (importOriginal) => ({
191+
...(await importOriginal<typeof import("../../config/paths.js")>()),
192+
isDefaultInstallIdentity: (env?: NodeJS.ProcessEnv) => isDefaultInstallIdentity(env),
193+
resolveConfigPath: (env: NodeJS.ProcessEnv, stateDir: string) => resolveConfigPath(env, stateDir),
194+
resolveGatewayPort: (cfg?: unknown, env?: unknown) => resolveGatewayPort(cfg, env),
195+
resolveStateDir: (env: NodeJS.ProcessEnv) => resolveStateDir(env),
196+
}));
197+
198+
vi.mock("../../config/io.runtime.js", () => ({
183199
createConfigIO: ({
184200
configPath,
185201
observe,
@@ -212,16 +228,6 @@ vi.mock("../../config/config.js", () => ({
212228
},
213229
};
214230
},
215-
getRuntimeConfig: () => cliLoadedConfig,
216-
loadConfig: () => cliLoadedConfig,
217-
resolveConfigPath: (env: NodeJS.ProcessEnv, stateDir: string) => resolveConfigPath(env, stateDir),
218-
resolveGatewayPort: (cfg?: unknown, env?: unknown) => resolveGatewayPort(cfg, env),
219-
resolveStateDir: (env: NodeJS.ProcessEnv) => resolveStateDir(env),
220-
}));
221-
222-
vi.mock("../../config/paths.js", async (importOriginal) => ({
223-
...(await importOriginal<typeof import("../../config/paths.js")>()),
224-
isDefaultInstallIdentity: (env?: NodeJS.ProcessEnv) => isDefaultInstallIdentity(env),
225231
}));
226232

227233
vi.mock("../../daemon/diagnostics.js", () => ({
@@ -342,10 +348,49 @@ function gatherStatus(overrides: Partial<Parameters<typeof gatherDaemonStatus>[0
342348
return gatherDaemonStatus({ rpc: {}, probe: true, deep: false, ...overrides });
343349
}
344350

351+
async function withStatusConfig<T>(
352+
rawConfig: string | undefined,
353+
run: (configPath: string) => Promise<T>,
354+
includeServiceEnv = false,
355+
): Promise<T> {
356+
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-status-config-"));
357+
const configPath = path.join(tmp, "openclaw.json");
358+
if (rawConfig !== undefined) {
359+
await fs.writeFile(configPath, rawConfig);
360+
}
361+
setTestEnvValue("OPENCLAW_STATE_DIR", tmp);
362+
setTestEnvValue("OPENCLAW_CONFIG_PATH", configPath);
363+
serviceReadCommand.mockResolvedValueOnce({
364+
programArguments: ["/bin/node", "cli", "gateway", "--port", "19001"],
365+
...(includeServiceEnv
366+
? {
367+
environment: {
368+
OPENCLAW_STATE_DIR: tmp,
369+
OPENCLAW_CONFIG_PATH: configPath,
370+
},
371+
}
372+
: {}),
373+
});
374+
try {
375+
return await run(configPath);
376+
} finally {
377+
await fs.rm(tmp, { recursive: true, force: true });
378+
}
379+
}
380+
345381
describe("gatherDaemonStatus", () => {
346382
let envSnapshot: ReturnType<typeof captureEnv>;
347383

348384
beforeEach(() => {
385+
readFileSpy = vi.spyOn(fs, "readFile").mockImplementation(async (filePath, options) => {
386+
if (
387+
filePath === "/tmp/openclaw-cli/openclaw.json" ||
388+
filePath === "/tmp/openclaw-daemon/openclaw.json"
389+
) {
390+
throw Object.assign(new Error("test config requires full IO"), { code: "EACCES" });
391+
}
392+
return await readFile(filePath, options);
393+
});
349394
envSnapshot = captureEnv([
350395
"OPENCLAW_STATE_DIR",
351396
"OPENCLAW_CONFIG_PATH",
@@ -438,6 +483,7 @@ describe("gatherDaemonStatus", () => {
438483
});
439484

440485
afterEach(() => {
486+
readFileSpy.mockRestore();
441487
envSnapshot.restore();
442488
});
443489

@@ -1076,84 +1122,128 @@ describe("gatherDaemonStatus", () => {
10761122
});
10771123

10781124
it("uses the fast config path for plain same-file status reads", async () => {
1079-
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-status-config-"));
1080-
const configPath = path.join(tmp, "openclaw.json");
1081-
await fs.writeFile(
1082-
configPath,
1125+
await withStatusConfig(
10831126
JSON.stringify({
10841127
gateway: {
10851128
bind: "custom",
10861129
customBindHost: "10.0.0.5",
10871130
controlUi: { enabled: true },
10881131
},
10891132
}),
1133+
async (configPath) => {
1134+
const status = await gatherStatus({ probe: false });
1135+
1136+
expect(createConfigIOCalls).not.toHaveBeenCalled();
1137+
expect(readConfigFileSnapshotCalls).not.toHaveBeenCalled();
1138+
expect(loadConfigCalls).not.toHaveBeenCalled();
1139+
expect(status.config?.cli.path).toBe(configPath);
1140+
expect(status.config?.cli.exists).toBe(true);
1141+
expect(status.config?.cli.valid).toBe(true);
1142+
expect(status.config?.cli.controlUi).toEqual({ enabled: true });
1143+
expect(status.config?.daemon).toBe(status.config?.cli);
1144+
expect(status.gateway?.bindMode).toBe("custom");
1145+
expect(status.gateway?.customBindHost).toBe("10.0.0.5");
1146+
},
1147+
true,
10901148
);
1091-
setTestEnvValue("OPENCLAW_STATE_DIR", tmp);
1092-
setTestEnvValue("OPENCLAW_CONFIG_PATH", configPath);
1093-
serviceReadCommand.mockResolvedValueOnce({
1094-
programArguments: ["/bin/node", "cli", "gateway", "--port", "19001"],
1095-
environment: {
1096-
OPENCLAW_STATE_DIR: tmp,
1097-
OPENCLAW_CONFIG_PATH: configPath,
1149+
});
1150+
1151+
it("uses the fast config path when the config file is missing", async () => {
1152+
await withStatusConfig(
1153+
undefined,
1154+
async (configPath) => {
1155+
const status = await gatherStatus({ probe: false });
1156+
1157+
expect(createConfigIOCalls).not.toHaveBeenCalled();
1158+
expect(status.config?.cli).toEqual({
1159+
path: configPath,
1160+
exists: false,
1161+
valid: true,
1162+
});
1163+
expect(status.config?.daemon).toBe(status.config?.cli);
1164+
expect(status.gateway).toMatchObject({
1165+
bindMode: "loopback",
1166+
port: 19001,
1167+
});
10981168
},
1169+
true,
1170+
);
1171+
});
1172+
1173+
it("keeps malformed JSON5 on the fast invalid-summary path", async () => {
1174+
await withStatusConfig(
1175+
"{ gateway:",
1176+
async (configPath) => {
1177+
const status = await gatherStatus({ probe: false });
1178+
1179+
expect(createConfigIOCalls).not.toHaveBeenCalled();
1180+
expect(status.config?.cli).toMatchObject({
1181+
path: configPath,
1182+
exists: true,
1183+
valid: false,
1184+
});
1185+
expect(status.config?.cli.issues?.[0]?.message).toContain("JSON5 parse failed");
1186+
expect(status.config?.daemon).toBe(status.config?.cli);
1187+
},
1188+
true,
1189+
);
1190+
});
1191+
1192+
it.each([
1193+
["include", JSON.stringify({ $include: "./base.json" })],
1194+
["substitution", JSON.stringify({ gateway: { auth: { token: "${STATUS_TOKEN}" } } })],
1195+
["root env", JSON.stringify({ env: { STATUS_TOKEN: "value" } })],
1196+
])("uses full config IO for %s config", async (_name, rawConfig) => {
1197+
await withStatusConfig(rawConfig, async (configPath) => {
1198+
await gatherStatus({ probe: false });
1199+
1200+
expect(createConfigIOCalls).toHaveBeenCalledOnce();
1201+
expect(createConfigIOCalls).toHaveBeenCalledWith(configPath, "skip", false);
1202+
expect(readConfigFileSnapshotCalls).toHaveBeenCalledWith(configPath);
10991203
});
1204+
});
11001205

1101-
try {
1102-
const status = await gatherStatus({ probe: false });
1103-
1104-
expect(readConfigFileSnapshotCalls).not.toHaveBeenCalled();
1105-
expect(loadConfigCalls).not.toHaveBeenCalled();
1106-
expect(status.config?.cli.path).toBe(configPath);
1107-
expect(status.config?.cli.exists).toBe(true);
1108-
expect(status.config?.cli.valid).toBe(true);
1109-
expect(status.config?.cli.controlUi).toEqual({ enabled: true });
1110-
expect(status.config?.daemon).toBe(status.config?.cli);
1111-
expect(status.gateway?.bindMode).toBe("custom");
1112-
expect(status.gateway?.customBindHost).toBe("10.0.0.5");
1113-
} finally {
1114-
await fs.rm(tmp, { recursive: true, force: true });
1115-
}
1206+
it("uses full config IO after a non-missing read failure", async () => {
1207+
await withStatusConfig("{}", async (configPath) => {
1208+
readFileSpy.mockRejectedValueOnce(
1209+
Object.assign(new Error("permission denied"), { code: "EACCES" }),
1210+
);
1211+
await gatherStatus({ probe: false });
1212+
1213+
expect(createConfigIOCalls).toHaveBeenCalledOnce();
1214+
expect(createConfigIOCalls).toHaveBeenCalledWith(configPath, "skip", false);
1215+
});
11161216
});
11171217

11181218
it("uses full plugin-aware config validation for deep status", async () => {
1119-
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-status-config-"));
1120-
const configPath = path.join(tmp, "openclaw.json");
1121-
await fs.writeFile(
1122-
configPath,
1219+
await withStatusConfig(
11231220
JSON.stringify({
11241221
gateway: {
11251222
bind: "loopback",
11261223
},
11271224
}),
1128-
);
1129-
setTestEnvValue("OPENCLAW_STATE_DIR", tmp);
1130-
setTestEnvValue("OPENCLAW_CONFIG_PATH", configPath);
1131-
cliLoadedConfig = {
1132-
gateway: {
1133-
bind: "loopback",
1134-
},
1135-
};
1136-
cliConfigWarnings = [
1137-
{
1138-
path: "plugins.entries.test-bad-plugin",
1139-
message:
1140-
"plugin test-bad-plugin: channel plugin manifest declares test-bad-plugin without channelConfigs metadata",
1141-
},
1142-
];
1143-
serviceReadCommand.mockResolvedValueOnce({
1144-
programArguments: ["/bin/node", "cli", "gateway", "--port", "19001"],
1145-
});
1225+
async (configPath) => {
1226+
cliLoadedConfig = {
1227+
gateway: {
1228+
bind: "loopback",
1229+
},
1230+
};
1231+
cliConfigWarnings = [
1232+
{
1233+
path: "plugins.entries.test-bad-plugin",
1234+
message:
1235+
"plugin test-bad-plugin: channel plugin manifest declares test-bad-plugin without channelConfigs metadata",
1236+
},
1237+
];
11461238

1147-
try {
1148-
const status = await gatherStatus({ probe: false, deep: true });
1239+
const status = await gatherStatus({ probe: false, deep: true });
11491240

1150-
expect(createConfigIOCalls).toHaveBeenCalledWith(configPath, "full", false);
1151-
expect(readConfigFileSnapshotCalls).toHaveBeenCalledWith(configPath);
1152-
expect(status.config?.cli.warnings).toEqual(cliConfigWarnings);
1153-
expect(status.config?.daemon).toBe(status.config?.cli);
1154-
} finally {
1155-
await fs.rm(tmp, { recursive: true, force: true });
1156-
}
1241+
expect(createConfigIOCalls).toHaveBeenCalledWith(configPath, "full", false);
1242+
expect(readConfigFileSnapshotCalls).toHaveBeenCalledWith(configPath);
1243+
expect(status.config?.cli.warnings).toEqual(cliConfigWarnings);
1244+
expect(status.config?.daemon).toBe(status.config?.cli);
1245+
},
1246+
);
11571247
});
11581248

11591249
it("resolves daemon gateway auth password SecretRef values before probing", async () => {

0 commit comments

Comments
 (0)