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