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

check-changed.test.ts

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