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

check-changed.test.ts

272 lines9.6 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 * as NodeServices from "@effect/platform-node/NodeServices";
7import * as Option from "effect/Option";
8import { assert, describe, it } from "@effect/vitest";
9import * as Clock from "effect/Clock";
10import * as Effect from "effect/Effect";
11import * as Fiber from "effect/Fiber";
12import * as Sink from "effect/Sink";
13import * as Stream from "effect/Stream";
14import { ChildProcess, ChildProcessSpawner } from "effect/process";
15import * as TestClock from "effect/testing/TestClock";
16​
17import {
18 comparisonBase,
19 defaultConcurrency,
20 gitLines,
21 runSteps,
22 splitTests,
23 type Step,
24} from "./check-changed.ts";
25​
26const GiB = 1024 ** 3;
27​
28describe("check:changed", () => {
29 it("bounds the default concurrency by the scarcer of cores and available memory", () => {
30 assert.strictEqual(defaultConcurrency(32, 128 * GiB), 16);
31 assert.strictEqual(defaultConcurrency(32, 20 * GiB), 3);
32 assert.strictEqual(defaultConcurrency(4, 15 * GiB), 2);
33 assert.strictEqual(defaultConcurrency(4, 2 * GiB), 1);
34 assert.strictEqual(defaultConcurrency(1, 64 * GiB), 1);
35 });
36​
37 it.effect(
38 "keeps weighted steps within the budget, in order, and serial steps one at a time",
39 () =>
40 Effect.gen(function* () {
41 const startedAt: Record<string, number> = {};
42 let active = 0;
43 let maxActive = 0;
44 let serialActive = 0;
45 let maxSerial = 0;
46 const step = (
47 name: string,
48 options: { weight?: number; serial?: boolean } = {},
49 ): Step<never> => {
50 const slots = Math.min(options.weight ?? 1, 3);
51 return {
52 name,
53 ...options,
54 run: Effect.gen(function* () {
55 startedAt[name] = (yield* Clock.currentTimeMillis) / 1000;
56 active += slots;
57 maxActive = Math.max(maxActive, active);
58 if (options.serial) maxSerial = Math.max(maxSerial, ++serialActive);
59 yield* Effect.sleep("1 second");
60 active -= slots;
61 if (options.serial) serialActive--;
62 return { ok: true, output: "" };
63 }),
64 };
65 };
66 const fiber = yield* runSteps(
67 [
68 step("light 1"),
69 // Above the budget, so it holds every slot rather than never starting.
70 step("heavy", { weight: 5 }),
71 step("pair", { weight: 2 }),
72 step("light 2"),
73 step("test 1", { serial: true }),
74 step("test 2", { serial: true }),
75 ],
76 { concurrency: 3, timeoutSeconds: 60 },
77 ).pipe(Effect.forkChild);
78 yield* TestClock.adjust("10 seconds");
79 const results = yield* Fiber.join(fiber);
80​
81 assert.deepStrictEqual(
82 results.map((result) => result.outcome),
83 ["pass", "pass", "pass", "pass", "pass", "pass"],
84 );
85 assert.strictEqual(maxActive, 3);
86 // Lighter steps queued behind the heavy one never start ahead of it.
87 assert.deepStrictEqual(startedAt, {
88 "light 1": 0,
89 heavy: 1,
90 pair: 2,
91 "light 2": 2,
92 "test 1": 3,
93 "test 2": 4,
94 });
95 assert.strictEqual(maxSerial, 1);
96 }),
97 );
98​
99 it.effect("interrupts a step at its timeout and reports TIMEOUT, apart from FAIL", () =>
100 Effect.gen(function* () {
101 let interrupted = false;
102 const fiber = yield* runSteps(
103 [
104 {
105 name: "hangs",
106 run: Effect.never.pipe(
107 Effect.onInterrupt(() => Effect.sync(() => (interrupted = true))),
108 ),
109 },
110 { name: "fails", run: Effect.succeed({ ok: false, output: "error" }) },
111 { name: "passes", run: Effect.succeed({ ok: true, output: "" }) },
112 ],
113 { concurrency: 3, timeoutSeconds: 10 },
114 ).pipe(Effect.forkChild);
115 yield* TestClock.adjust("9 seconds");
116 assert.isFalse(interrupted);
117 yield* TestClock.adjust("1 second");
118 const results = yield* Fiber.join(fiber);
119​
120 assert.isTrue(interrupted);
121 assert.deepStrictEqual(
122 results.map(({ name, outcome, time }) => [name, outcome, time]),
123 [
124 ["hangs", "TIMEOUT", "killed after 10s"],
125 ["fails", "FAIL", "0.0s"],
126 ["passes", "pass", "0.0s"],
127 ],
128 );
129 }),
130 );
131​
132 it("runs the .github/scripts node:test files with node --test, not vitest", () => {
133 assert.deepStrictEqual(
134 splitTests([
135 "apps/server/src/ws.test.ts",
136 ".github/scripts/ci-changes.test.cjs",
137 ".github\\scripts\\thread-transfer-report.test.cjs",
138 "scripts/check-changed.test.ts",
139 ]),
140 {
141 vitestTests: ["apps/server/src/ws.test.ts", "scripts/check-changed.test.ts"],
142 nodeTests: [
143 ".github/scripts/ci-changes.test.cjs",
144 ".github\\scripts\\thread-transfer-report.test.cjs",
145 ],
146 },
147 );
148 });
149​
150 it.effect("fails instead of returning an empty file list when git exits nonzero", () => {
151 const spawner = (exitCode: number) =>
152 ChildProcessSpawner.make(() =>
153 Effect.succeed(
154 ChildProcessSpawner.makeHandle({
155 pid: ChildProcessSpawner.ProcessId(1),
156 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
157 isRunning: Effect.succeed(false),
158 kill: () => Effect.void,
159 unref: Effect.succeed(Effect.void),
160 stdin: Sink.drain,
161 stdout: Stream.encodeText(Stream.make(exitCode === 0 ? "a.ts\nb.ts\n" : "")),
162 stderr: Stream.encodeText(
163 Stream.make(exitCode === 0 ? "" : "fatal: index file corrupt"),
164 ),
165 all: Stream.empty,
166 getInputFd: () => Sink.drain,
167 getOutputFd: () => Stream.empty,
168 }),
169 ),
170 );
171 return Effect.gen(function* () {
172 const listed = yield* gitLines("/repo", ["ls-files"]).pipe(
173 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner(0)),
174 );
175 assert.deepStrictEqual(listed, ["a.ts", "b.ts"]);
176 const error = yield* gitLines("/repo", ["ls-files"]).pipe(
177 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner(128)),
178 Effect.flip,
179 );
180 assert.strictEqual(
181 error,
182 "check:changed: git ls-files exited with 128: fatal: index file corrupt",
183 );
184 });
185 });
186});
187​
188// Hooks export GIT_DIR and GIT_INDEX_FILE, and user config or the default
189// ~/.config/git/ignore can ignore or sign fixture files.
190const fixtureConfig = {
191 "core.excludesFile": NodeOS.devNull,
192 "user.name": "Fixture",
193 "user.email": "fixture@example.invalid",
194};
195const env = {
196 ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_"))),
197 GIT_CONFIG_GLOBAL: NodeOS.devNull,
198 GIT_CONFIG_NOSYSTEM: "1",
199 GIT_CONFIG_COUNT: String(Object.keys(fixtureConfig).length),
200 ...Object.fromEntries(
201 Object.entries(fixtureConfig).flatMap(([key, value], index) => [
202 [`GIT_CONFIG_KEY_${index}`, key],
203 [`GIT_CONFIG_VALUE_${index}`, value],
204 ]),
205 ),
206};
207​
208// History A -> B -> C, with HEAD at C. Each remote's main points at A or B.
209function fixture(remotes: Record<string, "A" | "B">) {
210 const root = NodeFS.realpathSync(
211 NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-check-changed-")),
212 );
213 const commits: Record<string, string> = {};
214 try {
215 const write = (file: string, content: string) => {
216 const path = NodePath.join(root, file);
217 NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true });
218 NodeFS.writeFileSync(path, content);
219 };
220 const git = (...args: Array<string>) =>
221 NodeChildProcess.execFileSync("git", args, { cwd: root, encoding: "utf8", env }).trim();
222 git("init");
223 for (const name of ["A", "B", "C"]) {
224 write(`${name}.txt`, name);
225 git("add", ".");
226 git("commit", "-m", name);
227 commits[name] = git("rev-parse", "HEAD");
228 }
229 for (const [remote, commit] of Object.entries(remotes)) {
230 git("remote", "add", remote, NodePath.join(root, "missing"));
231 git("update-ref", `refs/remotes/${remote}/main`, commits[commit]!);
232 }
233 } catch (error) {
234 NodeFS.rmSync(root, { recursive: true, force: true });
235 throw error;
236 }
237 return {
238 commits,
239 root,
240 [Symbol.dispose]() {
241 NodeFS.rmSync(root, { recursive: true, force: true });
242 },
243 };
245​
246const compare = (root: string, ref: Option.Option<string>) =>
247 Effect.gen(function* () {
248 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
249 return yield* comparisonBase(root, ref).pipe(
250 Effect.provideService(
251 ChildProcessSpawner.ChildProcessSpawner,
252 ChildProcessSpawner.make((command) => spawner.spawn(ChildProcess.setEnv(command, env))),
253 ),
254 );
255 }).pipe(Effect.provide(NodeServices.layer), Effect.runPromise);
256​
257it.each(["upstream", "team/upstream"])(
258 "compares against %s/main when the fork's origin/main lags it",
259 async (remote) => {
260 using project = fixture({ origin: "A", [remote]: "B" });
261 const result = await compare(project.root, Option.none());
262 assert.strictEqual(result.base, project.commits.B);
263 assert.strictEqual(result.ref, remote + "/main");
264 },
265);
266​
267it("compares against an explicit ref instead of the closest remote main", async () => {
268 using project = fixture({ origin: "A", upstream: "B" });
269 const result = await compare(project.root, Option.some("origin/main"));
270 assert.strictEqual(result.base, project.commits.A);
271 assert.strictEqual(result.ref, "origin/main");
272});