@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,454 @@
1
+ // Watching a repository: events under the server's ids, changes between polls as versions with the
2
+ // state before them, merge results bound to their pair of commits, and the cadence of the polls.
3
+
4
+ import { afterEach, expect, test } from "bun:test";
5
+
6
+ import type { JournalReader } from "@niwa-labs/core";
7
+
8
+ import { setTimeout as sleep } from "node:timers/promises";
9
+
10
+ import {
11
+ ChecksObserved,
12
+ DEFAULT_INTERVALS,
13
+ JobObserved,
14
+ PipelineObserved,
15
+ Poller,
16
+ PrComment,
17
+ PrHead,
18
+ PrClosed,
19
+ PrMerged,
20
+ PrOpened,
21
+ Pushed,
22
+ forgePipelineRead,
23
+ forgePrList,
24
+ forgePrMerge,
25
+ forgePrMergePending,
26
+ forgeRepoStatus,
27
+ forgeRepoSync,
28
+ forgeRepoUnwatch,
29
+ forgeRepoWatch,
30
+ pollInterval,
31
+ } from "../src/index.ts";
32
+ import { GitLab } from "../src/gitlab.ts";
33
+ import { Seen, sync } from "../src/observe.ts";
34
+ import type { Emit } from "../src/observe.ts";
35
+ import { FakeGitLab, sha } from "./fake-gitlab.ts";
36
+ import { BILLING, forgeHost, openMr } from "./support.ts";
37
+ import type { ForgeHost } from "./support.ts";
38
+
39
+ const hosts: ForgeHost[] = [];
40
+ afterEach(async () => {
41
+ for (const host of hosts.splice(0)) await host.stop();
42
+ });
43
+
44
+ async function watched(opts: Parameters<typeof forgeHost>[0] = {}): Promise<ForgeHost> {
45
+ const host = await forgeHost(opts);
46
+ hosts.push(host);
47
+ await host.niwa.call(forgeRepoWatch, { repo: BILLING });
48
+ return host;
49
+ }
50
+
51
+ const syncNow = (host: ForgeHost) => host.niwa.call(forgeRepoSync, { repo: BILLING });
52
+ const dataOf = async (host: ForgeHost, type: string) => (await host.records([type])).map((one) => one.data as Record<string, unknown>);
53
+
54
+ test("events written before the repository was watched are history, and an event is written once under the server's id", async () => {
55
+ const host = await forgeHost();
56
+ hosts.push(host);
57
+ host.server.event(host.billing, { action_name: "pushed to", push_data: { ref: "main", ref_type: "branch", commit_from: sha("old-0"), commit_to: sha("old-1") } });
58
+ await host.niwa.call(forgeRepoWatch, { repo: BILLING });
59
+ const push = host.server.event(host.billing, { action_name: "pushed to", push_data: { ref: "main", ref_type: "branch", commit_from: sha("main-1"), commit_to: sha("main-2") } });
60
+ expect((await syncNow(host)).written).toBeGreaterThan(0);
61
+ expect(await syncNow(host)).toEqual({ written: 0 });
62
+ const records = await host.records([Pushed.name]);
63
+ expect(records.map((one) => [one.id, one.data])).toEqual([
64
+ [
65
+ `forge:gitlab.example.com:42:event:${String(push.id)}`,
66
+ { repo: { ...BILLING, projectId: 42 }, ref: "main", refType: "branch", before: sha("main-1"), after: sha("main-2"), author: "dev", source: { kind: "event", id: push.id } },
67
+ ],
68
+ ]);
69
+ });
70
+
71
+ test("a pull request opened and merged is written from the event log, and a merge pending on it is no longer pending", async () => {
72
+ const host = await watched();
73
+ openMr(host);
74
+ host.server.event(host.billing, { action_name: "opened", target_type: "MergeRequest", target_iid: 7 });
75
+ await syncNow(host);
76
+ expect(await dataOf(host, PrOpened.name)).toEqual([expect.objectContaining({ title: "MR 7", branch: "topic", base: "main", source: expect.objectContaining({ kind: "event" }) })]);
77
+ await host.niwa.call(forgePrMerge, { repo: BILLING, number: 7, expectHead: sha("topic-1"), method: "merge", when: "pipeline" });
78
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toHaveLength(1);
79
+
80
+ const mr = host.billing.mrs.get(7)!;
81
+ Object.assign(mr, { state: "merged", merge_commit_sha: sha("merge-7") });
82
+ host.server.event(host.billing, { action_name: "accepted", target_type: "MergeRequest", target_iid: 7, author: { username: "marge" } });
83
+ await syncNow(host);
84
+ expect(await dataOf(host, PrMerged.name)).toEqual([expect.objectContaining({ base: "main", head: sha("topic-1"), mergeSha: sha("merge-7"), by: "marge" })]);
85
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toEqual([]);
86
+ });
87
+
88
+ test("one merge is one record for a subscriber, whether the log or a look at the pull request told it first", async () => {
89
+ const host = await watched();
90
+ const mr = openMr(host);
91
+ host.server.event(host.billing, { action_name: "opened", target_type: "MergeRequest", target_iid: 7 });
92
+ await syncNow(host);
93
+ // The merge shows on the pull request before its event is in the log.
94
+ Object.assign(mr, { state: "merged", merge_commit_sha: sha("merge-7") });
95
+ await syncNow(host);
96
+ host.server.event(host.billing, { action_name: "accepted", target_type: "MergeRequest", target_iid: 7, author: { username: "marge" } });
97
+ await syncNow(host);
98
+ await syncNow(host);
99
+ expect(await dataOf(host, PrMerged.name)).toEqual([expect.objectContaining({ mergeSha: sha("merge-7"), source: { kind: "observed", version: 1 } })]);
100
+ });
101
+
102
+ test("a pull request closed and opened again is each state in turn, from the log and from a look at the open ones", async () => {
103
+ const host = await watched();
104
+ const mr = openMr(host);
105
+ const list = async () => (await host.niwa.call(forgePrList, {})).items.map((one) => one.state);
106
+ await syncNow(host);
107
+ expect(await list()).toEqual(["open"]);
108
+ mr.state = "closed";
109
+ await syncNow(host);
110
+ expect(await list()).toEqual(["closed"]);
111
+ // Reopened between two polls: only the open list shows it.
112
+ mr.state = "opened";
113
+ await syncNow(host);
114
+ expect(await list()).toEqual(["open"]);
115
+ // Closed and reopened with the log saying so.
116
+ mr.state = "closed";
117
+ host.server.event(host.billing, { action_name: "closed", target_type: "MergeRequest", target_iid: 7 });
118
+ await syncNow(host);
119
+ expect(await list()).toEqual(["closed"]);
120
+ mr.state = "opened";
121
+ host.server.event(host.billing, { action_name: "reopened", target_type: "MergeRequest", target_iid: 7 });
122
+ await syncNow(host);
123
+ expect(await list()).toEqual(["open"]);
124
+ mr.state = "closed";
125
+ await syncNow(host);
126
+ expect(await list()).toEqual(["closed"]);
127
+ expect((await dataOf(host, PrOpened.name)).map((one) => [one["reopened"], (one["source"] as { kind: string }).kind])).toEqual([
128
+ [undefined, "observed"],
129
+ [true, "observed"],
130
+ [true, "event"],
131
+ ]);
132
+ expect((await dataOf(host, PrClosed.name)).map((one) => (one["source"] as { kind: string }).kind)).toEqual(["observed", "event", "observed"]);
133
+ expect(await syncNow(host)).toEqual({ written: 0 });
134
+ });
135
+
136
+ test("a comment is written as its author, size and digest, never its text", async () => {
137
+ const host = await watched();
138
+ openMr(host);
139
+ const body = "The secret plan is in the wiki";
140
+ host.server.event(host.billing, { action_name: "commented on", target_type: "Note", note: { id: 9001, body, noteable_type: "MergeRequest", noteable_iid: 7, author: { username: "rev" } } });
141
+ await syncNow(host);
142
+ expect(await dataOf(host, PrComment.name)).toEqual([expect.objectContaining({ comment: 9001, author: "rev", size: body.length, digest: expect.stringMatching(/^sha256:/) })]);
143
+ expect(JSON.stringify(await host.records())).not.toContain("secret plan");
144
+ });
145
+
146
+ test("a head that moves away and back between polls is three observations, each with the head before it", async () => {
147
+ const host = await watched();
148
+ const mr = openMr(host);
149
+ await syncNow(host);
150
+ mr.sha = sha("topic-2");
151
+ await syncNow(host);
152
+ mr.sha = sha("topic-1");
153
+ await syncNow(host);
154
+ await syncNow(host);
155
+ const heads = await host.records([PrHead.name]);
156
+ expect(heads.map((one) => one.data)).toEqual([
157
+ expect.objectContaining({ head: sha("topic-1"), source: { kind: "observed", version: 1 } }),
158
+ expect.objectContaining({ head: sha("topic-2"), previous: sha("topic-1"), source: { kind: "observed", version: 2 } }),
159
+ expect.objectContaining({ head: sha("topic-1"), previous: sha("topic-2"), source: { kind: "observed", version: 3 } }),
160
+ ]);
161
+ expect(new Set(heads.map((one) => one.id)).size).toBe(3);
162
+ // An observation records no head the server never showed.
163
+ expect(await dataOf(host, PrOpened.name)).toEqual([expect.objectContaining({ source: { kind: "observed", version: 1 } })]);
164
+ });
165
+
166
+ test("a pipeline is written at each state it was seen in, and a merge result with the pair of commits it was made of", async () => {
167
+ const host = await watched();
168
+ openMr(host);
169
+ const mergeSha = sha("merge-result-1");
170
+ host.billing.commits.set(mergeSha, [sha("main-1"), sha("topic-1")]);
171
+ const result = host.server.pipeline(host.billing, { sha: mergeSha, ref: "refs/merge-requests/7/merge", source: "merge_request_event" });
172
+ host.server.job(host.billing, { pipeline: result.id, ref: result.ref, name: "test" });
173
+ const orphan = host.server.pipeline(host.billing, { sha: sha("unknown-merge"), ref: "refs/merge-requests/7/merge", source: "merge_request_event" });
174
+ await syncNow(host);
175
+ result.status = "success";
176
+ host.billing.jobs[0]!.status = "success";
177
+ await syncNow(host);
178
+ expect(await syncNow(host)).toEqual({ written: 0 });
179
+ const pipelines = await dataOf(host, PipelineObserved.name);
180
+ expect(pipelines).toEqual([
181
+ expect.objectContaining({ pipeline: result.id, kind: "merge-result", pr: 7, sourceSha: sha("topic-1"), targetSha: sha("main-1"), mergeSha, state: "running", source: { kind: "observed", version: 1 } }),
182
+ expect.objectContaining({ pipeline: result.id, state: "success", previous: "running", source: { kind: "observed", version: 2 } }),
183
+ ]);
184
+ expect(pipelines.some((one) => one["pipeline"] === orphan.id)).toBe(false);
185
+ expect((await dataOf(host, JobObserved.name)).map((one) => [one["state"], one["previous"]])).toEqual([
186
+ ["running", undefined],
187
+ ["success", "running"],
188
+ ]);
189
+ });
190
+
191
+ test("a tag's pipeline is a tag however it is read, though a list does not say that its ref is one", async () => {
192
+ const host = await watched();
193
+ const tagged = host.server.pipeline(host.billing, { sha: sha("v1-tip"), ref: "v1.0", tag: true, status: "success" });
194
+ host.server.pipeline(host.billing, { sha: sha("main-tip"), ref: "main" });
195
+ await syncNow(host);
196
+ const recorded = (await dataOf(host, PipelineObserved.name)).map((one) => [one["ref"], one["kind"]]);
197
+ expect(recorded).toEqual([["v1.0", "tag"], ["main", "branch"]]);
198
+ const read = (input: object) => host.niwa.call(forgePipelineRead, { repo: BILLING, ...input });
199
+ expect((await read({ sha: sha("v1-tip") })).items.map((one) => one.kind)).toEqual(["tag"]);
200
+ expect((await read({ pipeline: tagged.id })).items.map((one) => one.kind)).toEqual(["tag"]);
201
+ expect((await read({ sha: sha("v1-tip"), kind: "tag" })).items).toHaveLength(1);
202
+ });
203
+
204
+ test("a burst of pipelines between two polls is recorded whole, and a poll with nothing new reads one page", async () => {
205
+ const host = await watched();
206
+ for (let at = 0; at < 130; at += 1) host.server.pipeline(host.billing, { sha: sha(`burst-${String(at)}`), ref: "main", status: "success" });
207
+ await syncNow(host);
208
+ expect(await dataOf(host, PipelineObserved.name)).toHaveLength(130);
209
+ host.server.requests.length = 0;
210
+ expect(await syncNow(host)).toEqual({ written: 0 });
211
+ expect(host.server.seen("GET", /\/pipelines$/).map((one) => one.query["page"])).toEqual(["1"]);
212
+ });
213
+
214
+ test("a job that moves while its pipeline stays running is written at each state it was seen in", async () => {
215
+ const host = await watched();
216
+ const run = host.server.pipeline(host.billing, { sha: sha("main-tip"), ref: "main", status: "running" });
217
+ const job = host.server.job(host.billing, { pipeline: run.id, ref: "main", status: "pending" });
218
+ await syncNow(host);
219
+ job.status = "running";
220
+ await syncNow(host);
221
+ job.status = "success";
222
+ await syncNow(host);
223
+ expect((await dataOf(host, JobObserved.name)).map((one) => [one["state"], one["previous"]])).toEqual([
224
+ ["pending", undefined],
225
+ ["running", "pending"],
226
+ ["success", "running"],
227
+ ]);
228
+ expect(await dataOf(host, PipelineObserved.name)).toHaveLength(1);
229
+ });
230
+
231
+ test("a pipeline whose jobs could not be read is read again by the next pass, not taken as done", async () => {
232
+ const host = await watched();
233
+ const run = host.server.pipeline(host.billing, { sha: sha("main-tip"), ref: "main", status: "success" });
234
+ host.server.job(host.billing, { pipeline: run.id, ref: "main", status: "success" });
235
+ host.server.queue("GET", /\/pipelines\/\d+\/jobs$/, 429, { message: "slow down" }, { "Retry-After": "0" });
236
+ await expect(syncNow(host)).rejects.toThrow(/429|limit/);
237
+ await syncNow(host);
238
+ expect((await dataOf(host, JobObserved.name)).map((one) => one["state"])).toEqual(["success"]);
239
+ expect((await dataOf(host, PipelineObserved.name)).map((one) => one["state"])).toEqual(["success"]);
240
+ });
241
+
242
+ test("the checks of a pull request follow the pipelines of its head", async () => {
243
+ const host = await watched();
244
+ const mr = openMr(host);
245
+ const first = host.server.pipeline(host.billing, { sha: sha("topic-1"), ref: "refs/merge-requests/7/head", source: "merge_request_event" });
246
+ await syncNow(host);
247
+ first.status = "success";
248
+ await syncNow(host);
249
+ mr.sha = sha("topic-2");
250
+ await syncNow(host);
251
+ expect((await dataOf(host, ChecksObserved.name)).map((one) => [one["head"], one["state"], one["previous"]])).toEqual([
252
+ [sha("topic-1"), "pending", undefined],
253
+ [sha("topic-1"), "green", "pending"],
254
+ [sha("topic-2"), "none", "green"],
255
+ ]);
256
+ });
257
+
258
+ test("a projection takes from the journal only what it gained since the last time, and records of other repositories are not its own", () => {
259
+ const repo = { ...BILLING, projectId: 42 };
260
+ const stored: Array<{ seq: number; type: string; data: unknown }> = [];
261
+ const add = (type: string, data: unknown) => stored.push({ seq: stored.length + 1, type, data });
262
+ let returned = 0;
263
+ const journal = {
264
+ since: (from: number, types?: string[]) => {
265
+ const found = stored.filter((one) => one.seq > Number(from) && (types === undefined || types.includes(one.type)));
266
+ returned += found.length;
267
+ return found;
268
+ },
269
+ } as unknown as Parameters<Seen["absorb"]>[0];
270
+ const opened = (number: number, project: number) => ({ pr: { repo: { ...repo, projectId: project }, number }, title: "t", branch: "b", base: "main", source: { kind: "event", id: number } });
271
+ add("forge.pr.opened", opened(1, 42));
272
+ add("forge.pr.opened", opened(2, 43));
273
+ const seen = new Seen(repo);
274
+ seen.absorb(journal);
275
+ expect([...seen.life.keys()]).toEqual([1]);
276
+ expect(returned).toBe(2);
277
+ seen.absorb(journal);
278
+ expect(returned).toBe(2);
279
+ add("forge.pr.opened", opened(3, 42));
280
+ seen.absorb(journal);
281
+ expect([...seen.life.keys()]).toEqual([1, 3]);
282
+ expect(returned).toBe(3);
283
+ });
284
+
285
+ test("an event log of more than 2000 new events is written whole, oldest first, and the next poll finds nothing missing", async () => {
286
+ const host = await watched();
287
+ for (let at = 0; at < 2100; at += 1) {
288
+ host.server.event(host.billing, { action_name: "pushed to", push_data: { ref: "main", ref_type: "branch", commit_from: sha(`from-${String(at)}`), commit_to: sha(`to-${String(at)}`) } });
289
+ }
290
+ expect((await syncNow(host)).written).toBe(2100);
291
+ expect(await syncNow(host)).toEqual({ written: 0 });
292
+ expect((await host.niwa.call(forgeRepoStatus, {})).items[0]).not.toHaveProperty("eventsMissed");
293
+ }, 30_000);
294
+
295
+ test("a log read down to its bound says that what lay beyond it was not seen, and writes what it read", async () => {
296
+ const server = new FakeGitLab();
297
+ const project = server.project(42, "acme/billing");
298
+ const repo = { ...BILLING, projectId: 42 };
299
+ for (let at = 0; at < 250; at += 1) server.event(project, { action_name: "pushed to", push_data: { ref: "main", ref_type: "branch", commit_from: null, commit_to: sha(`to-${String(at)}`) } });
300
+ const stored: Array<{ seq: number; type: string; data: unknown; id: string }> = [];
301
+ const journal = { since: (from: number, types?: string[]) => stored.filter((one) => one.seq > Number(from) && (types === undefined || types.includes(one.type))) } as unknown as JournalReader;
302
+ const emit: Emit = async (type, data, opts) => {
303
+ stored.push({ seq: stored.length + 1, type: type.name, data, id: opts.id ?? "" });
304
+ return {} as never;
305
+ };
306
+ let gaps = 0;
307
+ const gitlab = new GitLab({ url: server.url, token: () => server.token, fetch: server.fetch, now: () => 0 });
308
+ const written = await sync({ gitlab, journal, emit, gap: () => (gaps += 1), eventPages: 2 }, repo);
309
+ expect(gaps).toBe(1);
310
+ expect(written).toBe(200);
311
+ const whole = await sync({ gitlab, journal, emit, gap: () => (gaps += 1), eventPages: 3 }, repo);
312
+ expect(gaps).toBe(1);
313
+ expect(whole).toBe(0);
314
+ });
315
+
316
+ test("a repository says when it was last polled and what its last poll failed with, and a poll that found nothing is not a failure", async () => {
317
+ const host = await watched();
318
+ const status = async () => (await host.niwa.call(forgeRepoStatus, { repo: BILLING })).items;
319
+ expect(await status()).toEqual([{ repo: { ...BILLING, projectId: 42 } }]);
320
+ host.server.queue("GET", /\/events$/, 503, { message: "server is down" });
321
+ await expect(syncNow(host)).rejects.toThrow(/503/);
322
+ const [failed] = await status();
323
+ expect(failed).toMatchObject({ lastError: expect.stringContaining("503") });
324
+ expect(failed?.lastPassAt).toBeGreaterThan(0);
325
+ expect(failed).not.toHaveProperty("lastOkAt");
326
+ expect(await syncNow(host)).toEqual({ written: 0 });
327
+ const [ok] = await status();
328
+ expect(ok?.lastOkAt).toBeGreaterThan(0);
329
+ expect(ok).not.toHaveProperty("lastError");
330
+ expect((await host.niwa.call(forgeRepoStatus, {})).items).toHaveLength(1);
331
+ });
332
+
333
+ test("a path that names another project than when it was watched before is read afresh", async () => {
334
+ const host = await watched();
335
+ openMr(host);
336
+ await syncNow(host);
337
+ await host.niwa.call(forgeRepoUnwatch, { repo: BILLING });
338
+ host.server.projects.delete(42);
339
+ const renamed = host.server.project(99, "acme/billing");
340
+ openMr(host, 3, "topic-3", renamed);
341
+ await host.niwa.call(forgeRepoWatch, { repo: BILLING });
342
+ expect((await syncNow(host)).written).toBeGreaterThan(0);
343
+ expect(await syncNow(host)).toEqual({ written: 0 });
344
+ expect((await dataOf(host, PrOpened.name)).map((one) => (one["pr"] as { repo: { projectId: number } }).repo.projectId)).toEqual([42, 99]);
345
+ });
346
+
347
+ test("a repository that is not watched is not polled", async () => {
348
+ const host = await forgeHost();
349
+ hosts.push(host);
350
+ await expect(syncNow(host)).rejects.toThrow(/not watched/);
351
+ });
352
+
353
+ test("the cadence: 20 seconds while waited on, 2 minutes after a change, 5 after an hour of quiet", () => {
354
+ const now = 10_000_000;
355
+ expect(pollInterval({ awaited: true, lastChangeAt: now - 7_200_000, now })).toBe(20_000);
356
+ expect(pollInterval({ awaited: false, lastChangeAt: now - 60_000, now })).toBe(120_000);
357
+ expect(pollInterval({ awaited: false, lastChangeAt: now - 3_600_000, now })).toBe(300_000);
358
+ expect(DEFAULT_INTERVALS).toEqual({ awaited: 20_000, background: 120_000, quiet: 300_000 });
359
+ });
360
+
361
+ test("the poller passes over a repository when its interval is up, sooner while it is read, never while the limit is spent", () => {
362
+ const poller = new Poller();
363
+ const free = () => 0;
364
+ let now = 0;
365
+ expect(poller.due(["a"], now, free)).toEqual(["a"]);
366
+ expect(poller.due(["a"], now, () => 5_000)).toEqual([]);
367
+ poller.passed("a", now, 1);
368
+ now += 60_000;
369
+ expect(poller.due(["a"], now, free)).toEqual([]);
370
+ now += 60_000;
371
+ expect(poller.due(["a"], now, free)).toEqual(["a"]);
372
+ poller.passed("a", now, 0);
373
+ poller.touch("a", now);
374
+ now += 20_000;
375
+ expect(poller.due(["a"], now, free)).toEqual(["a"]);
376
+ poller.passed("a", now, 0);
377
+ now += 4_000_000;
378
+ poller.passed("a", now, 0);
379
+ now += 200_000;
380
+ expect(poller.due(["a"], now, free)).toEqual([]);
381
+ now += 100_000;
382
+ expect(poller.due(["a"], now, free)).toEqual(["a"]);
383
+ });
384
+
385
+ test("with polling on, the module polls a watched repository by itself", async () => {
386
+ const host = await watched({ forge: { poll: { awaited: 20, background: 20, quiet: 20 } } });
387
+ host.server.event(host.billing, { action_name: "pushed new", push_data: { ref: "topic", ref_type: "branch", commit_from: null, commit_to: sha("topic-1") } });
388
+ const deadline = Date.now() + 5_000;
389
+ while ((await host.records([Pushed.name])).length === 0 && Date.now() < deadline) await sleep(20);
390
+ expect(await dataOf(host, Pushed.name)).toEqual([expect.objectContaining({ ref: "topic", after: sha("topic-1") })]);
391
+ });
392
+
393
+ test("an automatic merge called off on the server is no longer pending after the next poll", async () => {
394
+ const host = await watched();
395
+ openMr(host);
396
+ await host.niwa.call(forgePrMerge, { repo: BILLING, number: 7, expectHead: sha("topic-1"), method: "merge", when: "pipeline" });
397
+ await syncNow(host);
398
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toHaveLength(1);
399
+ host.billing.mrs.get(7)!.merge_when_pipeline_succeeds = false;
400
+ await syncNow(host);
401
+ await syncNow(host);
402
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toEqual([]);
403
+ expect(await host.records(["forge.pr.merge.disarmed"])).toHaveLength(1);
404
+ });
405
+
406
+ test("a merge train that dropped a pull request is no longer pending after the next poll", async () => {
407
+ const host = await watched();
408
+ openMr(host);
409
+ await host.niwa.call(forgePrMerge, { repo: BILLING, number: 7, expectHead: sha("topic-1"), method: "merge", when: "train" });
410
+ await syncNow(host);
411
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toHaveLength(1);
412
+ host.billing.mrs.get(7)!.in_train = false;
413
+ await syncNow(host);
414
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toEqual([]);
415
+ });
416
+
417
+ /** A host that polls on its own, quickly, with no repository watched. */
418
+ async function polling(): Promise<ForgeHost> {
419
+ const host = await forgeHost({ forge: { poll: { awaited: 20, background: 20, quiet: 20 } } });
420
+ hosts.push(host);
421
+ openMr(host);
422
+ return host;
423
+ }
424
+
425
+ async function settledPending(host: ForgeHost, expected: number): Promise<void> {
426
+ const deadline = Date.now() + 5_000;
427
+ while ((await host.niwa.call(forgePrMergePending, {})).items.length !== expected && Date.now() < deadline) await sleep(20);
428
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toHaveLength(expected);
429
+ }
430
+
431
+ test("a merge armed on a repository nobody watches is no longer pending once the server merged the pull request", async () => {
432
+ const host = await polling();
433
+ await host.niwa.call(forgePrMerge, { repo: BILLING, number: 7, expectHead: sha("topic-1"), method: "merge", when: "pipeline" });
434
+ await settledPending(host, 1);
435
+ Object.assign(host.billing.mrs.get(7)!, { state: "merged", merge_when_pipeline_succeeds: false, merge_commit_sha: sha("merge-7") });
436
+ await settledPending(host, 0);
437
+ expect(await host.records(["forge.pr.merge.settled"])).toEqual([expect.objectContaining({ data: expect.objectContaining({ outcome: "merged", mergeSha: sha("merge-7") }) })]);
438
+ // The repository was not watched: nothing about the merge is announced to those who subscribe to merges.
439
+ expect(await host.records([PrMerged.name])).toEqual([]);
440
+ }, 15_000);
441
+
442
+ test("a merge armed on a repository nobody watches is no longer pending once it is closed or called off on the server", async () => {
443
+ const host = await polling();
444
+ await host.niwa.call(forgePrMerge, { repo: BILLING, number: 7, expectHead: sha("topic-1"), method: "merge", when: "pipeline" });
445
+ host.billing.mrs.get(7)!.merge_when_pipeline_succeeds = false;
446
+ await settledPending(host, 0);
447
+ expect(await host.records(["forge.pr.merge.disarmed"])).toHaveLength(1);
448
+
449
+ openMr(host, 8, "topic-8");
450
+ await host.niwa.call(forgePrMerge, { repo: BILLING, number: 8, expectHead: sha("topic-8"), method: "merge", when: "pipeline" });
451
+ Object.assign(host.billing.mrs.get(8)!, { state: "closed", merge_when_pipeline_succeeds: false });
452
+ await settledPending(host, 0);
453
+ expect(await host.records(["forge.pr.merge.settled"])).toEqual([expect.objectContaining({ data: expect.objectContaining({ outcome: "closed" }) })]);
454
+ }, 15_000);
@@ -0,0 +1,125 @@
1
+ // The pull requests the module observed: folded from its records, the open ones first, with the checks of
2
+ // the head and the latest pipelines, and nothing asked of the server.
3
+
4
+ import { afterEach, expect, test } from "bun:test";
5
+
6
+ import { forgePrList, forgeRepoSync, forgeRepoWatch } from "../src/index.ts";
7
+ import { PIPELINES_SHOWN } from "../src/prs.ts";
8
+ import { sha } from "./fake-gitlab.ts";
9
+ import { BILLING, forgeHost, openMr } from "./support.ts";
10
+ import type { ForgeHost } from "./support.ts";
11
+
12
+ const PAYROLL = { host: "gitlab.example.com", path: "acme/payroll" };
13
+
14
+ const hosts: ForgeHost[] = [];
15
+ afterEach(async () => {
16
+ for (const host of hosts.splice(0)) await host.stop();
17
+ });
18
+
19
+ async function watched(): Promise<ForgeHost> {
20
+ const host = await forgeHost();
21
+ hosts.push(host);
22
+ await host.niwa.call(forgeRepoWatch, { repo: BILLING });
23
+ await host.niwa.call(forgeRepoWatch, { repo: PAYROLL });
24
+ return host;
25
+ }
26
+
27
+ const syncAll = async (host: ForgeHost) => {
28
+ await host.niwa.call(forgeRepoSync, { repo: BILLING });
29
+ await host.niwa.call(forgeRepoSync, { repo: PAYROLL });
30
+ };
31
+
32
+ test("an open pull request is listed with its head, its checks and its pipelines as they were last seen", async () => {
33
+ const host = await watched();
34
+ openMr(host);
35
+ const head = host.server.pipeline(host.billing, { sha: sha("topic-1"), ref: "refs/merge-requests/7/head", source: "merge_request_event" });
36
+ await syncAll(host);
37
+ expect((await host.niwa.call(forgePrList, {})).items).toEqual([
38
+ {
39
+ pr: { repo: { ...BILLING, projectId: 42 }, number: 7 },
40
+ state: "open",
41
+ title: "MR 7",
42
+ branch: "topic",
43
+ base: "main",
44
+ draft: false,
45
+ author: "dev",
46
+ head: sha("topic-1"),
47
+ checks: "pending",
48
+ pipelines: [{ pipeline: head.id, kind: "head", state: "running", sourceSha: sha("topic-1") }],
49
+ },
50
+ ]);
51
+
52
+ head.status = "success";
53
+ await syncAll(host);
54
+ const [listed] = (await host.niwa.call(forgePrList, {})).items;
55
+ expect(listed?.checks).toBe("green");
56
+ expect(listed?.pipelines).toEqual([expect.objectContaining({ pipeline: head.id, state: "success" })]);
57
+ });
58
+
59
+ test("a merge result is listed with the pair of commits it was made of, newest pipeline first", async () => {
60
+ const host = await watched();
61
+ openMr(host);
62
+ const first = host.server.pipeline(host.billing, { sha: sha("topic-1"), ref: "refs/merge-requests/7/head", source: "merge_request_event" });
63
+ const mergeSha = sha("merge-result-1");
64
+ host.billing.commits.set(mergeSha, [sha("main-1"), sha("topic-1")]);
65
+ const second = host.server.pipeline(host.billing, { sha: mergeSha, ref: "refs/merge-requests/7/merge", source: "merge_request_event" });
66
+ await syncAll(host);
67
+ const [listed] = (await host.niwa.call(forgePrList, {})).items;
68
+ expect(listed?.pipelines.map((one) => one.pipeline)).toEqual([second.id, first.id]);
69
+ expect(listed?.pipelines[0]).toEqual({ pipeline: second.id, kind: "merge-result", state: "running", sourceSha: sha("topic-1"), targetSha: sha("main-1"), mergeSha });
70
+ });
71
+
72
+ test("a pipeline of no pull request is not listed under one, and only the latest ones are kept", async () => {
73
+ const host = await watched();
74
+ openMr(host);
75
+ host.server.pipeline(host.billing, { sha: sha("main-1"), ref: "main", source: "push" });
76
+ const made = Array.from({ length: PIPELINES_SHOWN + 2 }, (_, at) =>
77
+ host.server.pipeline(host.billing, { sha: sha("topic-1"), ref: `refs/merge-requests/7/head`, source: "merge_request_event", status: at % 2 === 0 ? "success" : "failed" }),
78
+ );
79
+ await syncAll(host);
80
+ const [listed] = (await host.niwa.call(forgePrList, {})).items;
81
+ expect(listed?.pipelines).toHaveLength(PIPELINES_SHOWN);
82
+ expect(listed?.pipelines[0]?.pipeline).toBe(made.at(-1)?.id);
83
+ });
84
+
85
+ test("a title, a base and a draft flag that changed are read as they stand now", async () => {
86
+ const host = await watched();
87
+ const mr = openMr(host);
88
+ await syncAll(host);
89
+ Object.assign(mr, { title: "Draft: rework", target_branch: "release", draft: true });
90
+ await syncAll(host);
91
+ const [listed] = (await host.niwa.call(forgePrList, {})).items;
92
+ expect(listed).toMatchObject({ title: "Draft: rework", base: "release", draft: true, state: "open" });
93
+ });
94
+
95
+ test("the open ones come first, then the latest changed, and a filter keeps a repository or a state", async () => {
96
+ const host = await watched();
97
+ openMr(host, 7);
98
+ openMr(host, 8, "topic-8");
99
+ openMr(host, 3, "topic-3", host.payroll);
100
+ await syncAll(host);
101
+ Object.assign(host.billing.mrs.get(7)!, { state: "merged", merge_commit_sha: sha("merge-7") });
102
+ host.server.event(host.billing, { action_name: "accepted", target_type: "MergeRequest", target_iid: 7 });
103
+ await syncAll(host);
104
+
105
+ const all = (await host.niwa.call(forgePrList, {})).items.map((one) => [one.pr.repo.path, one.pr.number, one.state]);
106
+ expect(all).toEqual([
107
+ ["acme/payroll", 3, "open"],
108
+ ["acme/billing", 8, "open"],
109
+ ["acme/billing", 7, "merged"],
110
+ ]);
111
+ expect((await host.niwa.call(forgePrList, { repo: BILLING })).items.map((one) => one.pr.number)).toEqual([8, 7]);
112
+ expect((await host.niwa.call(forgePrList, { state: "merged" })).items.map((one) => one.pr.number)).toEqual([7]);
113
+ expect((await host.niwa.call(forgePrList, { repo: PAYROLL, state: "merged" })).items).toEqual([]);
114
+ });
115
+
116
+ test("a pull request closed without a merge is listed as closed", async () => {
117
+ const host = await watched();
118
+ openMr(host);
119
+ host.server.event(host.billing, { action_name: "opened", target_type: "MergeRequest", target_iid: 7 });
120
+ await syncAll(host);
121
+ host.billing.mrs.get(7)!.state = "closed";
122
+ host.server.event(host.billing, { action_name: "closed", target_type: "MergeRequest", target_iid: 7 });
123
+ await syncAll(host);
124
+ expect((await host.niwa.call(forgePrList, {})).items.map((one) => one.state)).toEqual(["closed"]);
125
+ });