Skip to content

Commit a906f57

Browse files
committed
fix(cli): a check that is stopped by a signal prints the report it has so far
Killed by SIGTERM or SIGINT, check closed Chrome and exited 143 or 130 with nothing on stdout, so a caller that stops a long check got no result at all. The signal now ends the check the way an expired deadline does: findings already made are kept, one finding says the check stopped before finishing, and the report is printed before the process exits with the signal's code.
1 parent d9e0d54 commit a906f57

6 files changed

Lines changed: 121 additions & 10 deletions

File tree

‎packages/cli/src/browser/launch.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,18 @@ const EXIT_POLL_MS = 50;
3131
let listening = false;
3232
let shutdown: Promise<void> | undefined;
3333

34+
const stopListeners = new Set<(signal: "SIGINT" | "SIGTERM") => void>();
35+
36+
export function onStopSignal(listener: (signal: "SIGINT" | "SIGTERM") => void): () => void {
37+
ownSignals();
38+
stopListeners.add(listener);
39+
return () => stopListeners.delete(listener);
40+
}
41+
3442
/** CLI signals close browser admission and native processes before the root exits. */
3543
function stopForSignal(signal: "SIGINT" | "SIGTERM"): void {
3644
if (shutdown) return;
45+
for (const listener of stopListeners) listener(signal);
3746
shutdown = closeManagedBrowsers();
3847
void shutdown.then(
3948
() => requestCliExit(signal === "SIGINT" ? 130 : 143),

‎packages/cli/src/commands/check.test.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ import {
4545
type MotionSpecResolution,
4646
} from "../utils/checkPipeline.js";
4747
import { resolveCompositionViewportFromHtml } from "../utils/compositionViewport.js";
48-
import { consumeCommandResult } from "../utils/commandResult.js";
48+
import { consumeCommandResult, registerRootExitRequester } from "../utils/commandResult.js";
4949
import { ambiguousIssue } from "../utils/motionAudit.js";
5050
import type { ProjectLintResult } from "../utils/lintProject.js";
5151
import type {
@@ -3120,3 +3120,39 @@ it("applies transition sample limits within the requested range", async () => {
31203120
expect(report.layout.transitionSamples).toEqual([7.8, 8]);
31213121
expect(report.layout.transitionSamplesDropped).toBe(3);
31223122
});
3123+
3124+
describe("check stopped by a signal", () => {
3125+
it("SIGTERM prints the report so far, then exits 143", async () => {
3126+
const { deps, runBrowserCheck } = dependencies(fakeDriver());
3127+
const reachedBrowser = new Promise<void>((resolve) => {
3128+
runBrowserCheck.mockImplementation(() => {
3129+
resolve();
3130+
return new Promise<CheckBrowserResult>(() => undefined);
3131+
});
3132+
});
3133+
const order: string[] = [];
3134+
registerRootExitRequester((code) => order.push(`exit ${code}`));
3135+
const log = vi.spyOn(console, "log").mockImplementation((line) => {
3136+
order.push(`print ${String(line).slice(0, 1)}`);
3137+
});
3138+
const command = createCheckCommand({
3139+
resolveProject: () => PROJECT,
3140+
runPipeline: (project, options) => runCheckPipeline(project, options, deps),
3141+
prepareMedia: vi.fn(async () => []),
3142+
withMeta: (value) => value,
3143+
});
3144+
3145+
const running = runCommand(command, { rawArgs: ["--json"] });
3146+
await reachedBrowser;
3147+
process.emit("SIGTERM");
3148+
await running;
3149+
await vi.waitFor(() => expect(order).toContain("exit 143"));
3150+
3151+
const report = JSON.parse(String(log.mock.calls[0]?.[0]));
3152+
expect(report.ok).toBe(false);
3153+
expect(report.runtime.findings.map((finding: CheckFinding) => finding.message)).toContain(
3154+
"Check stopped before finishing (SIGTERM).",
3155+
);
3156+
expect(order).toEqual(["print {", "exit 143"]);
3157+
});
3158+
});

‎packages/cli/src/commands/check.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import type { ArgsDef } from "citty";
1717
import type { Example } from "./_examples.js";
1818
import { parseAt } from "./layout.js";
1919
import { c } from "../ui/colors.js";
20+
import { registerBrowserSessionCleanup } from "../browser/launch.js";
2021
import { normalizeErrorMessage } from "../utils/errorMessage.js";
2122
import { setCommandExitCode } from "../utils/commandResult.js";
2223
import { swallowedFlagUsageError } from "../utils/reject-unknown-flags.js";
@@ -272,6 +273,7 @@ export function createCheckCommand(
272273
const args = parseArgs(rawArgs, CHECK_COMMAND_ARGS);
273274
const asJson = args.json === true;
274275

276+
const reported = untilReported();
275277
try {
276278
const project = dependencies.resolveProject(args.dir);
277279
const options = parseCheckOptions(args);
@@ -307,11 +309,38 @@ export function createCheckCommand(
307309
console.error(`${c.error("✗")} Check failed: ${message}`);
308310
}
309311
setCommandExitCode(1);
312+
} finally {
313+
reported.done();
310314
}
311315
},
312316
});
313317
}
314318

319+
const REPORT_GRACE_MS = 5_000;
320+
321+
function untilReported(): { done: () => void } {
322+
let done = (): void => undefined;
323+
const printed = new Promise<void>((resolve) => {
324+
done = resolve;
325+
});
326+
const forget = registerBrowserSessionCleanup(
327+
() =>
328+
new Promise<void>((resolve) => {
329+
const timer = setTimeout(resolve, REPORT_GRACE_MS);
330+
void printed.then(() => {
331+
clearTimeout(timer);
332+
resolve();
333+
});
334+
}),
335+
);
336+
return {
337+
done: () => {
338+
done();
339+
forget();
340+
},
341+
};
342+
}
343+
315344
async function runPrepareMedia(
316345
dependencies: CheckCommandDependencies,
317346
project: ProjectDir,

‎packages/cli/src/utils/checkDeadline.test.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { afterEach, expect, it, vi } from "vitest";
2-
import { CheckDeadline, CheckDeadlineError } from "./checkDeadline.js";
2+
import { CheckDeadline, CheckDeadlineError, CheckStoppedError } from "./checkDeadline.js";
33

44
afterEach(() => vi.useRealTimers());
55

@@ -158,3 +158,21 @@ it("an operation that settles restarts the idle clock", async () => {
158158
await deadline.close();
159159
}
160160
});
161+
162+
it("a stop ends the check at once, keeping what it already found", async () => {
163+
vi.useFakeTimers();
164+
const deadline = new CheckDeadline();
165+
deadline.start();
166+
deadline.keepPartial(() => ({ screenshots: [] }));
167+
try {
168+
const sample = deadline.run(() => rejectOnAbort(deadline.signal));
169+
const failed = expect(sample).rejects.toThrow("Check stopped before finishing (SIGTERM).");
170+
deadline.stop("SIGTERM");
171+
await failed;
172+
await expect(deadline.run(async () => "late")).rejects.toBeInstanceOf(CheckStoppedError);
173+
expect(deadline.signal.aborted).toBe(true);
174+
expect(deadline.partialResult()).toEqual({ screenshots: [] });
175+
} finally {
176+
await deadline.close();
177+
}
178+
});

‎packages/cli/src/utils/checkDeadline.ts‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,17 +33,23 @@ export class CheckDeadlineError extends Error {
3333
}
3434
}
3535

36+
export class CheckStoppedError extends Error {
37+
constructor(signal: string) {
38+
super(`Check stopped before finishing (${signal}).`);
39+
}
40+
}
41+
3642
/** Ends a check that makes no progress for CHECK_IDLE_MS; each phase entered or operation settled restarts it. */
3743
export class CheckDeadline {
3844
private readonly abort = new AbortController();
3945
private readonly operations = new Set<Promise<unknown>>();
4046
readonly signal = this.abort.signal;
4147
private readonly browsers = new Set<Browser>();
4248
private readonly scripts: string[] = [];
43-
private expired: CheckDeadlineError | undefined;
49+
private expired: Error | undefined;
4450
private timer: NodeJS.Timeout | undefined;
4551
private readonly expiry: Promise<never>;
46-
private rejectExpiry!: (error: CheckDeadlineError) => void;
52+
private rejectExpiry!: (error: Error) => void;
4753
private phase: "waiting" | "started" | "closed" = "waiting";
4854
private work: { phase: CheckPhase; since: number } | undefined;
4955
private readonly spent = new Map<CheckPhase, number>();
@@ -95,13 +101,24 @@ export class CheckDeadline {
95101
private rearm(): void {
96102
if (this.phase !== "started" || this.expired) return;
97103
clearTimeout(this.timer);
98-
this.timer = setTimeout(() => {
99-
this.expired = new CheckDeadlineError(this.scripts.at(-1), this.describe());
100-
this.rejectExpiry(this.expired);
101-
this.abort.abort(this.expired);
102-
}, CHECK_IDLE_MS);
104+
this.timer = setTimeout(
105+
() => this.expire(new CheckDeadlineError(this.scripts.at(-1), this.describe())),
106+
CHECK_IDLE_MS,
107+
);
103108
}
104109

110+
private expire(error: Error): void {
111+
clearTimeout(this.timer);
112+
this.expired = error;
113+
this.rejectExpiry(error);
114+
this.abort.abort(error);
115+
}
116+
117+
stop = (signal: string): void => {
118+
if (this.expired || this.phase === "closed") return;
119+
this.expire(new CheckStoppedError(signal));
120+
};
121+
105122
ownBrowser = (browser: Browser): void => {
106123
if (this.expired) throw this.expired;
107124
if (this.phase === "closed") throw new Error("Check has already finished.");

‎packages/cli/src/utils/checkPipeline.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { BrowserCleanupError } from "../browser/launch.js";
1+
import { BrowserCleanupError, onStopSignal } from "../browser/launch.js";
22
import type { CheckProgress } from "./checkProgress.js";
33
import { CheckDeadline, CheckDeadlineError, type CheckPhase } from "./checkDeadline.js";
44
import {
@@ -1655,6 +1655,7 @@ export async function runCheckPipeline(
16551655
: [];
16561656

16571657
const deadline = new CheckDeadline();
1658+
const forgetStop = onStopSignal(deadline.stop);
16581659
let outcome: { kind: "report"; report: CheckReport } | { kind: "failed"; error: unknown };
16591660
try {
16601661
let browser: CheckBrowserResult;
@@ -1691,6 +1692,7 @@ export async function runCheckPipeline(
16911692
} catch (error) {
16921693
outcome = { kind: "failed", error };
16931694
}
1695+
forgetStop();
16941696
try {
16951697
await deadline.close();
16961698
} catch (error) {

0 commit comments

Comments
 (0)