Skip to content

Commit f620c19

Browse files
authored
fix(gateway): bound service reads in status (#117636)
* fix(gateway): bound status service reads * fix(gateway): preserve service probe errors
1 parent 47bb037 commit f620c19

4 files changed

Lines changed: 109 additions & 22 deletions

File tree

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

Lines changed: 78 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,12 @@ import type { StaleOpenClawUpdateLaunchdJob } from "../../daemon/launchd.js";
77
import { createMockGatewayService } from "../../daemon/service.test-helpers.js";
88
import type { PortListener, PortUsageStatus } from "../../infra/ports.js";
99
import type { GatewayRestartHandoff } from "../../infra/restart-handoff.js";
10+
import { defaultRuntime } from "../../runtime.js";
1011
import { captureEnv, deleteTestEnvValue, setTestEnvValue } from "../../test-utils/env.js";
1112
import { VERSION } from "../../version.js";
1213
import type { GatewayRestartSnapshot } from "./restart-health.js";
1314
import { gatherDaemonStatus } from "./status.gather.js";
15+
import { printDaemonStatus } from "./status.print.js";
1416

1517
type PortConnections = Awaited<
1618
ReturnType<typeof import("../../infra/ports.js").inspectPortConnections>
@@ -103,10 +105,15 @@ const inspectWindowsGatewayFirewall = vi.fn<(opts?: unknown) => Promise<unknown>
103105
details: [],
104106
}));
105107
const auditGatewayServiceConfig = vi.fn(async (_opts?: unknown) => undefined);
106-
const serviceIsLoaded = vi.fn(async (_opts?: unknown) => true);
108+
const serviceIsLoaded = vi.fn<
109+
(opts?: { env?: NodeJS.ProcessEnv; timeoutMs?: number }) => Promise<boolean>
110+
>(async (_opts?: { env?: NodeJS.ProcessEnv; timeoutMs?: number }) => true);
107111
const serviceReadRuntime = vi.fn<
108-
(_env?: NodeJS.ProcessEnv) => Promise<{ status: string; detail?: string }>
109-
>(async (_env?: NodeJS.ProcessEnv) => ({ status: "running" }));
112+
(
113+
_env?: NodeJS.ProcessEnv,
114+
_opts?: { timeoutMs?: number },
115+
) => Promise<{ status: string; detail?: string }>
116+
>(async (_env?: NodeJS.ProcessEnv, _opts?: { timeoutMs?: number }) => ({ status: "running" }));
110117
const inspectGatewayRestart = vi.fn<(opts?: unknown) => Promise<GatewayRestartSnapshot>>(
111118
async (_opts?: unknown) => ({
112119
runtime: { status: "running", pid: 1234 },
@@ -210,7 +217,8 @@ vi.mock("../../daemon/inspect.js", () => ({
210217
findExtraGatewayServices: (env: unknown, opts?: unknown) => findExtraGatewayServices(env, opts),
211218
}));
212219

213-
vi.mock("../../daemon/launchd.js", () => ({
220+
vi.mock("../../daemon/launchd.js", async (importOriginal) => ({
221+
...(await importOriginal<typeof import("../../daemon/launchd.js")>()),
214222
findStaleOpenClawUpdateLaunchdJobs: (env?: NodeJS.ProcessEnv) =>
215223
findStaleOpenClawUpdateLaunchdJobs(env),
216224
}));
@@ -219,7 +227,8 @@ vi.mock("../../daemon/service-audit.js", () => ({
219227
auditGatewayServiceConfig: (opts: unknown) => auditGatewayServiceConfig(opts),
220228
}));
221229

222-
vi.mock("../../daemon/service.js", () => ({
230+
vi.mock("../../daemon/service.js", async (importOriginal) => ({
231+
...(await importOriginal<typeof import("../../daemon/service.js")>()),
223232
resolveGatewayService: () =>
224233
createMockGatewayService({
225234
isLoaded: serviceIsLoaded,
@@ -374,6 +383,9 @@ describe("gatherDaemonStatus", () => {
374383
readLastGatewayErrorLine.mockReset();
375384
readLastGatewayErrorLine.mockResolvedValue(null);
376385
readGatewayRestartHandoffSync.mockClear();
386+
serviceIsLoaded.mockClear();
387+
serviceReadCommand.mockClear();
388+
serviceReadRuntime.mockClear();
377389
readConfigFileSnapshotCalls.mockClear();
378390
loadConfigCalls.mockClear();
379391
daemonConfigWarnings = [];
@@ -640,6 +652,67 @@ describe("gatherDaemonStatus", () => {
640652
expect((status.service.runtime as { detail?: string }).detail).toBe("19001");
641653
});
642654

655+
it("bounds both service-manager reads and still emits JSON after they time out", async () => {
656+
serviceIsLoaded.mockImplementationOnce(async (args?: { timeoutMs?: number }) => {
657+
if (args?.timeoutMs === undefined) {
658+
return await new Promise<boolean>(() => {});
659+
}
660+
throw new Error("systemctl is-enabled timed out");
661+
});
662+
serviceReadRuntime.mockImplementationOnce(async (_env, opts) => {
663+
if (opts?.timeoutMs === undefined) {
664+
return await new Promise<{ status: string }>(() => {});
665+
}
666+
throw new Error("systemctl show timed out");
667+
});
668+
669+
const status = await gatherDaemonStatus({
670+
rpc: { timeout: "100", json: true },
671+
probe: false,
672+
deep: true,
673+
});
674+
675+
expect(serviceIsLoaded).toHaveBeenCalledWith(expect.objectContaining({ timeoutMs: 100 }));
676+
expect(serviceReadRuntime).toHaveBeenCalledWith(expect.any(Object), { timeoutMs: 100 });
677+
expect(status.service.loaded).toBe(false);
678+
expect(status.service.runtime).toEqual({
679+
status: "unknown",
680+
detail: "Error: systemctl show timed out",
681+
});
682+
683+
const writeJson = vi.spyOn(defaultRuntime, "writeJson").mockImplementation(() => {});
684+
try {
685+
printDaemonStatus(status, { json: true, deep: true });
686+
expect(writeJson).toHaveBeenCalledOnce();
687+
const serialized = JSON.stringify(writeJson.mock.calls[0]?.[0]);
688+
if (!serialized) {
689+
throw new Error("expected terminal JSON output");
690+
}
691+
expect(JSON.parse(serialized)).toMatchObject({
692+
service: {
693+
loaded: false,
694+
runtime: {
695+
status: "unknown",
696+
detail: "Error: systemctl show timed out",
697+
},
698+
},
699+
});
700+
} finally {
701+
writeJson.mockRestore();
702+
}
703+
704+
const log = vi.spyOn(defaultRuntime, "log").mockImplementation(() => {});
705+
const error = vi.spyOn(defaultRuntime, "error").mockImplementation(() => {});
706+
try {
707+
printDaemonStatus(status, { json: false, deep: true });
708+
const output = log.mock.calls.flat().join("\n");
709+
expect(output).toContain("Runtime: unknown (Error: systemctl show timed out)");
710+
} finally {
711+
log.mockRestore();
712+
error.mockRestore();
713+
}
714+
}, 1_000);
715+
643716
it("keeps gateway status read-only when service management is unsupported", async () => {
644717
serviceReadCommand.mockResolvedValueOnce(null);
645718
serviceIsLoaded.mockResolvedValueOnce(false);

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

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import type { ExtraGatewayService, FindExtraGatewayServicesOptions } from "../..
2121
import type { StaleOpenClawUpdateLaunchdJob } from "../../daemon/launchd.js";
2222
import type { ServiceConfigAudit } from "../../daemon/service-audit.js";
2323
import type { GatewayServiceRuntime } from "../../daemon/service-runtime.js";
24-
import { resolveGatewayService } from "../../daemon/service.js";
24+
import { readGatewayServiceState, resolveGatewayService } from "../../daemon/service.js";
2525
import { resolveAdvertisedControlUiLinks } from "../../gateway/control-ui-links.js";
2626
import { gatewaySecretInputPathCanWin } from "../../gateway/credentials-secret-inputs.js";
2727
import { trimToUndefined } from "../../gateway/credentials.js";
@@ -578,20 +578,13 @@ export async function gatherDaemonStatus(
578578
allowExecSecretRefs?: boolean;
579579
} & FindExtraGatewayServicesOptions,
580580
): Promise<DaemonStatus> {
581+
const timeoutMs = parseStrictPositiveInteger(opts.rpc.timeout ?? undefined) ?? 10_000;
581582
const service = resolveGatewayService();
582-
const command = await service.readCommand(process.env).catch(() => null);
583-
const serviceEnv = command?.environment
584-
? ({
585-
...process.env,
586-
...command.environment,
587-
} satisfies NodeJS.ProcessEnv)
588-
: process.env;
589-
const [loaded, runtime] = await Promise.all([
590-
service.isLoaded({ env: serviceEnv }).catch(() => false),
591-
service
592-
.readRuntime(serviceEnv)
593-
.catch((err: unknown) => ({ status: "unknown", detail: String(err) })),
594-
]);
583+
const serviceState = await readGatewayServiceState(service, {
584+
env: process.env,
585+
timeoutMs,
586+
});
587+
const { command, env: serviceEnv, loaded, runtime } = serviceState;
595588
const restartHandoff = opts.deep ? readGatewayRestartHandoffSync(serviceEnv) : null;
596589
const configAudit: ServiceConfigAudit = command
597590
? await loadServiceAuditModule().then(({ auditGatewayServiceConfig }) =>
@@ -655,8 +648,6 @@ export async function gatherDaemonStatus(
655648
.catch(() => [])
656649
: [];
657650

658-
const timeoutMs = parseStrictPositiveInteger(opts.rpc.timeout ?? undefined) ?? 10_000;
659-
660651
const tlsEnabled = daemonCfg.gateway?.tls?.enabled === true;
661652
const shouldUseLocalTlsRuntime = opts.probe && !probeUrlOverride && tlsEnabled;
662653
const tlsRuntime = shouldUseLocalTlsRuntime

‎src/daemon/service.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,23 @@ describe("readGatewayServiceState", () => {
186186
);
187187
});
188188

189+
it("preserves runtime probe failures as an explicit unknown state", async () => {
190+
const service = createService({
191+
isLoaded: vi.fn(async () => true),
192+
readRuntime: vi.fn(async () => {
193+
throw new Error("systemctl show timed out");
194+
}),
195+
});
196+
197+
const state = await readGatewayServiceState(service, { timeoutMs: 100 });
198+
199+
expect(state.running).toBe(false);
200+
expect(state.runtime).toEqual({
201+
status: "unknown",
202+
detail: "Error: systemctl show timed out",
203+
});
204+
});
205+
189206
it("validates merged service env before native status probes", async () => {
190207
const isLoaded = vi.fn(async () => true);
191208
const readRuntime = vi.fn(async () => ({ status: "running" as const }));

‎src/daemon/service.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,13 @@ export async function readGatewayServiceState(
196196
// bound; isLoaded/readRuntime can spawn service-manager subprocesses.
197197
const [loaded, runtime] = await Promise.all([
198198
service.isLoaded({ env, timeoutMs: args.timeoutMs }).catch(() => false),
199-
service.readRuntime(env, { timeoutMs: args.timeoutMs }).catch(() => undefined),
199+
service.readRuntime(env, { timeoutMs: args.timeoutMs }).catch(
200+
(error: unknown) =>
201+
({
202+
status: "unknown",
203+
detail: String(error),
204+
}) satisfies GatewayServiceRuntime,
205+
),
200206
]);
201207
return {
202208
installed: command !== null,

0 commit comments

Comments
 (0)