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

githubStackActions.test.ts

439 lines14.1 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 GitHubApi from "../sourceControl/GitHubApi.ts";
8import { runGitHubStackAction as runStackAction } from "./githubStackActions.ts";
9​
10/**
11 * One request as the fake saw it, flattened to words: the path or document, then each variable
12 * or body field as `name=value`, so an assertion reads as "this request carried that value".
13 */
14type Call = ReadonlyArray<string>;
15type Send = (
16 call: Call,
17 kind: "graphql" | "rest",
18) => Effect.Effect<string, GitHubApi.GitHubApiError>;
19​
20const runGitHubStackAction = (send: Send, input: Parameters<typeof runStackAction>[0]) =>
21 runStackAction(input).pipe(
22 Effect.provide(
23 Layer.mock(GitHubApi.GitHubApi)({
24 graphql: (request) => {
25 // GitHub refuses a document that declares a variable it never uses.
26 const declared = [...request.query.matchAll(/\$(\w+)\s*:/g)].map((match) => match[1]!);
27 const unused = declared.filter(
28 (name) => !new RegExp(`\\$${name}(?!\\w)(?!\\s*:)`).test(request.query),
29 );
30 if (unused.length > 0) {
31 return Effect.die(new Error(`Variables declared but not used: ${unused.join(", ")}`));
32 }
33 return send(words(request.query, request.variables), "graphql");
34 },
35 rest: (request) =>
36 send(words(request.path, request.body), "rest").pipe(
37 Effect.map((body) => ({
38 status: 200,
39 headers: {},
40 body,
41 truncated: false,
42 invalidUtf8: false,
43 })),
44 ),
45 }),
46 ),
47 );
48​
49const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
50​
51function words(head: string, fields: unknown): Call {
52 return [
53 head,
54 ...Object.entries((fields ?? {}) as Record<string, unknown>).map(
55 ([key, value]) => `${key}=${typeof value === "string" ? value : encodeJson(value)}`,
56 ),
57 ];
59​
60const isMutation = (call: Call) => call[0]!.startsWith("mutation");
61​
62const stack = [
63 {
64 number: 50,
65 url: "https://api.github.com/repos/acme/web/stacks/50",
66 base: { ref: "main" },
67 pull_requests: [
68 {
69 number: 1,
70 title: "Base",
71 head: { ref: "base", sha: "aaa" },
72 state: "closed",
73 merged_at: "2026-01-01T00:00:00Z",
74 },
75 {
76 number: 2,
77 title: "Middle",
78 head: { ref: "middle", sha: "bbb" },
79 state: "open",
80 draft: false,
81 },
82 { number: 3, title: "Top", head: { ref: "top", sha: "ccc" }, state: "open", draft: false },
83 ],
84 },
85];
86const input = {
87 cwd: "/repo",
88 repository: "acme/web",
89 host: "github.com",
90 number: 3,
91 stackNumber: 50,
92 expectedStackHeads: [
93 { number: 2, headSha: "bbb" },
94 { number: 3, headSha: "ccc" },
95 ],
96 action: "merge" as const,
97};
98const access = {
99 data: {
100 repository: {
101 pr2: { headRepository: { viewerPermission: "WRITE" }, maintainerCanModify: false },
102 pr3: { headRepository: { viewerPermission: "WRITE" }, maintainerCanModify: false },
103 },
104 },
105};
106​
107const branch = (number: number, headRefOid: string, behindBy = 1, processed: string[] = []) => ({
108 data: {
109 processed: processed.map((headRefOid) => ({ headRefOid })),
110 repository: {
111 pullRequest: { id: `PR_${number}`, headRefOid, baseRef: { compare: { behindBy } } },
112 },
113 },
114});
115const rebased = {
116 data: { updatePullRequestBranch: { pullRequest: { headRefOid: "rebased-sha" } } },
117};
118const rebaseResponses = [branch(2, "bbb"), rebased, branch(3, "ccc", 1, ["rebased-sha"]), rebased];
119​
120function fake(responses: readonly unknown[]) {
121 const calls: Call[] = [];
122 const execute: Send = (call) =>
123 Effect.sync(() => {
124 calls.push(call);
125 const value = responses[calls.length - 1];
126 if (value === undefined) throw new Error("Unexpected GitHub request");
127 return encodeJson(value);
128 });
129 return { execute, calls };
131​
132it.effect("submits one atomic merge with the reviewed head and respects the merge queue", () =>
133 Effect.gen(function* () {
134 const api = fake([stack, { status: "enqueued", details: {} }]);
135 yield* runGitHubStackAction(api.execute, { ...input, mergeMethod: "squash" });
136 expect(api.calls).toHaveLength(2);
137 expect(api.calls[1]).toContain("repos/acme/web/pulls/3/merge-async");
138 expect(api.calls[1]).toContain("sha=ccc");
139 expect(api.calls[1]).toContain("merge_action=default");
140 expect(api.calls[1]).toContain("merge_method=squash");
141 }),
142);
143​
144it.effect("merges through the selected layer without including later draft layers", () =>
145 Effect.gen(function* () {
146 const fiveLayers = [
147 {
148 ...stack[0],
149 pull_requests: Array.from({ length: 5 }, (_, index) => ({
150 number: index + 1,
151 head: { ref: `layer-${index + 1}`, sha: `sha-${index + 1}` },
152 state: "open",
153 draft: index >= 3,
154 })),
155 },
156 ];
157 const api = fake([fiveLayers, { status: "merged", details: {} }]);
158 yield* runGitHubStackAction(api.execute, {
159 ...input,
160 number: 3,
161 expectedStackHeads: [1, 2, 3].map((number) => ({ number, headSha: `sha-${number}` })),
162 });
163 expect(api.calls).toHaveLength(2);
164 expect(api.calls[1]).toContain("repos/acme/web/pulls/3/merge-async");
165 expect(api.calls[1]).toContain("sha=sha-3");
166 expect(api.calls[1]).toContain("merge_action=default");
167 }),
168);
169​
170it.effect("rejects stale reviewed heads below a selected middle layer", () =>
171 Effect.gen(function* () {
172 const api = fake([stack]);
173 const result = yield* runGitHubStackAction(api.execute, {
174 ...input,
175 number: 2,
176 expectedStackHeads: [{ number: 2, headSha: "old-head" }],
177 }).pipe(Effect.result);
178 expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: "GitHubStackChangedError" } });
179 expect(api.calls).toHaveLength(1);
180 }),
181);
182​
183it.effect("does not merge from an already merged layer", () =>
184 Effect.gen(function* () {
185 const api = fake([stack]);
186 const result = yield* runGitHubStackAction(api.execute, {
187 ...input,
188 number: 1,
189 expectedStackHeads: [],
190 }).pipe(Effect.result);
191 expect(result).toMatchObject({
192 _tag: "Failure",
193 failure: { _tag: "GitHubStackUnsupportedError" },
194 });
195 expect(api.calls).toHaveLength(1);
196 }),
197);
198​
199it.effect("polls an accepted merge and reports a later rule rejection", () =>
200 Effect.gen(function* () {
201 const api = fake([
202 stack,
203 { status: "pending", details: { uuid: "operation" } },
204 { status: "failed", details: { message: "Required checks have not passed" } },
205 ]);
206 const fiber = yield* runGitHubStackAction(api.execute, input).pipe(
207 Effect.result,
208 Effect.forkChild,
209 );
210 yield* TestClock.adjust("1 second");
211 const result = yield* Fiber.join(fiber);
212 expect(result).toMatchObject({
213 _tag: "Failure",
214 failure: { _tag: "GitHubStackMergeRejectedError" },
215 });
216 expect(api.calls[2]).toContain("repos/acme/web/pulls/3/merge-async/operation");
217 }),
218);
219​
220it.effect("retains stack identity and a rejection response without a message", () =>
221 Effect.gen(function* () {
222 const rejection = { status: "failed", details: {} };
223 const api = fake([stack, rejection]);
224 const result = yield* runGitHubStackAction(api.execute, input).pipe(Effect.result);
225 expect(result).toMatchObject({
226 _tag: "Failure",
227 failure: {
228 _tag: "GitHubStackMergeRejectedError",
229 repository: input.repository,
230 number: input.number,
231 stackNumber: input.stackNumber,
232 cause: rejection,
233 },
234 });
235 }),
236);
237​
238it.effect("refuses a changed stack before performing any mutation", () =>
239 Effect.gen(function* () {
240 const api = fake([stack]);
241 const result = yield* runGitHubStackAction(api.execute, {
242 ...input,
243 expectedStackHeads: [
244 { number: 2, headSha: "old" },
245 { number: 3, headSha: "ccc" },
246 ],
247 }).pipe(Effect.result);
248 expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: "GitHubStackChangedError" } });
249 expect(api.calls).toHaveLength(1);
250 }),
251);
252​
253it.effect("rebases unmerged layers bottom to top without local git commands", () =>
254 Effect.gen(function* () {
255 const api = fake([stack, access, ...rebaseResponses]);
256 yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
257 const mutations = api.calls.filter(isMutation);
258 expect(mutations).toHaveLength(2);
259 expect(mutations[0]).toContain("id=PR_2");
260 expect(mutations[0]).toContain("sha=bbb");
261 expect(mutations[1]).toContain("id=PR_3");
262 expect(mutations[1]).toContain("sha=ccc");
263 }),
264);
265​
266it.effect("does not update later layers after a rebase failure", () =>
267 Effect.gen(function* () {
268 const api = fake([stack, access, branch(2, "bbb")]);
269 const execute: Send = (call, kind) =>
270 !isMutation(call)
271 ? api.execute(call, kind)
272 : Effect.fail(
273 new GitHubApi.GitHubApiAuthenticationError({
274 host: "github.com",
275 operation: "runGitHubStackAction",
276 }),
277 );
278 const result = yield* runGitHubStackAction(execute, { ...input, action: "update-branch" }).pipe(
279 Effect.result,
280 );
281 expect(result).toMatchObject({
282 _tag: "Failure",
283 failure: { _tag: "GitHubStackRebaseFailedError", number: 2, completed: 0 },
284 });
285 }),
286);
287​
288it.effect("refuses the entire rebase before mutation when a later fork denies write access", () =>
289 Effect.gen(function* () {
290 const api = fake([
291 stack,
292 {
293 data: {
294 repository: {
295 ...access.data.repository,
296 pr3: { headRepository: { viewerPermission: "READ" }, maintainerCanModify: false },
297 },
298 },
299 },
300 ]);
301 const result = yield* runGitHubStackAction(api.execute, {
302 ...input,
303 action: "update-branch",
304 }).pipe(Effect.result);
305 expect(result).toMatchObject({
306 _tag: "Failure",
307 failure: { _tag: "GitHubStackPermissionError" },
308 });
309 expect(api.calls).toHaveLength(2);
310 }),
311);
312​
313it.effect("allows a fork that explicitly permits maintainer updates", () =>
314 Effect.gen(function* () {
315 const api = fake([
316 stack,
317 {
318 data: {
319 repository: {
320 ...access.data.repository,
321 pr3: { headRepository: { viewerPermission: "READ" }, maintainerCanModify: true },
322 },
323 },
324 },
325 ...rebaseResponses,
326 ]);
327 yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
328 expect(api.calls.at(-1)).toContain("id=PR_3");
329 }),
330);
331​
332it.effect("bounds polling and reports a still-running merge without claiming success", () =>
333 Effect.gen(function* () {
334 const api = fake([
335 stack,
336 ...Array.from({ length: 40 }, () => ({ status: "pending", details: { uuid: "operation" } })),
337 ]);
338 const fiber = yield* runGitHubStackAction(api.execute, input).pipe(
339 Effect.result,
340 Effect.forkChild,
341 );
342 yield* TestClock.adjust("6 minutes");
343 expect(yield* Fiber.join(fiber)).toMatchObject({
344 _tag: "Failure",
345 failure: { _tag: "GitHubStackMergePendingError" },
346 });
347 expect(api.calls.length).toBeLessThan(40);
348 }),
349);
350​
351it.effect("rejects a push after preflight without rebasing the new revision", () =>
352 Effect.gen(function* () {
353 const api = fake([stack, access, branch(2, "new-head")]);
354 const result = yield* runGitHubStackAction(api.execute, {
355 ...input,
356 action: "update-branch",
357 }).pipe(Effect.result);
358 expect(result).toMatchObject({
359 _tag: "Failure",
360 failure: { _tag: "GitHubStackChangedError", number: 2, completed: 0 },
361 });
362 expect(api.calls).toHaveLength(3);
363 }),
364);
365​
366it.effect("skips current layers without submitting a rebase mutation", () =>
367 Effect.gen(function* () {
368 const api = fake([stack, access, branch(2, "bbb", 0), branch(3, "ccc", 0, ["bbb"])]);
369 yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
370 expect(api.calls.some((args) => isMutation(args))).toBe(false);
371 }),
372);
373​
374it.effect("keeps earlier progress and stops after a later layer fails", () =>
375 Effect.gen(function* () {
376 const api = fake([
377 stack,
378 access,
379 branch(2, "bbb"),
380 rebased,
381 branch(3, "ccc", 1, ["rebased-sha"]),
382 { data: { updatePullRequestBranch: null } },
383 ]);
384 const result = yield* runGitHubStackAction(api.execute, {
385 ...input,
386 action: "update-branch",
387 }).pipe(Effect.result);
388 expect(result).toMatchObject({
389 _tag: "Failure",
390 failure: { _tag: "GitHubStackRebaseFailedError", number: 3, completed: 1 },
391 });
392 }),
393);
394​
395it.effect("reports partial progress when a later head changes during the rebase", () =>
396 Effect.gen(function* () {
397 const api = fake([
398 stack,
399 access,
400 branch(2, "bbb"),
401 rebased,
402 branch(3, "concurrent-head", 1, ["rebased-sha"]),
403 ]);
404 const result = yield* runGitHubStackAction(api.execute, {
405 ...input,
406 action: "update-branch",
407 }).pipe(Effect.result);
408 expect(result).toMatchObject({
409 _tag: "Failure",
410 failure: { _tag: "GitHubStackChangedError", number: 3, completed: 1 },
411 });
412 if (result._tag === "Failure") {
413 expect(result.failure.message).toContain("Earlier updates remain on GitHub");
414 }
415 expect(api.calls.filter((args) => isMutation(args))).toHaveLength(1);
416 }),
417);
418​
419it.effect.each([false, true])("rejects a push to a processed layer, rebased=%s", (rebasedParent) =>
420 Effect.gen(function* () {
421 const api = fake([
422 stack,
423 access,
424 branch(2, "bbb", rebasedParent ? 1 : 0),
425 ...(rebasedParent ? [rebased] : []),
426 branch(3, "ccc", 1, ["concurrent-parent-head"]),
427 ]);
428 const result = yield* runGitHubStackAction(api.execute, {
429 ...input,
430 action: "update-branch",
431 }).pipe(Effect.result);
432 expect(result).toMatchObject({
433 _tag: "Failure",
434 failure: { _tag: "GitHubStackChangedError", number: 2, completed: 1 },
435 });
436 expect(api.calls.at(-1)?.includes('ids=["PR_2"]')).toBe(true);
437 expect(api.calls.filter((args) => isMutation(args))).toHaveLength(rebasedParent ? 1 : 0);
438 }),
439);