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

check-changed.test.ts

448 lines16.3 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6import { expect } from "vite-plus/test";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import * as Option from "effect/Option";
9import { assert, describe, it } from "@effect/vitest";
10import * as Clock from "effect/Clock";
11import * as Effect from "effect/Effect";
12import * as Fiber from "effect/Fiber";
13import * as Sink from "effect/Sink";
14import * as Stream from "effect/Stream";
15import { ChildProcess, ChildProcessSpawner } from "effect/process";
16import * as TestClock from "effect/testing/TestClock";
17​
18import {
19 comparisonBase,
20 defaultConcurrency,
21 docReaderTests,
22 gitLines,
23 runSteps,
24 splitTests,
25 type Step,
26} from "./check-changed.ts";
27import { decide, readWorkspace } from "../.github/scripts/ci-changes.cjs";
28​
29const GiB = 1024 ** 3;
30​
31describe("check:changed", () => {
32 it("bounds the default concurrency by the scarcer of cores and available memory", () => {
33 assert.strictEqual(defaultConcurrency(32, 128 * GiB), 16);
34 assert.strictEqual(defaultConcurrency(32, 20 * GiB), 3);
35 assert.strictEqual(defaultConcurrency(4, 15 * GiB), 2);
36 assert.strictEqual(defaultConcurrency(4, 2 * GiB), 1);
37 assert.strictEqual(defaultConcurrency(1, 64 * GiB), 1);
38 });
39​
40 it("runs the server tests for the one guide they read and leaves other docs inert", () => {
41 const packages = readWorkspace();
42 assert.isTrue(
43 decide(["docs/user/t3-connect-troubleshooting.md"], packages, false).outputs.test_server,
44 );
45 assert.deepStrictEqual(docReaderTests(["docs/user/t3-connect-troubleshooting.md"]), [
46 "apps/server/src/cloud/ConnectReachability.test.ts",
47 ]);
48 assert.deepStrictEqual(decide(["docs/user/install.md"], packages, false).affected, []);
49 });
50​
51 it.effect(
52 "keeps weighted steps within the budget, in order, and serial steps one at a time",
53 () =>
54 Effect.gen(function* () {
55 const startedAt: Record<string, number> = {};
56 let active = 0;
57 let maxActive = 0;
58 let serialActive = 0;
59 let maxSerial = 0;
60 const step = (
61 name: string,
62 options: { weight?: number; serial?: boolean } = {},
63 ): Step<never> => {
64 const slots = Math.min(options.weight ?? 1, 3);
65 return {
66 name,
67 ...options,
68 run: Effect.gen(function* () {
69 startedAt[name] = (yield* Clock.currentTimeMillis) / 1000;
70 active += slots;
71 maxActive = Math.max(maxActive, active);
72 if (options.serial) maxSerial = Math.max(maxSerial, ++serialActive);
73 yield* Effect.sleep("1 second");
74 active -= slots;
75 if (options.serial) serialActive--;
76 return { ok: true, output: "" };
77 }),
78 };
79 };
80 const fiber = yield* runSteps(
81 [
82 step("light 1"),
83 // Above the budget, so it holds every slot rather than never starting.
84 step("heavy", { weight: 5 }),
85 step("pair", { weight: 2 }),
86 step("light 2"),
87 step("test 1", { serial: true }),
88 step("test 2", { serial: true }),
89 ],
90 { concurrency: 3, timeoutSeconds: 60 },
91 ).pipe(Effect.forkChild);
92 yield* TestClock.adjust("10 seconds");
93 const results = yield* Fiber.join(fiber);
94​
95 assert.deepStrictEqual(
96 results.map((result) => result.outcome),
97 ["pass", "pass", "pass", "pass", "pass", "pass"],
98 );
99 assert.strictEqual(maxActive, 3);
100 // Lighter steps queued behind the heavy one never start ahead of it.
101 assert.deepStrictEqual(startedAt, {
102 "light 1": 0,
103 heavy: 1,
104 pair: 2,
105 "light 2": 2,
106 "test 1": 3,
107 "test 2": 4,
108 });
109 assert.strictEqual(maxSerial, 1);
110 }),
111 );
112​
113 it.effect("interrupts a step at its timeout and reports TIMEOUT, apart from FAIL", () =>
114 Effect.gen(function* () {
115 let interrupted = false;
116 const fiber = yield* runSteps(
117 [
118 {
119 name: "hangs",
120 run: Effect.never.pipe(
121 Effect.onInterrupt(() => Effect.sync(() => (interrupted = true))),
122 ),
123 },
124 { name: "fails", run: Effect.succeed({ ok: false, output: "error" }) },
125 { name: "passes", run: Effect.succeed({ ok: true, output: "" }) },
126 ],
127 { concurrency: 3, timeoutSeconds: 10 },
128 ).pipe(Effect.forkChild);
129 yield* TestClock.adjust("9 seconds");
130 assert.isFalse(interrupted);
131 yield* TestClock.adjust("1 second");
132 const results = yield* Fiber.join(fiber);
133​
134 assert.isTrue(interrupted);
135 assert.deepStrictEqual(
136 results.map(({ name, outcome, time }) => [name, outcome, time]),
137 [
138 ["hangs", "TIMEOUT", "killed after 10s"],
139 ["fails", "FAIL", "0.0s"],
140 ["passes", "pass", "0.0s"],
141 ],
142 );
143 }),
144 );
145​
146 it("runs the .github/scripts node:test files with node --test, not vitest", () => {
147 assert.deepStrictEqual(
148 splitTests([
149 "apps/server/src/ws.test.ts",
150 ".github/scripts/ci-changes.test.cjs",
151 ".github\\scripts\\thread-transfer-report.test.cjs",
152 "scripts/check-changed.test.ts",
153 ]),
154 {
155 vitestTests: ["apps/server/src/ws.test.ts", "scripts/check-changed.test.ts"],
156 nodeTests: [
157 ".github/scripts/ci-changes.test.cjs",
158 ".github\\scripts\\thread-transfer-report.test.cjs",
159 ],
160 },
161 );
162 });
163​
164 it.effect("fails instead of returning an empty file list when git exits nonzero", () => {
165 const spawner = (exitCode: number) =>
166 ChildProcessSpawner.make(() =>
167 Effect.succeed(
168 ChildProcessSpawner.makeHandle({
169 pid: ChildProcessSpawner.ProcessId(1),
170 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
171 isRunning: Effect.succeed(false),
172 kill: () => Effect.void,
173 unref: Effect.succeed(Effect.void),
174 stdin: Sink.drain,
175 stdout: Stream.encodeText(Stream.make(exitCode === 0 ? "a.ts\nb.ts\n" : "")),
176 stderr: Stream.encodeText(
177 Stream.make(exitCode === 0 ? "" : "fatal: index file corrupt"),
178 ),
179 all: Stream.empty,
180 getInputFd: () => Sink.drain,
181 getOutputFd: () => Stream.empty,
182 }),
183 ),
184 );
185 return Effect.gen(function* () {
186 const listed = yield* gitLines("/repo", ["ls-files"]).pipe(
187 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner(0)),
188 );
189 assert.deepStrictEqual(listed, ["a.ts", "b.ts"]);
190 const error = yield* gitLines("/repo", ["ls-files"]).pipe(
191 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner(128)),
192 Effect.flip,
193 );
194 assert.strictEqual(
195 error,
196 "check:changed: git ls-files exited with 128: fatal: index file corrupt",
197 );
198 });
199 });
200​
201 it.each([
202 "packages/shared/src/testing/longTempDir.ts",
203 "packages/shared/src/testing/providerEnv.ts",
204 ])("tests every package when the shared test setup file %s changes", (file) => {
205 assert.strictEqual(decide([file], readWorkspace(), false).outputs.test_packages, "");
206 });
207});
208​
209// Hooks export GIT_DIR and GIT_INDEX_FILE, and user config or the default
210// ~/.config/git/ignore can ignore or sign fixture files.
211const fixtureConfig = {
212 "core.excludesFile": NodeOS.devNull,
213 "user.name": "Fixture",
214 "user.email": "fixture@example.invalid",
215};
216const env = {
217 ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_"))),
218 GIT_CONFIG_GLOBAL: NodeOS.devNull,
219 GIT_CONFIG_NOSYSTEM: "1",
220 GIT_CONFIG_COUNT: String(Object.keys(fixtureConfig).length),
221 ...Object.fromEntries(
222 Object.entries(fixtureConfig).flatMap(([key, value], index) => [
223 [`GIT_CONFIG_KEY_${index}`, key],
224 [`GIT_CONFIG_VALUE_${index}`, value],
225 ]),
226 ),
227};
228​
229// History A -> B -> C, with HEAD at C. Each remote's main points at A or B.
230function fixture(remotes: Record<string, "A" | "B">) {
231 const root = NodeFS.realpathSync(
232 NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-check-changed-")),
233 );
234 const commits: Record<string, string> = {};
235 try {
236 const write = (file: string, content: string) => {
237 const path = NodePath.join(root, file);
238 NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true });
239 NodeFS.writeFileSync(path, content);
240 };
241 const git = (...args: Array<string>) =>
242 NodeChildProcess.execFileSync("git", args, { cwd: root, encoding: "utf8", env }).trim();
243 git("init");
244 for (const name of ["A", "B", "C"]) {
245 write(`${name}.txt`, name);
246 git("add", ".");
247 git("commit", "-m", name);
248 commits[name] = git("rev-parse", "HEAD");
249 }
250 for (const [remote, commit] of Object.entries(remotes)) {
251 git("remote", "add", remote, NodePath.join(root, "missing"));
252 git("update-ref", `refs/remotes/${remote}/main`, commits[commit]!);
253 }
254 } catch (error) {
255 NodeFS.rmSync(root, { recursive: true, force: true });
256 throw error;
257 }
258 return {
259 commits,
260 root,
261 [Symbol.dispose]() {
262 NodeFS.rmSync(root, { recursive: true, force: true });
263 },
264 };
266​
267const compare = (root: string, ref: Option.Option<string>) =>
268 Effect.gen(function* () {
269 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
270 return yield* comparisonBase(root, ref).pipe(
271 Effect.provideService(
272 ChildProcessSpawner.ChildProcessSpawner,
273 ChildProcessSpawner.make((command) => spawner.spawn(ChildProcess.setEnv(command, env))),
274 ),
275 );
276 }).pipe(Effect.provide(NodeServices.layer), Effect.runPromise);
277​
278it.each(["upstream", "team/upstream"])(
279 "compares against %s/main when the fork's origin/main lags it",
280 async (remote) => {
281 using project = fixture({ origin: "A", [remote]: "B" });
282 const result = await compare(project.root, Option.none());
283 assert.strictEqual(result.base, project.commits.B);
284 assert.strictEqual(result.ref, remote + "/main");
285 },
286);
287​
288it("compares against an explicit ref instead of the closest remote main", async () => {
289 using project = fixture({ origin: "A", upstream: "B" });
290 const result = await compare(project.root, Option.some("origin/main"));
291 assert.strictEqual(result.base, project.commits.A);
292 assert.strictEqual(result.ref, "origin/main");
293});
294​
295function launcherFixture() {
296 const root = NodeFS.realpathSync(
297 NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3 checks & (fixture) ")),
298 );
299 const write = (file: string, content: string) => {
300 const path = NodePath.join(root, file);
301 NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true });
302 NodeFS.writeFileSync(path, content);
303 };
304 for (const file of [
305 "scripts/check-changed.ts",
306 "scripts/check-changed-command.ts",
307 ".github/scripts/ci-changes.cjs",
308 ]) {
309 write(file, NodeFS.readFileSync(NodePath.join(import.meta.dirname, "..", file), "utf8"));
310 }
311 write(".gitignore", "node_modules/\nrecords/\n");
312 write("pnpm-workspace.yaml", "packages:\n - packages/*\n");
313 write(
314 "package.json",
315 JSON.stringify({ type: "module", scripts: { "knip:check": "knip --include files" } }),
316 );
317 write("packages/example/package.json", JSON.stringify({ name: "example" }));
318 const source = "packages/example/space & (draft) %PATH% ! 研究.ts";
319 write(source, "export const value = 1;\n");
320 write(
321 "node_modules/vite-plus/package.json",
322 JSON.stringify({ type: "module", exports: { "./bin": "./cli.js" } }),
323 );
324 write(
325 "node_modules/vite-plus/cli.js",
326 `
327 import fs from 'node:fs';
328 import path from 'node:path';
329 const args = process.argv.slice(2);
330 fs.writeFileSync(path.join(process.env.RECORDS, process.pid + '.json'), JSON.stringify({ args, cwd: process.cwd() }));
331 console.log('fixture stdout: ' + args[0]);
332 console.error('fixture stderr: ' + args[0]);
333 process.exit(args[0] === process.env.FAIL_STEP ? 23 : 0);
334 `,
335 );
336 // Select the Windows launcher without changing the Effect runtime's host platform.
337 write(
338 "scripts/check-changed.ts",
339 NodeFS.readFileSync(NodePath.join(import.meta.dirname, "check-changed.ts"), "utf8").replace(
340 "vitePlusCommand(args, platform)",
341 'vitePlusCommand(args, "win32")',
342 ),
343 );
344 for (const name of ["effect", "@effect/platform-node", "@t3tools/shared"]) {
345 const dest = NodePath.join(root, "node_modules", name);
346 NodeFS.mkdirSync(NodePath.dirname(dest), { recursive: true });
347 NodeFS.symlinkSync(
348 NodeFS.realpathSync(NodePath.join(import.meta.dirname, "node_modules", name)),
349 dest,
350 "junction",
351 );
352 }
353 const git = (...args: Array<string>) =>
354 NodeChildProcess.execFileSync("git", args, { cwd: root, stdio: "pipe", env });
355 git("init");
356 git("add", ".");
357 git(
358 "-c",
359 "user.name=Fixture",
360 "-c",
361 "user.email=fixture@example.invalid",
362 "-c",
363 "commit.gpgsign=false",
364 "-c",
365 "core.hooksPath=",
366 "commit",
367 "-m",
368 "fixture",
369 );
370 const records = NodePath.join(root, "records");
371 NodeFS.mkdirSync(records);
372 return {
373 root,
374 source,
375 write,
376 run(failStep = "") {
377 return NodeChildProcess.spawnSync(process.execPath, ["scripts/check-changed.ts", "HEAD"], {
378 cwd: root,
379 encoding: "utf8",
380 env: { ...env, TEMP: NodeOS.tmpdir(), RECORDS: records, FAIL_STEP: failStep },
381 });
382 },
383 calls: (): Array<{ args: Array<string>; cwd: string }> =>
384 NodeFS.readdirSync(records).map((file) =>
385 JSON.parse(NodeFS.readFileSync(NodePath.join(records, file), "utf8")),
386 ),
387 [Symbol.dispose]() {
388 NodeFS.rmSync(root, { recursive: true, force: true });
389 },
390 };
392​
393it("checks changed source paths through the Windows launcher", () => {
394 using project = launcherFixture();
395 project.write(project.source, "export const value = 2;\n");
396 const result = project.run();
397 expect(result.status, result.stdout + result.stderr).toBe(0);
398 const calls = project.calls();
399 expect(calls.find(({ args }) => args[0] === "lint")).toEqual({
400 args: ["lint", "--no-error-on-unmatched-pattern", project.source],
401 cwd: project.root,
402 });
403 expect(calls.some(({ args }) => args[0] === "fmt" && args.includes(project.source))).toBe(true);
404 expect(calls.some(({ args }) => args[0] === "run" && args.includes("typecheck"))).toBe(true);
405 expect(calls.some(({ args }) => args[0] === "install")).toBe(false);
406 expect(result.stdout).toContain("fixture stdout: lint");
407 expect(result.stdout).toContain("fixture stderr: lint");
408});
409​
410it("lints an Astro component and runs knip when only it changed", () => {
411 using project = launcherFixture();
412 const page = "packages/example/Page.astro";
413 project.write(page, "---\nconst title = 1;\n---\n<h1>{title}</h1>\n");
414 const result = project.run();
415 expect(result.status, result.stdout + result.stderr).toBe(0);
416 const calls = project.calls();
417 expect(calls.find(({ args }) => args[0] === "lint")?.args).toEqual([
418 "lint",
419 "--no-error-on-unmatched-pattern",
420 page,
421 ]);
422 expect(calls.some(({ args }) => args[0] === "exec" && args[1] === "knip")).toBe(true);
423});
424​
425it.each(["install", "lint"])("reports a failing %s step with its output", (step) => {
426 using project = launcherFixture();
427 project.write(project.source, "export const value = 2;\n");
428 project.write(
429 "packages/example/package.json",
430 JSON.stringify({ name: "example", version: "1.0.1" }),
431 );
432 const result = project.run(step);
433 expect(result.status, result.stdout + result.stderr).toBe(1);
434 const install = project.calls().find(({ args }) => args[0] === "install");
435 expect(install?.args, result.stdout + result.stderr).toEqual([
436 "install",
437 "--lockfile-only",
438 "--ignore-scripts",
439 ]);
440 expect(install?.cwd).not.toBe(project.root);
441 expect(result.stdout + result.stderr).toContain(`fixture stdout: ${step}`);
442 expect(result.stdout + result.stderr).toContain(`fixture stderr: ${step}`);
443 expect(result.stdout).toContain(step === "install" ? "FAIL unused patches" : "FAIL lint");
444 if (step === "lint") expect(result.stdout).toContain("pass unused patches");
445 expect(
446 NodeFS.existsSync(NodePath.join(project.root, "node_modules/.cache/check-changed.json")),
447 ).toBe(false);
448});