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