Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

test-cached.ts

159 lines6.2 KB

1// @effect-diagnostics nodeBuiltinImport:off globalConsole:off
2import * as NodeCrypto from "node:crypto";
3import * as NodeChildProcess from "node:child_process";
4import * as NodeFS from "node:fs";
5import * as NodePath from "node:path";
6import * as NodeUtil from "node:util";
7​
8import { matchesTestPath } from "./lib/cached-tests.ts";
9import { shardedTestFiles } from "./lib/sharded-tests.ts";
10​
11const root = NodePath.resolve(import.meta.dirname, "..");
12const { values, positionals } = NodeUtil.parseArgs({
13 args: process.argv[2] === "--" ? process.argv.slice(3) : process.argv.slice(2),
14 allowPositionals: true,
15 options: {
16 "group-size": { type: "string", default: "1" },
17 concurrency: { type: "string", default: "1" },
18 shard: { type: "string" },
19 report: { type: "string" },
20 "verify-hits": { type: "string", default: "0" },
21 uncached: { type: "string", multiple: true, default: [] },
22 help: { type: "boolean", short: "h" },
23 },
24});
25if (values.help) {
26 console.log(
27 "vp run test:cached [--group-size 1] [--concurrency 1] [--shard index/count] [--uncached file] [test files or directories]",
28 );
29 process.exit(0);
31const groupSize = Number(values["group-size"]);
32const concurrency = Number(values.concurrency);
33const verifyHits = Number(values["verify-hits"]);
34if (!Number.isSafeInteger(verifyHits) || verifyHits < 0)
35 throw new Error("Invalid verification count");
36if (![groupSize, concurrency].every((value) => Number.isSafeInteger(value) && value > 0)) {
37 throw new Error("Group size and concurrency must be positive integers");
39if (values.shard && positionals.length !== 1) {
40 throw new Error("Sharding requires exactly one test project directory");
42const candidates = values.shard
43 ? (await shardedTestFiles(NodePath.resolve(positionals[0]!), values.shard)).map((file) =>
44 NodePath.relative(root, file),
45 )
46 : NodeChildProcess.execFileSync(
47 "git",
48 ["ls-files", "-z", "--cached", "--others", "--exclude-standard"],
49 { cwd: root, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 },
50 ).split("\0");
51const filters = positionals.map((path) => NodePath.relative(root, NodePath.resolve(path)));
52const isSelectable = (file: string) =>
53 /\.(?:test|spec)\.[cm]?[jt]sx?$/.test(file) &&
54 !file.startsWith(".repos/") &&
55 NodeFS.existsSync(NodePath.join(root, file)) &&
56 matchesTestPath(file, filters);
57if (values.shard) {
58 const rejected = candidates.filter((file) => !isSelectable(file));
59 if (rejected.length)
60 throw new Error(`Discovered tests cannot be selected: ${rejected.join(", ")}`);
62const files = [...new Set(candidates)].filter(isSelectable);
63if (files.length === 0) {
64 console.error("No test files matched");
65 process.exit(values.shard ? 0 : 1);
67console.log(
68 `Cached tests: ${files.length} files, ${groupSize} per task, concurrency ${concurrency}`,
69);
70const env = {
71 ...process.env,
72 T3_CACHED_TESTS: JSON.stringify({
73 files,
74 groupSize,
75 uncached: values.uncached.map((file) => NodePath.relative(root, NodePath.resolve(file))),
76 }),
77};
78const started = performance.now();
79const result = NodeChildProcess.spawnSync(
80 NodePath.join(root, "node_modules/.bin/vp"),
81 ["run", "--concurrency-limit", String(concurrency), "test-cache"],
82 {
83 cwd: root,
84 env,
85 stdio: "inherit",
86 },
87);
88if (result.error) throw result.error;
89const cacheRunMs = performance.now() - started;
90process.exitCode = result.status ?? 1;
91if (values.report || verifyHits > 0) {
92 const cacheRoot =
93 process.env.VITE_CACHE_PATH || NodePath.join(root, "node_modules/.vite/task-cache");
94 const summaryFiles = NodeFS.readdirSync(cacheRoot, { withFileTypes: true })
95 .filter((entry) => entry.isDirectory())
96 .map((entry) => NodePath.join(cacheRoot, entry.name, "last-summary.json"))
97 .filter((file) => NodeFS.existsSync(file))
98 .sort((a, b) => NodeFS.statSync(b).mtimeMs - NodeFS.statSync(a).mtimeMs);
99 const summary: {
100 tasks: Array<{
101 task_name: string;
102 result: { CacheHit?: { source: string; saved_duration_ms: number } };
103 }>;
104 } = JSON.parse(NodeFS.readFileSync(summaryFiles[0]!, "utf8"));
105 const rank = (task: string) =>
106 NodeCrypto.createHash("sha256")
107 .update(
108 `${process.env.GITHUB_RUN_ID || "local"}:${process.env.GITHUB_RUN_ATTEMPT || "1"}:${task}`,
109 )
110 .digest("hex");
111 const hits = summary.tasks.filter((task) => task.result.CacheHit);
112 const verify = hits
113 .toSorted((a, b) => rank(a.task_name).localeCompare(rank(b.task_name)))
114 .slice(0, verifyHits);
115 const verification: Array<{ task: string; exitCode: number; durationMs: number }> = [];
116 if (result.status === 0) {
117 for (const task of verify) {
118 console.log(`Verifying cached result without cache: ${task.task_name}`);
119 const start = performance.now();
120 const audit = NodeChildProcess.spawnSync(
121 NodePath.join(root, "node_modules/.bin/vp"),
122 ["run", "--no-cache", "--remote-cache", "off", task.task_name],
123 { cwd: root, env, stdio: "inherit" },
124 );
125 if (audit.error) throw audit.error;
126 verification.push({
127 task: task.task_name,
128 exitCode: audit.status ?? 1,
129 durationMs: performance.now() - start,
130 });
131 if (audit.status !== 0) process.exitCode = audit.status ?? 1;
132 }
133 }
134 const report = {
135 shard: values.shard,
136 files,
137 cacheRunMs,
138 exitCode: result.status,
139 summary,
140 verification,
141 };
142 if (values.report) {
143 NodeFS.mkdirSync(NodePath.dirname(values.report), { recursive: true });
144 NodeFS.writeFileSync(values.report, `${JSON.stringify(report, null, 2)}\n`);
145 }
146 if (process.env.GITHUB_STEP_SUMMARY) {
147 const remote = hits.filter((task) => task.result.CacheHit?.source === "Remote").length;
148 const savedMs = hits.reduce(
149 (total, task) => total + (task.result.CacheHit?.saved_duration_ms ?? 0),
150 0,
151 );
152 NodeFS.appendFileSync(
153 process.env.GITHUB_STEP_SUMMARY,
154 `### Server test cache (${values.shard || "unsharded"})\n\n` +
155 `${files.length} files selected; ${hits.length} hits (${remote} remote); ${(savedMs / 1000).toFixed(1)}s task runtime avoided; ${(cacheRunMs / 1000).toFixed(1)}s elapsed.\n\n` +
156 `${verification.length} cached results re-executed without cache; ${verification.filter((audit) => audit.exitCode !== 0).length} verification failures.\n`,
157 );
158 }