Skip to content

Commit 4f3f314

Browse files
committed
fix(cli): the check cache hashes files without a stat race and its tests run before the signal test
1 parent 1c2c3a7 commit 4f3f314

4 files changed

Lines changed: 83 additions & 62 deletions

File tree

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

Lines changed: 43 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -3991,50 +3991,6 @@ it("applies transition sample limits within the requested range", async () => {
39913991
expect(report.layout.transitionSamplesDropped).toBe(3);
39923992
});
39933993

3994-
describe("check stopped by a signal", () => {
3995-
it("SIGTERM prints the report so far, then exits 143", async () => {
3996-
const { deps, runBrowserCheck } = dependencies(fakeDriver());
3997-
const reachedBrowser = new Promise<void>((resolve) => {
3998-
runBrowserCheck.mockImplementation(() => {
3999-
resolve();
4000-
return new Promise<CheckBrowserResult>(() => undefined);
4001-
});
4002-
});
4003-
const order: string[] = [];
4004-
registerRootExitRequester((code) => order.push(`exit ${code}`));
4005-
const log = vi.spyOn(console, "log").mockImplementation((line) => {
4006-
order.push(`print ${String(line).slice(0, 1)}`);
4007-
});
4008-
const command = createCheckCommand({
4009-
resolveProject: () => PROJECT,
4010-
runPipeline: (project, options) => runCheckPipeline(project, options, deps),
4011-
prepareMedia: vi.fn(async () => []),
4012-
withMeta: (value) => value,
4013-
});
4014-
4015-
const running = runCommand(command, { rawArgs: ["--json"] });
4016-
await reachedBrowser;
4017-
process.emit("SIGTERM");
4018-
await running;
4019-
await vi.waitFor(() => expect(order).toContain("exit 143"));
4020-
4021-
const report = JSON.parse(String(log.mock.calls[0]?.[0]));
4022-
expect(report.ok).toBe(false);
4023-
expect(report.runtime.findings.map((finding: CheckFinding) => finding.message)).toContain(
4024-
"Check stopped before finishing (SIGTERM).",
4025-
);
4026-
expect(order).toEqual(["print {", "exit 143"]);
4027-
});
4028-
});
4029-
4030-
describe("check --lint-verbose", () => {
4031-
it("is a known flag, as render, preview and publish spell it, and a made-up one still is not", () => {
4032-
const check = createCheckCommand() as never;
4033-
expect(() => assertKnownFlags(check, ["--lint-verbose", "--json"], "check")).not.toThrow();
4034-
expect(() => assertKnownFlags(check, ["--lint-loud"], "check")).toThrow("Unknown flag");
4035-
});
4036-
});
4037-
40383994
describe("check cache", () => {
40393995
const dirs: string[] = [];
40403996
afterEach(() => {
@@ -4098,3 +4054,46 @@ describe("check cache", () => {
40984054
expect(runPipeline).toHaveBeenCalledTimes(4);
40994055
});
41004056
});
4057+
describe("check stopped by a signal", () => {
4058+
it("SIGTERM prints the report so far, then exits 143", async () => {
4059+
const { deps, runBrowserCheck } = dependencies(fakeDriver());
4060+
const reachedBrowser = new Promise<void>((resolve) => {
4061+
runBrowserCheck.mockImplementation(() => {
4062+
resolve();
4063+
return new Promise<CheckBrowserResult>(() => undefined);
4064+
});
4065+
});
4066+
const order: string[] = [];
4067+
registerRootExitRequester((code) => order.push(`exit ${code}`));
4068+
const log = vi.spyOn(console, "log").mockImplementation((line) => {
4069+
order.push(`print ${String(line).slice(0, 1)}`);
4070+
});
4071+
const command = createCheckCommand({
4072+
resolveProject: () => PROJECT,
4073+
runPipeline: (project, options) => runCheckPipeline(project, options, deps),
4074+
prepareMedia: vi.fn(async () => []),
4075+
withMeta: (value) => value,
4076+
});
4077+
4078+
const running = runCommand(command, { rawArgs: ["--json"] });
4079+
await reachedBrowser;
4080+
process.emit("SIGTERM");
4081+
await running;
4082+
await vi.waitFor(() => expect(order).toContain("exit 143"));
4083+
4084+
const report = JSON.parse(String(log.mock.calls[0]?.[0]));
4085+
expect(report.ok).toBe(false);
4086+
expect(report.runtime.findings.map((finding: CheckFinding) => finding.message)).toContain(
4087+
"Check stopped before finishing (SIGTERM).",
4088+
);
4089+
expect(order).toEqual(["print {", "exit 143"]);
4090+
});
4091+
});
4092+
4093+
describe("check --lint-verbose", () => {
4094+
it("is a known flag, as render, preview and publish spell it, and a made-up one still is not", () => {
4095+
const check = createCheckCommand() as never;
4096+
expect(() => assertKnownFlags(check, ["--lint-verbose", "--json"], "check")).not.toThrow();
4097+
expect(() => assertKnownFlags(check, ["--lint-loud"], "check")).toThrow("Unknown flag");
4098+
});
4099+
});

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

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -321,16 +321,7 @@ export function createCheckCommand(
321321
return;
322322
}
323323
recordLastCheck({ at: new Date().toISOString(), codes: {} });
324-
const key = checkCacheable(options)
325-
? checkCacheKey(project.dir, options, VERSION)
326-
: undefined;
327-
const cached = key ? readCachedPass(project.dir, key) : undefined;
328-
const report =
329-
cached ??
330-
(await withProjectLock(project.dir, "check", () =>
331-
dependencies.runPipeline(project, options),
332-
));
333-
if (key && !cached) storePass(project.dir, key, report);
324+
const report = await checkOrReplay(dependencies, project, options);
334325
recordLastCheck({
335326
at: new Date().toISOString(),
336327
exitCode: checkExitCode(report),
@@ -364,6 +355,21 @@ export function createCheckCommand(
364355
});
365356
}
366357

358+
async function checkOrReplay(
359+
dependencies: CheckCommandDependencies,
360+
project: ProjectDir,
361+
options: CheckOptions,
362+
): Promise<SavedCheckReport> {
363+
const key = checkCacheable(options) ? checkCacheKey(project.dir, options, VERSION) : undefined;
364+
const cached = key ? readCachedPass(project.dir, key) : undefined;
365+
if (cached) return cached;
366+
const report = await withProjectLock(project.dir, "check", () =>
367+
dependencies.runPipeline(project, options),
368+
);
369+
if (key) storePass(project.dir, key, report);
370+
return report;
371+
}
372+
367373
function reportCheckFailure(
368374
error: unknown,
369375
asJson: boolean,

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

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
import { createHash } from "node:crypto";
2-
import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
2+
import {
3+
closeSync,
4+
fstatSync,
5+
mkdirSync,
6+
openSync,
7+
readFileSync,
8+
readdirSync,
9+
writeFileSync,
10+
} from "node:fs";
311
import { join } from "node:path";
412
import type { CheckOptions, CheckReport } from "./checkTypes.js";
513

@@ -11,6 +19,19 @@ function cachePath(projectDir: string): string {
1119
return join(projectDir, ".hyperframes", "cache", "check.json");
1220
}
1321

22+
function fileFingerprint(path: string): string {
23+
const fd = openSync(path, "r");
24+
try {
25+
const stat = fstatSync(fd);
26+
if (stat.isDirectory()) return "dir";
27+
return stat.size <= HASH_CONTENT_UP_TO
28+
? createHash("sha256").update(readFileSync(fd)).digest("hex")
29+
: `${stat.size}:${stat.mtimeMs}`;
30+
} finally {
31+
closeSync(fd);
32+
}
33+
}
34+
1435
function hashTree(dir: string, prefix: string, hash: ReturnType<typeof createHash>): void {
1536
const entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
1637
a.name < b.name ? -1 : 1,
@@ -19,11 +40,8 @@ function hashTree(dir: string, prefix: string, hash: ReturnType<typeof createHas
1940
if (SKIPPED_DIRS.has(entry.name)) continue;
2041
const path = join(dir, entry.name);
2142
const name = `${prefix}${entry.name}`;
22-
const stat = statSync(path);
23-
if (stat.isDirectory()) hashTree(path, `${name}/`, hash);
24-
else if (stat.size <= HASH_CONTENT_UP_TO)
25-
hash.update(`${name}\0${createHash("sha256").update(readFileSync(path)).digest("hex")}\0`);
26-
else hash.update(`${name}\0${stat.size}:${stat.mtimeMs}\0`);
43+
if (entry.isDirectory()) hashTree(path, `${name}/`, hash);
44+
else hash.update(`${name}\0${fileFingerprint(path)}\0`);
2745
}
2846
}
2947

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

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ export interface CheckOptions {
3838
autoProxy?: boolean;
3939
browserGpuMode?: BrowserGpuMode;
4040
includeUnmounted?: boolean;
41-
/** False (--no-cache) re-runs even when nothing changed since the last pass. */
4241
cache?: boolean;
4342
}
4443

@@ -398,7 +397,6 @@ export interface CheckReport {
398397
notes: string[];
399398
};
400399
ok: boolean;
401-
/** Set when this is the stored result of the last pass over an unchanged project. */
402400
cached?: { at: string };
403401
strict: boolean;
404402
browserSkipped: boolean;

0 commit comments

Comments
 (0)