@niwa-labs/forge 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,239 @@
1
+ // The script helpers, over the globals a workflow script is given: what they call, what they wait
2
+ // for, and what they answer.
3
+
4
+ import { afterEach, expect, test } from "bun:test";
5
+
6
+ import { resolveQuery } from "@niwa-labs/core";
7
+
8
+ import { forgePipelineRead, forgePrMerge, forgePrRead } from "../src/actions.ts";
9
+ import { durationMs, land, untilHeadMoved, untilPipeline, untilPrEnded } from "../src/flow.ts";
10
+ import { sha } from "./fake-gitlab.ts";
11
+
12
+ const repo = { host: "gitlab.example.com", path: "acme/billing" };
13
+ const head = sha("topic-1");
14
+
15
+ interface Seen {
16
+ calls: Array<{ name: string; input: any; label?: string }>;
17
+ waits: Array<{ type: string; filter: unknown; opts: any }>;
18
+ }
19
+
20
+ const globals = globalThis as Record<string, unknown>;
21
+ afterEach(() => {
22
+ for (const name of ["call", "wait", "now", "race"]) delete globals[name];
23
+ });
24
+
25
+ /** Script globals over answers the test gives: each call and wait takes the next of its list. */
26
+ function scriptWith(answers: { calls: Record<string, any[]>; waits?: Record<string, any[]>; clock?: number[] }): Seen {
27
+ const seen: Seen = { calls: [], waits: [] };
28
+ const clock = [...(answers.clock ?? [])];
29
+ globals.call = async (name: string, input: unknown, opts?: { label?: string }) => {
30
+ seen.calls.push({ name, input, ...(opts?.label === undefined ? {} : { label: opts.label }) });
31
+ // The host holds a call to the schema of its action: so does the script.
32
+ const refs = { [forgePipelineRead.name]: forgePipelineRead, [forgePrMerge.name]: forgePrMerge, [forgePrRead.name]: forgePrRead };
33
+ refs[name]?.input.parse(input);
34
+ const next = answers.calls[name]?.shift();
35
+ if (next === undefined) throw new Error(`no answer for ${name}`);
36
+ return next;
37
+ };
38
+ // A script waits for a query a builder gave, of one type: the host holds it to the catalogue.
39
+ globals.wait = async (query: Parameters<typeof resolveQuery>[0], opts: unknown) => {
40
+ const resolved = resolveQuery(query);
41
+ const [type] = resolved.types ?? [];
42
+ if (resolved.types?.length !== 1 || type === undefined) throw new Error("a wait names one type");
43
+ seen.waits.push({ type, filter: resolved.filter, opts });
44
+ const next = answers.waits?.[type]?.shift();
45
+ return next ?? new Promise(() => {});
46
+ };
47
+ globals.now = async () => clock.shift() ?? 0;
48
+ globals.race = async (_name: string, branches: Record<string, () => Promise<unknown>>) =>
49
+ await Promise.race(Object.entries(branches).map(async ([key, run]) => ({ key, value: await run() })));
50
+ return seen;
51
+ }
52
+
53
+ const pipeline = (id: number, state: string, kind = "head") => ({ repo: { ...repo, projectId: 42 }, pipeline: id, kind, ref: "main", sourceSha: head, state });
54
+
55
+ test("a pipeline that already settled answers at once", async () => {
56
+ const seen = scriptWith({ calls: { "forge.pipeline.read": [{ items: [pipeline(5, "success"), pipeline(4, "failed")] }] }, clock: [0] });
57
+ expect(await untilPipeline("ci", { repo, sha: head, deadline: "40m" })).toEqual({ outcome: "green", pipeline: 5 });
58
+ expect(seen.waits).toEqual([]);
59
+ });
60
+
61
+ test("a running pipeline is waited for by its commit, and read again when a record of it arrives", async () => {
62
+ const seen = scriptWith({
63
+ calls: { "forge.pipeline.read": [{ items: [pipeline(5, "running", "merge-result")] }, { items: [pipeline(5, "failed", "merge-result")] }] },
64
+ waits: { "forge.pipeline": [{ data: {}, at: 77 }] },
65
+ clock: [0, 1_000],
66
+ });
67
+ expect(await untilPipeline("ci", { repo, sha: head, kind: "merge-result", deadline: "40m" })).toEqual({ outcome: "red", pipeline: 5 });
68
+ expect(seen.calls.map((one) => [one.input.kind, one.label])).toEqual([
69
+ ["merge-result", "ci-read-1"],
70
+ ["merge-result", "ci-read-2"],
71
+ ]);
72
+ expect(seen.waits[0]).toMatchObject({
73
+ type: "forge.pipeline",
74
+ filter: { "repo.host": repo.host, "repo.path": repo.path, sourceSha: head, kind: "merge-result" },
75
+ opts: { timeout: 300_000, label: "ci-wait-1" },
76
+ });
77
+ });
78
+
79
+ test("a pipeline still running at the deadline times out", async () => {
80
+ scriptWith({
81
+ calls: { "forge.pipeline.read": [{ items: [] }, { items: [pipeline(5, "running")] }] },
82
+ waits: { "forge.pipeline": [{ timedOut: true }] },
83
+ clock: [0, 1_000, 2_400_000],
84
+ });
85
+ expect(await untilPipeline("ci", { repo, sha: head, deadline: "40m" })).toEqual({ outcome: "timed-out" });
86
+ });
87
+
88
+ test("landing at once answers the commit the merge made, and a refusal says why", async () => {
89
+ const seen = scriptWith({
90
+ calls: { "forge.pr.merge": [{ outcome: "merged", sha: sha("m"), externalId: "x" }, { outcome: "refused", why: "SHA does not match" }] },
91
+ });
92
+ expect(await land("land", { pr: { repo, number: 7 }, expectHead: head, method: "squash" })).toEqual({ outcome: "merged", sha: sha("m") });
93
+ expect(seen.calls[0]).toEqual({ name: "forge.pr.merge", input: { repo, number: 7, expectHead: head, method: "squash", when: "now" }, label: "land-merge" });
94
+ expect(await land("again", { pr: { repo, number: 7 }, expectHead: head, method: "merge" })).toEqual({ outcome: "refused", why: "SHA does not match" });
95
+ });
96
+
97
+ const armed = { outcome: "armed", externalId: "gitlab.example.com/acme/billing!7", cancel: "forge.pr.merge.cancel" };
98
+ const read = (state: string, fields: Record<string, unknown> = {}) => ({
99
+ pr: { repo: { ...repo, projectId: 42 }, number: 7 },
100
+ state,
101
+ title: "t",
102
+ branch: "topic",
103
+ base: "main",
104
+ head,
105
+ draft: false,
106
+ autoMerge: state === "open",
107
+ ...fields,
108
+ });
109
+ const auto = { pr: { repo, number: 7 }, expectHead: head, method: "merge", auto: true } as const;
110
+
111
+ test("an automatic landing waits for the merge, and a merge at another head is not this landing", async () => {
112
+ scriptWith({ calls: { "forge.pr.merge": [armed] }, waits: { "forge.pr.merged": [{ data: { head, mergeSha: sha("m") }, at: 9 }] } });
113
+ expect(await land("land", auto)).toEqual({ outcome: "merged", sha: sha("m") });
114
+
115
+ scriptWith({ calls: { "forge.pr.merge": [armed] }, waits: { "forge.pr.merged": [{ data: { head: sha("other") }, at: 9 }] } });
116
+ expect(await land("land", auto)).toMatchObject({ outcome: "refused" });
117
+
118
+ scriptWith({ calls: { "forge.pr.merge": [armed] }, waits: { "forge.pr.merge.disarmed": [{ data: {}, at: 9 }] } });
119
+ expect(await land("land", auto)).toMatchObject({ outcome: "refused", why: expect.stringContaining("called off") });
120
+ });
121
+
122
+ test("an automatic landing still waiting at the deadline reads the pull request first and is queued-unknown", async () => {
123
+ const seen = scriptWith({
124
+ calls: { "forge.pr.merge": [armed], "forge.pr.read": [read("open")] },
125
+ waits: { "forge.pr.merged": [{ timedOut: true }] },
126
+ clock: [0, 300_000],
127
+ });
128
+ expect(await land("land", { ...auto, deadline: "5m" })).toMatchObject({ outcome: "queued-unknown" });
129
+ expect(seen.calls.filter((one) => one.name === "forge.pr.read")).toHaveLength(1);
130
+ expect(seen.waits[0]?.opts.timeout).toBe(300_000);
131
+ });
132
+
133
+ test("a merge that was recorded before the waits began, or never recorded, is found by reading the pull request", async () => {
134
+ const seen = scriptWith({
135
+ calls: { "forge.pr.merge": [armed], "forge.pr.read": [read("merged", { mergeSha: sha("m"), autoMerge: false })] },
136
+ waits: { "forge.pr.merged": [{ timedOut: true }] },
137
+ clock: [0],
138
+ });
139
+ expect(await land("land", { ...auto, deadline: "2h" })).toEqual({ outcome: "merged", sha: sha("m") });
140
+ expect(seen.waits.every((one) => one.opts.timeout === 300_000)).toBe(true);
141
+ expect(seen.calls.at(-1)).toMatchObject({ name: "forge.pr.read", input: { repo, number: 7 } });
142
+
143
+ scriptWith({
144
+ calls: { "forge.pr.merge": [armed], "forge.pr.read": [read("merged", { head: sha("other"), mergeSha: sha("m"), autoMerge: false })] },
145
+ waits: { "forge.pr.merged": [{ timedOut: true }] },
146
+ clock: [0],
147
+ });
148
+ expect(await land("land", auto)).toMatchObject({ outcome: "refused", why: expect.stringContaining("not at") });
149
+ });
150
+
151
+ test("a pull request the server no longer holds for merging is refused when the read says so, not after the deadline", async () => {
152
+ scriptWith({
153
+ calls: { "forge.pr.merge": [armed], "forge.pr.read": [read("open", { autoMerge: false })] },
154
+ waits: { "forge.pr.merged": [{ timedOut: true }] },
155
+ clock: [0],
156
+ });
157
+ expect(await land("land", auto)).toMatchObject({ outcome: "refused", why: expect.stringContaining("no longer") });
158
+
159
+ scriptWith({ calls: { "forge.pr.merge": [armed], "forge.pr.read": [read("closed", { autoMerge: false })] }, waits: { "forge.pr.merged": [{ timedOut: true }] }, clock: [0, 0] });
160
+ expect(await land("land", auto)).toMatchObject({ outcome: "refused", why: expect.stringContaining("closed") });
161
+ });
162
+
163
+ test("durations are milliseconds or a number with a unit", () => {
164
+ expect(durationMs(250)).toBe(250);
165
+ expect(durationMs("40m")).toBe(2_400_000);
166
+ expect(durationMs("2h")).toBe(7_200_000);
167
+ expect(() => durationMs("soon")).toThrow(/duration/);
168
+ });
169
+
170
+ test("a helper called outside a script says so", async () => {
171
+ await expect(untilPipeline("ci", { repo, sha: head, deadline: "1m" })).rejects.toThrow(/workflow script/);
172
+ });
173
+
174
+ test("a pipeline that waits on a manual job is still pending, as the checks of a pull request say", async () => {
175
+ scriptWith({
176
+ calls: { "forge.pipeline.read": [{ items: [pipeline(5, "manual")] }, { items: [pipeline(5, "success")] }] },
177
+ waits: { "forge.pipeline": [{ data: {}, at: 3 }] },
178
+ clock: [0, 1_000],
179
+ });
180
+ expect(await untilPipeline("ci", { repo, sha: head, deadline: "40m" })).toEqual({ outcome: "green", pipeline: 5 });
181
+ });
182
+
183
+ test("the helpers take the repository of a record, whose project id the actions do not", async () => {
184
+ const known = { ...repo, projectId: 42 };
185
+ const seen = scriptWith({
186
+ calls: {
187
+ "forge.pipeline.read": [{ items: [pipeline(5, "success")] }],
188
+ "forge.pr.merge": [{ outcome: "merged", sha: sha("m"), externalId: "x" }],
189
+ },
190
+ clock: [0],
191
+ });
192
+ expect(await untilPipeline("ci", { repo: known, sha: head, deadline: "40m" })).toEqual({ outcome: "green", pipeline: 5 });
193
+ expect(seen.calls[0]?.input.repo).toEqual(repo);
194
+ expect(await land("land", { pr: { repo: known, number: 7 }, expectHead: head, method: "merge" })).toMatchObject({ outcome: "merged" });
195
+ expect(seen.calls[1]?.input.repo).toEqual(repo);
196
+ });
197
+
198
+ test("landing waits for the merge, the close and the call-off of the pull request, each by its query", async () => {
199
+ const seen = scriptWith({ calls: { "forge.pr.merge": [armed] }, waits: { "forge.pr.merged": [{ data: { head, mergeSha: sha("m") }, at: 9 }] } });
200
+ await land("land", auto);
201
+ const filter = { "pr.repo.host": repo.host, "pr.repo.path": repo.path, "pr.number": 7 };
202
+ expect(seen.waits.map((one) => [one.type, one.filter, one.opts.label])).toEqual([
203
+ ["forge.pr.merged", filter, "land-merged-1"],
204
+ ["forge.pr.closed", filter, "land-closed-1"],
205
+ ["forge.pr.merge.disarmed", filter, "land-disarmed-1"],
206
+ ]);
207
+ });
208
+
209
+ const pr = { repo, number: 7 };
210
+
211
+ test("a script waits for the head of a pull request to move, and is told where to go on from", async () => {
212
+ const seen = scriptWith({ calls: {}, waits: { "forge.pr.head": [{ data: { head: sha("b"), previous: head }, at: 31 }, { data: { head: sha("c") }, at: 40 }, { timedOut: true }] } });
213
+ expect(await untilHeadMoved("head", { pr, from: 12, timeout: "30m" })).toEqual({ moved: true, head: sha("b"), previous: head, at: 31 });
214
+ expect(await untilHeadMoved("head-2", { pr, from: 31 })).toEqual({ moved: true, head: sha("c"), at: 40 });
215
+ expect(await untilHeadMoved("head-3", { pr, from: 40, timeout: 1000 })).toEqual({ moved: false });
216
+ expect(seen.waits.map((one) => one.opts)).toEqual([
217
+ { from: 12, timeout: "30m", label: "head" },
218
+ { from: 31, label: "head-2" },
219
+ { from: 40, timeout: 1000, label: "head-3" },
220
+ ]);
221
+ expect(seen.waits[0]?.filter).toEqual({ "pr.repo.host": repo.host, "pr.repo.path": repo.path, "pr.number": 7 });
222
+ });
223
+
224
+ test("a script waits for a pull request to be merged or closed, by the two queries, and is told how it ended", async () => {
225
+ const pr = { repo: { ...repo, projectId: 42 }, number: 7 };
226
+ const seen = scriptWith({ calls: {}, waits: { "forge.pr.closed": [{ data: { by: "marge" }, at: 12 }] } });
227
+ expect(await untilPrEnded("end", { pr, from: 5, timeout: "1h" })).toEqual({ ended: "closed", by: "marge", at: 12 });
228
+ const prFilter = { "pr.repo.host": repo.host, "pr.repo.path": repo.path, "pr.number": 7 };
229
+ expect(seen.waits).toEqual([
230
+ { type: "forge.pr.merged", filter: prFilter, opts: { from: 5, timeout: "1h", label: "end-merged" } },
231
+ { type: "forge.pr.closed", filter: prFilter, opts: { from: 5, timeout: "1h", label: "end-closed" } },
232
+ ]);
233
+
234
+ scriptWith({ calls: {}, waits: { "forge.pr.merged": [{ data: { head, mergeSha: sha("m") }, at: 9 }] } });
235
+ expect(await untilPrEnded("end", { pr })).toEqual({ ended: "merged", head, mergeSha: sha("m"), at: 9 });
236
+
237
+ scriptWith({ calls: {}, waits: { "forge.pr.merged": [{ timedOut: true }] } });
238
+ expect(await untilPrEnded("end", { pr, timeout: "1m" })).toEqual({ ended: false });
239
+ });
@@ -0,0 +1,91 @@
1
+ // The REST client: the token in a header and nowhere else, ETags by URL and page, the server's limit.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { ForgeError, GitLab } from "../src/gitlab.ts";
6
+ import { FakeGitLab } from "./fake-gitlab.ts";
7
+
8
+ function client(server: FakeGitLab, now = () => 1_000_000) {
9
+ return new GitLab({ url: server.url, token: () => server.token, fetch: server.fetch, now });
10
+ }
11
+
12
+ test("every request carries the token in PRIVATE-TOKEN", async () => {
13
+ const server = new FakeGitLab();
14
+ server.project(42, "acme/billing");
15
+ await client(server).get("/projects/42");
16
+ expect(server.requests[0]?.headers["PRIVATE-TOKEN"]).toBe(server.token);
17
+ });
18
+
19
+ test("a read asks again with the ETag it was given, and a 304 answers what was read before", async () => {
20
+ const server = new FakeGitLab();
21
+ server.project(42, "acme/billing");
22
+ const gitlab = client(server);
23
+ const first = await gitlab.get<{ id: number }>("/projects/42");
24
+ const second = await gitlab.get<{ id: number }>("/projects/42");
25
+ expect(second).toEqual(first);
26
+ const [one, two] = server.seen("GET", /^\/projects\/42$/);
27
+ expect(one?.headers["If-None-Match"]).toBeUndefined();
28
+ expect(two?.headers["If-None-Match"]).toMatch(/^W\//);
29
+ });
30
+
31
+ test("a list reads every page, and keeps the ETag of each page apart", async () => {
32
+ const server = new FakeGitLab();
33
+ const project = server.project(42, "acme/billing");
34
+ for (let at = 0; at < 3; at += 1) server.pipeline(project, { sha: "a".repeat(40), ref: "main" });
35
+ server.queue("GET", /\/pipelines$/, 200, [{ id: 1 }], { "X-Next-Page": "2", ETag: "page-1" });
36
+ server.queue("GET", /\/pipelines$/, 200, [{ id: 2 }], { ETag: "page-2" });
37
+ const gitlab = client(server);
38
+ expect(await gitlab.list<{ id: number }>("/projects/42/pipelines")).toEqual([{ id: 1 }, { id: 2 }]);
39
+ server.queue("GET", /\/pipelines$/, 304, null, {});
40
+ server.queue("GET", /\/pipelines$/, 304, null, {});
41
+ expect(await gitlab.list<{ id: number }>("/projects/42/pipelines")).toEqual([{ id: 1 }, { id: 2 }]);
42
+ const asked = server.seen("GET", /\/pipelines$/);
43
+ expect(asked.map((one) => [one.query["page"], one.headers["If-None-Match"]])).toEqual([
44
+ ["1", undefined],
45
+ ["2", undefined],
46
+ ["1", "page-1"],
47
+ ["2", "page-2"],
48
+ ]);
49
+ });
50
+
51
+ test("a 429 is refused for its Retry-After, and the server is not asked again before it", async () => {
52
+ const server = new FakeGitLab();
53
+ server.project(42, "acme/billing");
54
+ let now = 1_000_000;
55
+ const gitlab = client(server, () => now);
56
+ server.queue("GET", /^\/projects\/42$/, 429, { message: "Retry later" }, { "Retry-After": "30" });
57
+ const error = await gitlab.get("/projects/42").catch((caught: unknown) => caught);
58
+ expect(error).toBeInstanceOf(ForgeError);
59
+ expect((error as ForgeError).code).toBe("rate-limited");
60
+ expect((error as ForgeError).retryAfterMs).toBe(30_000);
61
+ await expect(gitlab.get("/projects/42")).rejects.toThrow(/limit/);
62
+ expect(server.requests).toHaveLength(1);
63
+ now += 30_000;
64
+ expect(await gitlab.get<{ id: number }>("/projects/42")).toMatchObject({ id: 42 });
65
+ });
66
+
67
+ test("a spent limit holds the client back until the server's reset", async () => {
68
+ const server = new FakeGitLab();
69
+ server.project(42, "acme/billing");
70
+ let now = 1_000_000;
71
+ const gitlab = client(server, () => now);
72
+ server.headers = { "RateLimit-Remaining": "0", "RateLimit-Reset": String((now + 10_000) / 1000) };
73
+ await gitlab.get("/projects/42");
74
+ expect(gitlab.waitMs()).toBe(10_000);
75
+ await expect(gitlab.get("/projects/42")).rejects.toThrow(ForgeError);
76
+ expect(server.requests).toHaveLength(1);
77
+ server.headers = {};
78
+ now += 10_000;
79
+ await gitlab.get("/projects/42");
80
+ expect(server.requests).toHaveLength(2);
81
+ });
82
+
83
+ test("an error says the path and the server's words, never the token", async () => {
84
+ const server = new FakeGitLab();
85
+ server.project(42, "acme/billing");
86
+ const gitlab = new GitLab({ url: server.url, token: () => "glpat-wrong", fetch: server.fetch, now: () => 0 });
87
+ const error = (await gitlab.get("/projects/42").catch((caught: unknown) => caught)) as ForgeError;
88
+ expect(error.code).toBe("unauthorized");
89
+ expect(error.message).toContain("/api/v4/projects/42");
90
+ expect(error.message).not.toContain("glpat");
91
+ });
@@ -0,0 +1,251 @@
1
+ // Merging: only at the expected head, a merge the server takes for later shown with what calls it
2
+ // off, and a merge that was cut off checked against the server.
3
+
4
+ import { afterEach, expect, test } from "bun:test";
5
+
6
+ import { createNiwa } from "@niwa-labs/testing";
7
+ import type { OperationId } from "@niwa-labs/core";
8
+
9
+ import { CancelStarted, MergeStarted, forge, secret, forgePrMerge, forgePrMergeCancel, forgePrMergePending, forgePrRead } from "../src/index.ts";
10
+ import { sha } from "./fake-gitlab.ts";
11
+ import { BILLING, forgeHost, openMr } from "./support.ts";
12
+ import type { ForgeHost } from "./support.ts";
13
+
14
+ const hosts: ForgeHost[] = [];
15
+ afterEach(async () => {
16
+ for (const host of hosts.splice(0)) await host.stop();
17
+ });
18
+
19
+ async function served(): Promise<ForgeHost> {
20
+ const host = await forgeHost();
21
+ hosts.push(host);
22
+ openMr(host);
23
+ return host;
24
+ }
25
+
26
+ const head = sha("topic-1");
27
+ const ask = { repo: BILLING, number: 7, expectHead: head, method: "merge" } as const;
28
+
29
+ /** The operation of the last merge asked, as its record says. */
30
+ async function lastOperation(host: ForgeHost): Promise<OperationId> {
31
+ const asked = (await host.records([MergeStarted.name])).at(-1);
32
+ return MergeStarted.schema.parse(asked?.data).operation as OperationId;
33
+ }
34
+
35
+ /** Ask the module's own check of the merge, as the host does after a cut. */
36
+ async function check(host: ForgeHost, operation: OperationId) {
37
+ const merge = host.actions.get(forgePrMerge.name);
38
+ if (merge?.check === undefined) throw new Error("forge.pr.merge has no check");
39
+ return await merge.check(operation, { operationId: operation, caller: { kind: "host" } });
40
+ }
41
+
42
+ test("a merge at the expected head merges and answers the commit it made", async () => {
43
+ const host = await served();
44
+ const done = await host.niwa.call(forgePrMerge, { ...ask, method: "squash" });
45
+ expect(done).toEqual({ outcome: "merged", sha: sha(`merge-7-${head}`), externalId: "gitlab.example.com/acme/billing!7" });
46
+ expect(host.server.seen("PUT", /\/merge$/)[0]?.body).toMatchObject({ sha: head, squash: true });
47
+ });
48
+
49
+ test("a squash in a project that merges by merge commit lands on the merge commit, not on the squash it was made from", async () => {
50
+ const host = await served();
51
+ const done = await host.niwa.call(forgePrMerge, { ...ask, method: "squash" });
52
+ const mr = host.billing.mrs.get(7)!;
53
+ expect(mr.squash_commit_sha).toBe(sha("squash-7"));
54
+ expect(mr.merge_commit_sha).not.toBe(mr.squash_commit_sha);
55
+ expect(done).toMatchObject({ outcome: "merged", sha: mr.merge_commit_sha });
56
+ const operation = await lastOperation(host);
57
+ expect(await check(host, operation)).toMatchObject({ status: "completed", value: { sha: mr.merge_commit_sha } });
58
+ expect(await host.niwa.call(forgePrRead, { repo: BILLING, number: 7 })).toMatchObject({ mergeSha: mr.merge_commit_sha });
59
+ });
60
+
61
+ test("a squash in a project that merges by fast-forward lands on the squash commit", async () => {
62
+ const host = await served();
63
+ host.billing.fastForward = true;
64
+ const done = await host.niwa.call(forgePrMerge, { ...ask, method: "squash" });
65
+ expect(done).toMatchObject({ outcome: "merged", sha: sha("squash-7") });
66
+ expect(await check(host, await lastOperation(host))).toMatchObject({ status: "completed", value: { sha: sha("squash-7") } });
67
+ expect(await host.niwa.call(forgePrRead, { repo: BILLING, number: 7 })).toMatchObject({ mergeSha: sha("squash-7") });
68
+ });
69
+
70
+ test("a head that moved is refused by the server and nothing is merged", async () => {
71
+ const host = await served();
72
+ host.billing.mrs.get(7)!.sha = sha("topic-2");
73
+ const done = await host.niwa.call(forgePrMerge, ask);
74
+ expect(done).toMatchObject({ outcome: "refused", why: expect.stringContaining("SHA does not match") });
75
+ expect(host.billing.mrs.get(7)?.state).toBe("opened");
76
+ });
77
+
78
+ test("an automatic merge is armed, listed as pending with its id and the action that calls it off, and cancelled", async () => {
79
+ const host = await served();
80
+ const done = await host.niwa.call(forgePrMerge, { ...ask, when: "pipeline" });
81
+ expect(done).toEqual({ outcome: "armed", externalId: "gitlab.example.com/acme/billing!7", cancel: "forge.pr.merge.cancel" });
82
+ const { items } = await host.niwa.call(forgePrMergePending, {});
83
+ expect(items).toEqual([
84
+ {
85
+ pr: { repo: { ...BILLING, projectId: 42 }, number: 7 },
86
+ mode: "auto-merge",
87
+ externalId: "gitlab.example.com/acme/billing!7",
88
+ expectHead: head,
89
+ cancel: { action: "forge.pr.merge.cancel", input: { repo: BILLING, number: 7 } },
90
+ },
91
+ ]);
92
+ const cancel = items[0]?.cancel;
93
+ expect(await host.niwa.call(forgePrMergeCancel, cancel?.input ?? { repo: BILLING, number: 0 })).toEqual({ cancelled: true });
94
+ expect(host.billing.mrs.get(7)?.merge_when_pipeline_succeeds).toBe(false);
95
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toEqual([]);
96
+ });
97
+
98
+ test("a merge train takes the pull request as queued, and calling it off takes it out of the train", async () => {
99
+ const host = await served();
100
+ expect(await host.niwa.call(forgePrMerge, { ...ask, when: "train" })).toMatchObject({ outcome: "queued" });
101
+ expect(host.billing.mrs.get(7)?.in_train).toBe(true);
102
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toEqual([expect.objectContaining({ mode: "train" })]);
103
+ expect(await host.niwa.call(forgePrMergeCancel, { repo: BILLING, number: 7 })).toEqual({ cancelled: true });
104
+ expect(host.billing.mrs.get(7)?.in_train).toBe(false);
105
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toEqual([]);
106
+ });
107
+
108
+ test("a check of a merge that was never asked says it failed", async () => {
109
+ const host = await served();
110
+ expect(await check(host, "op-never" as OperationId)).toEqual({ status: "failed", error: expect.stringContaining("never asked") });
111
+ });
112
+
113
+ test("a merge whose answer was lost is checked against the pull request on the server", async () => {
114
+ const host = await served();
115
+ host.server.queue("PUT", /\/merge$/, 502, { message: "bad gateway" });
116
+ await expect(host.niwa.call(forgePrMerge, ask)).rejects.toThrow(/502/);
117
+ const operation = await lastOperation(host);
118
+ expect(await check(host, operation)).toMatchObject({ status: "unknown" });
119
+
120
+ const mr = host.billing.mrs.get(7)!;
121
+ mr.state = "merged";
122
+ mr.merge_commit_sha = sha("merged-on-the-server");
123
+ expect(await check(host, operation)).toEqual({
124
+ status: "completed",
125
+ value: { outcome: "merged", sha: sha("merged-on-the-server"), externalId: "gitlab.example.com/acme/billing!7" },
126
+ });
127
+ });
128
+
129
+ test("a merge that was merged at another head than the one expected is not this merge", async () => {
130
+ const host = await served();
131
+ host.server.queue("PUT", /\/merge$/, 502, { message: "bad gateway" });
132
+ await expect(host.niwa.call(forgePrMerge, ask)).rejects.toThrow(/502/);
133
+ const mr = host.billing.mrs.get(7)!;
134
+ Object.assign(mr, { state: "merged", sha: sha("topic-2"), merge_commit_sha: sha("other") });
135
+ expect(await check(host, await lastOperation(host))).toMatchObject({ status: "failed" });
136
+ });
137
+
138
+ test("an automatic merge the server armed while its answer was lost is found by the check and listed as pending once", async () => {
139
+ const host = await served();
140
+ host.server.queue("PUT", /\/merge$/, 502, { message: "bad gateway" });
141
+ await expect(host.niwa.call(forgePrMerge, { ...ask, when: "pipeline" })).rejects.toThrow(/502/);
142
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toEqual([]);
143
+ host.billing.mrs.get(7)!.merge_when_pipeline_succeeds = true;
144
+ const operation = await lastOperation(host);
145
+ expect(await check(host, operation)).toMatchObject({ status: "completed", value: { outcome: "armed" } });
146
+ expect(await check(host, operation)).toMatchObject({ status: "completed", value: { outcome: "armed" } });
147
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toHaveLength(1);
148
+ expect(await host.records(["forge.pr.merge.armed"])).toHaveLength(1);
149
+ });
150
+
151
+ test("a check after an automatic merge the call recorded itself writes no second record of it", async () => {
152
+ const host = await served();
153
+ await host.niwa.call(forgePrMerge, { ...ask, when: "pipeline" });
154
+ expect(await check(host, await lastOperation(host))).toMatchObject({ status: "completed", value: { outcome: "armed" } });
155
+ expect(await host.records(["forge.pr.merge.armed"])).toHaveLength(1);
156
+ });
157
+
158
+ test("a cancel the server answers without calling anything off leaves the merge pending", async () => {
159
+ const host = await served();
160
+ await host.niwa.call(forgePrMerge, { ...ask, when: "pipeline" });
161
+ host.server.queue("POST", /cancel_merge_when_pipeline_succeeds$/, 201, { status: "error", message: "Merge train rate limit" });
162
+ expect(await host.niwa.call(forgePrMergeCancel, { repo: BILLING, number: 7 })).toEqual({ cancelled: false });
163
+ expect(host.billing.mrs.get(7)?.merge_when_pipeline_succeeds).toBe(true);
164
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toHaveLength(1);
165
+ expect(await host.records(["forge.pr.merge.disarmed"])).toEqual([]);
166
+ expect(await host.niwa.call(forgePrMergeCancel, { repo: BILLING, number: 7 })).toEqual({ cancelled: true });
167
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toEqual([]);
168
+ });
169
+
170
+ test("a cancel that finds the pull request merged does not say the merge was called off", async () => {
171
+ const host = await served();
172
+ await host.niwa.call(forgePrMerge, { ...ask, when: "pipeline" });
173
+ const mr = host.billing.mrs.get(7)!;
174
+ host.server.queue("POST", /cancel_merge_when_pipeline_succeeds$/, 406, { message: "406 Not Acceptable" });
175
+ host.server.queue("DELETE", /merge_trains/, 404, { message: "404 Not found" });
176
+ Object.assign(mr, { state: "merged", merge_when_pipeline_succeeds: false, merge_commit_sha: sha("merged-meanwhile") });
177
+ expect(await host.niwa.call(forgePrMergeCancel, { repo: BILLING, number: 7 })).toEqual({ cancelled: false });
178
+ expect(await host.records(["forge.pr.merge.disarmed"])).toEqual([]);
179
+ });
180
+
181
+ test("calling off an automatic merge does not ask about a merge train, which a server may not have", async () => {
182
+ const host = await served();
183
+ await host.niwa.call(forgePrMerge, { ...ask, when: "pipeline" });
184
+ host.server.queue("GET", /merge_trains/, 403, { message: "403 Forbidden" });
185
+ expect(await host.niwa.call(forgePrMergeCancel, { repo: BILLING, number: 7 })).toEqual({ cancelled: true });
186
+ expect(host.server.seen("GET", /merge_trains/)).toEqual([]);
187
+ expect(await host.records(["forge.pr.merge.disarmed"])).toHaveLength(1);
188
+ });
189
+
190
+ test("concurrent merges and cancellations send one mutation per claim", async () => {
191
+ const host = await served();
192
+ const merge = () => host.niwa.call(forgePrMerge, { ...ask, when: "pipeline" });
193
+ const first = await Promise.allSettled([merge(), merge()]);
194
+ expect(first.filter(answer => answer.status === "fulfilled")).toHaveLength(1);
195
+ expect(host.server.seen("PUT", /\/merge$/)).toHaveLength(1);
196
+ const cancel = () => host.niwa.call(forgePrMergeCancel, { repo: BILLING, number: 7 });
197
+ const second = await Promise.allSettled([cancel(), cancel()]);
198
+ expect(second.filter(answer => answer.status === "fulfilled" && answer.value.cancelled)).toHaveLength(1);
199
+ expect(host.server.seen("POST", /cancel_merge_when_pipeline_succeeds$/)).toHaveLength(1);
200
+ });
201
+
202
+ test("an interrupted cancellation is recovered from GitLab without sending another mutation", async () => {
203
+ const host = await served();
204
+ await host.niwa.call(forgePrMerge, { ...ask, when: "pipeline" });
205
+ host.server.queue("POST", /cancel_merge_when_pipeline_succeeds$/, 502, {});
206
+ await expect(host.niwa.call(forgePrMergeCancel, { repo: BILLING, number: 7 })).rejects.toThrow(/502/);
207
+ const operation = CancelStarted.schema.parse((await host.records([CancelStarted.name]))[0]?.data).operation as OperationId;
208
+ const cancel = host.actions.get(forgePrMergeCancel.name)!;
209
+ const check = () => cancel.check!(operation, { operationId: operation, caller: { kind: "host" } });
210
+ expect(await check()).toEqual({ status: "unknown" });
211
+ host.billing.mrs.get(7)!.merge_when_pipeline_succeeds = false;
212
+ expect(await check()).toEqual({ status: "completed", value: { cancelled: true } });
213
+ expect(await check()).toEqual({ status: "completed", value: { cancelled: true } });
214
+ expect(host.server.seen("POST", /cancel_merge_when_pipeline_succeeds$/)).toHaveLength(1);
215
+ expect(await host.records(["forge.pr.merge.disarmed"])).toHaveLength(1);
216
+ });
217
+
218
+ test("reopening a host finds an interrupted merge on an unwatched repository without sending it again", async () => {
219
+ const host = await served();
220
+ host.server.queue("PUT", /\/merge$/, 502, {});
221
+ await expect(host.niwa.call(forgePrMerge, { ...ask, when: "pipeline" })).rejects.toThrow(/502/);
222
+ await host.niwa.close();
223
+ host.billing.mrs.get(7)!.merge_when_pipeline_succeeds = true;
224
+ const restarted = createNiwa({ home: host.home });
225
+ restarted.use(forge({
226
+ servers: [{ host: BILLING.host, url: host.server.url, token: secret("GITLAB_TOKEN") }],
227
+ fetch: host.server.fetch, env: {}, poll: { awaited: 15, background: 15, quiet: 15 },
228
+ }));
229
+ try {
230
+ await restarted.serve();
231
+ const until = Date.now() + 3000;
232
+ while ((await restarted.call(forgePrMergePending, {})).items.length === 0 && Date.now() < until) await Bun.sleep(15);
233
+ expect((await restarted.call(forgePrMergePending, {})).items).toHaveLength(1);
234
+ expect(host.server.seen("PUT", /\/merge$/)).toHaveLength(1);
235
+ } finally {
236
+ await restarted.close();
237
+ }
238
+ });
239
+
240
+ test("an expected target commit refuses before any GitLab merge request", async () => {
241
+ const host = await served();
242
+ const target = sha("main-tip");
243
+ host.billing.branches.set("main", target);
244
+ expect((await host.niwa.call(forgePrRead, { repo: BILLING, number: 7, landing: true })).landing)
245
+ .toMatchObject({ targetSha: target, conditionalMerge: false });
246
+ for (const expectTarget of [target, sha("obsolete")]) {
247
+ expect(await host.niwa.call(forgePrMerge, { ...ask, expectTarget })).toMatchObject({ outcome: "refused" });
248
+ }
249
+ expect(host.server.seen("PUT", /\/merge$/)).toHaveLength(0);
250
+ expect(await host.records([MergeStarted.name])).toHaveLength(0);
251
+ });