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

githubStackActions.test.ts

432 lines14.5 KB

1import { expect, it } from "@effect/vitest";
2import * as Layer from "effect/Layer";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as Schema from "effect/Schema";
6import * as TestClock from "effect/testing/TestClock";
7import * as FileSystem from "effect/FileSystem";
8import * as Redacted from "effect/Redacted";
9import { HttpClient, HttpClientResponse } from "effect/http";
10import { ChildProcessSpawner } from "effect/process";
11import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
12import * as GitHubRest from "./GitHubRest.ts";
13import * as GitHubCredentials from "./GitHubCredentials.ts";
14import * as GitHubQuota from "./GitHubQuota.ts";
15import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
16import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
17import { runGitHubStackAction as runStackAction } from "./githubStackActions.ts";
18​
19/**
20 * One request as the fake saw it, flattened to words: the path or document, then each variable
21 * or body field as `name=value`, so an assertion reads as "this request carried that value".
22 * A batched GraphQL request is one call, its variables carrying their alias prefixes.
23 */
24type Call = ReadonlyArray<string>;
25/** The next answer in the script: a REST body, or for GraphQL the `data` to answer with. */
26type Send = (call: Call, kind: "graphql" | "rest") => Effect.Effect<unknown>;
27​
28let gitCalls: Array<ReadonlyArray<string>> = [];
29const fakeGit = Layer.mergeAll(
30 TestSourceControlHost.layer({
31 process: {
32 run: (input) =>
33 Effect.sync(() => {
34 gitCalls.push(input.args);
35 const stdout =
36 input.args[0] === "rev-parse" || input.args[0] === "merge-base" ? "new-sha\n" : "";
37 return {
38 exitCode: ChildProcessSpawner.ExitCode(0),
39 stdout,
40 stderr: "",
41 stdoutTruncated: false,
42 stderrTruncated: false,
43 };
44 }),
45 },
46 }),
47 FileSystem.layerNoop({ makeTempDirectoryScoped: () => Effect.succeed("/tmp/scratch") }),
48);
49​
50/** GitHub's GraphQL endpoint, answering each request with the next scripted `data`. */
51const graphQlHttp = (send: Send) =>
52 HttpClient.make((request) =>
53 Effect.gen(function* () {
54 const sent =
55 request.body._tag === "Uint8Array"
56 ? (JSON.parse(new TextDecoder().decode(request.body.body)) as {
57 readonly query: string;
58 readonly variables: Readonly<Record<string, unknown>>;
59 })
60 : { query: "", variables: {} };
61 const data = yield* send(words(sent.query, sent.variables), "graphql");
62 return HttpClientResponse.fromWeb(
63 request,
64 new Response(encodeJson({ data }), { headers: { "content-type": "application/json" } }),
65 );
66 }),
67 );
68​
69const runGitHubStackAction = (send: Send, input: Parameters<typeof runStackAction>[0]) =>
70 runStackAction(input).pipe(
71 Effect.provide(
72 Layer.mergeAll(
73 fakeGit,
74 Layer.mock(GitHubRest.GitHubRest)({
75 credential: () => Effect.succeed({ token: Redacted.make("token"), fingerprint: "fp" }),
76 rest: (request) =>
77 send(words(request.path, request.body), "rest").pipe(
78 Effect.map((body) => ({
79 status: 200,
80 headers: {},
81 body: encodeJson(body),
82 truncated: false,
83 invalidUtf8: false,
84 })),
85 ),
86 }),
87 GitHubRequestPolicy.layer.pipe(
88 Layer.provide(
89 Layer.mergeAll(
90 Layer.succeed(GitHubCredentials.GitHubCredentials, {
91 get: (host) =>
92 Effect.succeed({
93 host,
94 token: Redacted.make("token"),
95 source: "gh" as const,
96 fingerprint: "fp",
97 }),
98 invalidate: () => Effect.void,
99 }),
100 GitHubQuota.layer,
101 SourceControlRateLimit.layer,
102 ),
103 ),
104 ),
105 Layer.succeed(HttpClient.HttpClient, graphQlHttp(send)),
106 ),
107 ),
108 );
109​
110const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
111​
112function words(head: string, fields: unknown): Call {
113 return [
114 head,
115 ...Object.entries((fields ?? {}) as Record<string, unknown>).map(
116 ([key, value]) => `${key}=${typeof value === "string" ? value : encodeJson(value)}`,
117 ),
118 ];
120​
121const isMutation = (call: Call) => call[0]!.startsWith("mutation");
122​
123const stack = [
124 {
125 number: 50,
126 url: "https://api.github.com/repos/acme/web/stacks/50",
127 base: { ref: "main" },
128 pull_requests: [
129 {
130 number: 1,
131 title: "Base",
132 head: { ref: "base", sha: "aaa" },
133 state: "closed",
134 merged_at: "2026-01-01T00:00:00Z",
135 },
136 {
137 number: 2,
138 title: "Middle",
139 head: { ref: "middle", sha: "bbb" },
140 state: "open",
141 draft: false,
142 },
143 { number: 3, title: "Top", head: { ref: "top", sha: "ccc" }, state: "open", draft: false },
144 ],
145 },
146];
147const input = {
148 cwd: "/repo",
149 repository: "acme/web",
150 host: "github.com",
151 number: 3,
152 stackNumber: 50,
153 expectedStackHeads: [
154 { number: 2, headSha: "bbb" },
155 { number: 3, headSha: "ccc" },
156 ],
157 action: "merge" as const,
158};
159const writable = { headRepository: { viewerPermission: "WRITE" }, maintainerCanModify: false };
160/** One batched branch-access answer: each open layer's pull request, in stack order. */
161const accessOf = (...pullRequests: ReadonlyArray<unknown>) =>
162 Object.fromEntries(
163 pullRequests.map((pullRequest, index) => [`_${index}_repository`, { pullRequest }]),
164 );
165const access = accessOf(writable, writable);
166​
167const branch = (number: number, headRefOid: string, behindBy = 1, processed: string[] = []) => ({
168 data: {
169 processed: processed.map((headRefOid) => ({ headRefOid })),
170 repository: {
171 pullRequest: { id: `PR_${number}`, headRefOid, baseRef: { compare: { behindBy } } },
172 },
173 },
174});
175const rebased = {
176 data: { updatePullRequestBranch: { pullRequest: { headRefOid: "rebased-sha" } } },
177};
178const rebaseResponses = [branch(2, "bbb"), rebased, branch(3, "ccc", 1, ["rebased-sha"]), rebased];
179​
180function fake(responses: readonly unknown[]) {
181 const calls: Call[] = [];
182 const execute: Send = (call) =>
183 Effect.sync(() => {
184 calls.push(call);
185 const value = responses[calls.length - 1];
186 if (value === undefined) throw new Error("Unexpected GitHub request");
187 return value;
188 });
189 return { execute, calls };
191​
192it.effect("submits one atomic merge with the reviewed head and respects the merge queue", () =>
193 Effect.gen(function* () {
194 const api = fake([stack, { status: "enqueued", details: {} }]);
195 yield* runGitHubStackAction(api.execute, { ...input, mergeMethod: "squash" });
196 expect(api.calls).toHaveLength(2);
197 expect(api.calls[1]).toContain("repos/acme/web/pulls/3/merge-async");
198 expect(api.calls[1]).toContain("sha=ccc");
199 expect(api.calls[1]).toContain("merge_action=default");
200 expect(api.calls[1]).toContain("merge_method=squash");
201 }),
202);
203​
204it.effect("merges through the selected layer without including later draft layers", () =>
205 Effect.gen(function* () {
206 const fiveLayers = [
207 {
208 ...stack[0],
209 pull_requests: Array.from({ length: 5 }, (_, index) => ({
210 number: index + 1,
211 head: { ref: `layer-${index + 1}`, sha: `sha-${index + 1}` },
212 state: "open",
213 draft: index >= 3,
214 })),
215 },
216 ];
217 const api = fake([fiveLayers, { status: "merged", details: {} }]);
218 yield* runGitHubStackAction(api.execute, {
219 ...input,
220 number: 3,
221 expectedStackHeads: [1, 2, 3].map((number) => ({ number, headSha: `sha-${number}` })),
222 });
223 expect(api.calls).toHaveLength(2);
224 expect(api.calls[1]).toContain("repos/acme/web/pulls/3/merge-async");
225 expect(api.calls[1]).toContain("sha=sha-3");
226 expect(api.calls[1]).toContain("merge_action=default");
227 }),
228);
229​
230it.effect("rejects stale reviewed heads below a selected middle layer", () =>
231 Effect.gen(function* () {
232 const api = fake([stack]);
233 const result = yield* runGitHubStackAction(api.execute, {
234 ...input,
235 number: 2,
236 expectedStackHeads: [{ number: 2, headSha: "old-head" }],
237 }).pipe(Effect.result);
238 expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: "GitHubStackChangedError" } });
239 expect(api.calls).toHaveLength(1);
240 }),
241);
242​
243it.effect("does not merge from an already merged layer", () =>
244 Effect.gen(function* () {
245 const api = fake([stack]);
246 const result = yield* runGitHubStackAction(api.execute, {
247 ...input,
248 number: 1,
249 expectedStackHeads: [],
250 }).pipe(Effect.result);
251 expect(result).toMatchObject({
252 _tag: "Failure",
253 failure: { _tag: "GitHubStackUnsupportedError" },
254 });
255 expect(api.calls).toHaveLength(1);
256 }),
257);
258​
259it.effect("polls an accepted merge and reports a later rule rejection", () =>
260 Effect.gen(function* () {
261 const api = fake([
262 stack,
263 { status: "pending", details: { uuid: "operation" } },
264 { status: "failed", details: { message: "Required checks have not passed" } },
265 ]);
266 const fiber = yield* runGitHubStackAction(api.execute, input).pipe(
267 Effect.result,
268 Effect.forkChild,
269 );
270 yield* TestClock.adjust("1 second");
271 const result = yield* Fiber.join(fiber);
272 expect(result).toMatchObject({
273 _tag: "Failure",
274 failure: { _tag: "GitHubStackMergeRejectedError" },
275 });
276 expect(api.calls[2]).toContain("repos/acme/web/pulls/3/merge-async/operation");
277 }),
278);
279​
280it.effect("retains stack identity and a rejection response without a message", () =>
281 Effect.gen(function* () {
282 const rejection = { status: "failed", details: {} };
283 const api = fake([stack, rejection]);
284 const result = yield* runGitHubStackAction(api.execute, input).pipe(Effect.result);
285 expect(result).toMatchObject({
286 _tag: "Failure",
287 failure: {
288 _tag: "GitHubStackMergeRejectedError",
289 repository: input.repository,
290 number: input.number,
291 stackNumber: input.stackNumber,
292 cause: rejection,
293 },
294 });
295 }),
296);
297​
298it.effect("refuses a changed stack before performing any mutation", () =>
299 Effect.gen(function* () {
300 const api = fake([stack]);
301 const result = yield* runGitHubStackAction(api.execute, {
302 ...input,
303 expectedStackHeads: [
304 { number: 2, headSha: "old" },
305 { number: 3, headSha: "ccc" },
306 ],
307 }).pipe(Effect.result);
308 expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: "GitHubStackChangedError" } });
309 expect(api.calls).toHaveLength(1);
310 }),
311);
312​
313it.effect("refuses the entire rebase before mutation when a later fork denies write access", () =>
314 Effect.gen(function* () {
315 const api = fake([
316 stack,
317 accessOf(writable, {
318 headRepository: { viewerPermission: "READ" },
319 maintainerCanModify: false,
320 }),
321 ]);
322 const result = yield* runGitHubStackAction(api.execute, {
323 ...input,
324 action: "update-branch",
325 }).pipe(Effect.result);
326 expect(result).toMatchObject({
327 _tag: "Failure",
328 failure: { _tag: "GitHubStackPermissionError" },
329 });
330 expect(api.calls).toHaveLength(2);
331 }),
332);
333​
334it.effect("allows a fork that explicitly permits maintainer updates", () =>
335 Effect.gen(function* () {
336 const api = fake([
337 stack,
338 accessOf(writable, {
339 headRepository: { viewerPermission: "READ" },
340 maintainerCanModify: true,
341 }),
342 ...rebaseResponses,
343 ]);
344 yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
345 expect(gitCalls.filter((args) => args[0] === "push")).toHaveLength(2);
346 }),
347);
348​
349it.effect("rebases for a GitHub App, which GitHub gives no permission to read", () =>
350 Effect.gen(function* () {
351 gitCalls = [];
352 const api = fake([
353 stack,
354 accessOf(
355 { headRepository: { viewerPermission: null }, maintainerCanModify: false },
356 { headRepository: { viewerPermission: null }, maintainerCanModify: false },
357 ),
358 ...rebaseResponses,
359 ]);
360 yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
361 expect(gitCalls.filter((args) => args[0] === "push")).toHaveLength(2);
362 }),
363);
364​
365it.effect("bounds polling and reports a still-running merge without claiming success", () =>
366 Effect.gen(function* () {
367 const api = fake([
368 stack,
369 ...Array.from({ length: 40 }, () => ({ status: "pending", details: { uuid: "operation" } })),
370 ]);
371 const fiber = yield* runGitHubStackAction(api.execute, input).pipe(
372 Effect.result,
373 Effect.forkChild,
374 );
375 yield* TestClock.adjust("6 minutes");
376 expect(yield* Fiber.join(fiber)).toMatchObject({
377 _tag: "Failure",
378 failure: { _tag: "GitHubStackMergePendingError" },
379 });
380 expect(api.calls.length).toBeLessThan(40);
381 }),
382);
383​
384it.effect("rebases the open layers bottom to top in a scratch clone, each onto the one below", () =>
385 Effect.gen(function* () {
386 gitCalls = [];
387 const api = fake([stack, access]);
388 yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
389 // Both layers' access is one aliased read, layer by layer in stack order.
390 expect(api.calls[1]).toEqual(
391 expect.arrayContaining(["_0_number=2", "_1_number=3", "_0_owner=acme", "_0_name=web"]),
392 );
393 // GitHub is only read; every change is a git push with a lease on the reviewed head.
394 expect(api.calls.some(isMutation)).toBe(false);
395 const rebases = gitCalls.filter((args) => args[0] === "rebase");
396 expect(rebases).toEqual([
397 ["rebase", "--quiet", "--onto", "origin/main", "new-sha"],
398 ["rebase", "--quiet", "--onto", "new-sha", "bbb"],
399 ]);
400 expect(gitCalls.filter((args) => args[0] === "push")).toEqual([
401 [
402 "push",
403 "--quiet",
404 "--force-with-lease=refs/heads/middle:bbb",
405 "origin",
406 "new-sha:refs/heads/middle",
407 ],
408 [
409 "push",
410 "--quiet",
411 "--force-with-lease=refs/heads/top:ccc",
412 "origin",
413 "new-sha:refs/heads/top",
414 ],
415 ]);
416 }),
417);
418​
419it.effect("checks every layer's write access before any git runs", () =>
420 Effect.gen(function* () {
421 gitCalls = [];
422 const api = fake([
423 stack,
424 accessOf(writable, {
425 headRepository: { viewerPermission: "READ" },
426 maintainerCanModify: false,
427 }),
428 ]);
429 yield* Effect.flip(runGitHubStackAction(api.execute, { ...input, action: "update-branch" }));
430 expect(gitCalls).toEqual([]);
431 }),
432);