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

githubStackActions.test.ts

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