-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpreview-controller.test.ts
More file actions
629 lines (552 loc) · 18.3 KB
/
Copy pathpreview-controller.test.ts
File metadata and controls
629 lines (552 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
import assert from "node:assert/strict";
import { afterEach, beforeEach, describe, it } from "node:test";
import {
assess,
inventory,
TEARDOWN_REQUESTED_DESCRIPTION,
create,
finalize,
inactivate,
PREVIEW_LABEL,
recheck,
type GitHubApi,
resolve,
retire,
} from "./preview-controller.ts";
const originalEnvironment = { ...process.env };
const pull = {
state: "open",
draft: false,
html_url: "https://github.example/owner/repo/pull/7",
title: "Preview test",
author_association: "COLLABORATOR",
labels: [{ name: PREVIEW_LABEL }],
base: { ref: "main" },
head: { ref: "feature", sha: "head-sha", repo: { full_name: "owner/repo" } },
};
const unlabelled = { ...pull, labels: [{ name: "enhancement" }] };
const makeCore = () => {
const outputs = new Map<string, string>();
const failures: string[] = [];
const notices: string[] = [];
return {
outputs,
failures,
notices,
notice: (message: string) => notices.push(message),
setFailed: (message: string) => failures.push(message),
setOutput: (name: string, value: string) => outputs.set(name, value),
};
};
const makeContext = () => ({
repo: { owner: "owner", repo: "repo" },
payload: { repository: { default_branch: "main" }, pull_request: { number: 7 } },
});
type Deployment = { environment: string; id: number; sha: string };
type Status = { description?: string | null; state: string };
interface GitHubOptions {
deployments?: Deployment[];
files?: { filename: string }[];
resolvedPull?: typeof pull;
statuses?: Record<number, Status[]>;
defaultStatuses?: Status[];
}
const makeGitHub = ({
deployments = [{ environment: "preview/pr-7", id: 1, sha: "old-sha" }],
files = [],
resolvedPull = pull,
statuses = {},
defaultStatuses = [],
}: GitHubOptions = {}): GitHubApi => ({
paginate: async <T>(
endpoint: (params: Record<string, unknown>) => Promise<{ data: T[] }>,
params: Record<string, unknown>,
) => (await endpoint(params)).data,
rest: {
pulls: {
get: () => Promise.resolve({ data: resolvedPull }),
},
repos: {
compareCommitsWithBasehead: (params) => {
// The whole stack, not this layer's diff: always default branch to head SHA.
assert.equal(params.basehead, `main...${resolvedPull.head.sha}`);
return Promise.resolve({ data: { files } });
},
createDeployment: () =>
Promise.resolve({ data: { environment: "preview/pr-7", id: 2, sha: "head-sha" } }),
createDeploymentStatus: () => Promise.resolve({ data: {} }),
deleteDeployment: () => Promise.resolve({ data: {} }),
listDeployments: (params) =>
Promise.resolve({
data:
typeof params.environment === "string"
? deployments.filter((entry) => entry.environment === params.environment)
: deployments,
}),
listDeploymentStatuses: (params) =>
Promise.resolve({ data: statuses[Number(params.deployment_id)] ?? defaultStatuses }),
},
},
});
beforeEach(() => {
Object.assign(process.env, {
COOLIFY_URL: "https://coolify.example",
COOLIFY_PREVIEW_URL_TEMPLATE: "https://pr{pr}.example",
});
});
afterEach(() => {
process.env = { ...originalEnvironment };
});
void describe("preview controller admission", () => {
void it("deploys an opted-in head with current successful CI", async () => {
const core = makeCore();
await resolve({ github: makeGitHub(), context: makeContext(), core });
assert.equal(core.outputs.get("eligible"), "true");
assert.equal(core.outputs.get("head_sha"), "head-sha");
assert.equal(core.outputs.get("environment"), "preview/pr-7");
assert.equal(core.outputs.get("preview_url"), "https://pr7.example/");
});
void it("stays silent on a pull request that never opted in", async () => {
const core = makeCore();
await resolve({
github: makeGitHub({ resolvedPull: unlabelled }),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("eligible"), "false");
assert.equal(core.outputs.get("announce"), "false");
});
void it("explains a fork instead of handing it deployment credentials", async () => {
const core = makeCore();
await resolve({
github: makeGitHub({
resolvedPull: { ...pull, head: { ...pull.head, repo: { full_name: "contributor/fork" } } },
}),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("eligible"), "false");
assert.equal(core.outputs.get("announce"), "true");
assert.match(core.outputs.get("reason") ?? "", /fork/);
});
void it("waits for a draft to be marked ready for review", async () => {
const core = makeCore();
await resolve({
github: makeGitHub({ resolvedPull: { ...pull, draft: true } }),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("eligible"), "false");
assert.match(core.outputs.get("reason") ?? "", /draft/);
});
void it("refuses PR-controlled changes to any part of the deployment control plane", async () => {
for (const filename of [
".github/workflows/reusable-docker-build.yml",
".github/actions/setup-bun/action.yml",
"docker/preview/compose.app.yaml",
"docker/preview/.env.example",
]) {
const core = makeCore();
await resolve({
github: makeGitHub({ files: [{ filename }] }),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("eligible"), "false", filename);
assert.match(core.outputs.get("reason") ?? "", /trusted deployment policy/, filename);
}
});
void it("refuses a comparison too large for GitHub to report in full", async () => {
const core = makeCore();
await resolve({
github: makeGitHub({
files: Array.from({ length: 300 }, (_unused, index) => ({ filename: `src/f${index}.ts` })),
}),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("eligible"), "false");
assert.match(core.outputs.get("reason") ?? "", /deployment policy cannot be verified/);
});
void it("deploys a stacked layer, whose base is another pull request's branch", async () => {
const core = makeCore();
await resolve({
github: makeGitHub({ resolvedPull: { ...pull, base: { ref: "feat/layer-1" } } }),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("eligible"), "true");
// Coolify picks its application by this ref, and that application tracks the default branch.
assert.equal(core.outputs.get("base_ref"), "main");
});
void it("skips a pull request whose author is not a repository collaborator", async () => {
const core = makeCore();
await resolve({
github: makeGitHub({ resolvedPull: { ...pull, author_association: "CONTRIBUTOR" } }),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("eligible"), "false");
assert.match(core.outputs.get("reason") ?? "", /not a repository collaborator/);
});
void it("refuses a preview URL template that cannot name the pull request", async () => {
process.env.COOLIFY_PREVIEW_URL_TEMPLATE = "https://preview.example";
await assert.rejects(
resolve({ github: makeGitHub(), context: makeContext(), core: makeCore() }),
/must contain \{pr\}/,
);
});
void it("keeps quiet when the current head is already deployed", async () => {
const core = makeCore();
await resolve({
github: makeGitHub({
deployments: [{ environment: "preview/pr-7", id: 2, sha: "head-sha" }],
statuses: { 2: [{ state: "success" }] },
}),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("eligible"), "false");
assert.equal(core.outputs.get("announce"), "false");
});
});
void describe("preview host capacity", () => {
const occupants = (count: number): Deployment[] =>
Array.from({ length: count }, (_unused, index) => ({
environment: `preview/pr-${100 + index}`,
id: 100 + index,
sha: `head-${index}`,
}));
void it("names the occupants when the host is full", async () => {
const core = makeCore();
await resolve({
github: makeGitHub({ deployments: occupants(3) }),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("eligible"), "false");
assert.equal(core.outputs.get("announce"), "true");
assert.match(core.outputs.get("reason") ?? "", /#100, #101, #102/);
});
void it("keeps updating a preview that already holds a slot on a full host", async () => {
const core = makeCore();
await resolve({
github: makeGitHub({
deployments: [...occupants(2), { environment: "preview/pr-7", id: 1, sha: "old-sha" }],
}),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("eligible"), "true");
});
void it("does not count a verified cleanup tombstone against the host", async () => {
const core = makeCore();
await resolve({
github: makeGitHub({
deployments: occupants(3),
statuses: {
102: [{ description: TEARDOWN_REQUESTED_DESCRIPTION, state: "inactive" }],
},
}),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("eligible"), "true");
});
void it("sweeps only the previews that still hold a slot", async () => {
const core = makeCore();
await inventory({
github: makeGitHub({
deployments: occupants(3),
// pr-102's teardown was recorded, so re-sending its close event would ask Coolify to
// remove a stack that is already gone — and would spend the sweep's bound doing it.
statuses: {
102: [{ description: TEARDOWN_REQUESTED_DESCRIPTION, state: "inactive" }],
},
}),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("previews"), JSON.stringify([100, 101]));
});
void it("still counts a preview whose cleanup was never verified", async () => {
const core = makeCore();
await resolve({
github: makeGitHub({
deployments: occupants(3),
statuses: { 102: [{ description: "Superseded", state: "inactive" }] },
}),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("eligible"), "false");
});
void it("honours a configured host limit", async () => {
process.env.PREVIEW_MAX_ACTIVE = "1";
const core = makeCore();
await resolve({
github: makeGitHub({ deployments: occupants(1) }),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("eligible"), "false");
assert.match(core.outputs.get("reason") ?? "", /1\/1/);
});
});
void it("registers GitHub deployments against the immutable head SHA", async () => {
Object.assign(process.env, {
HEAD_SHA: "head-sha",
ENVIRONMENT: "preview/pr-7",
PR_NUMBER: "7",
PREVIEW_URL: "https://pr7.example",
SOURCE_RUN_URL: "https://github.example/runs/50",
});
let deploymentRef = "";
let initialState = "";
const baseGitHub = makeGitHub();
const github: GitHubApi = {
...baseGitHub,
rest: {
...baseGitHub.rest,
repos: {
...baseGitHub.rest.repos,
createDeploymentStatus: (params: Record<string, unknown>) => {
initialState = String(params.state);
return Promise.resolve({ data: {} });
},
createDeployment: (params: Record<string, unknown>) => {
deploymentRef = String(params.ref);
assert.equal(params.task, "deploy:preview");
assert.equal(params.transient_environment, true);
return Promise.resolve({
data: { environment: "preview/pr-7", id: 2, sha: "head-sha" },
});
},
},
},
};
const core = makeCore();
await create({ github, context: makeContext(), core });
assert.equal(deploymentRef, "head-sha");
assert.equal(initialState, "queued");
assert.equal(core.outputs.get("deployment_id"), "2");
});
void it("stands down without failing when the head moved during preflight", async () => {
Object.assign(process.env, { HEAD_SHA: "head-sha", PR_NUMBER: "7" });
const core = makeCore();
await recheck({
github: makeGitHub({ resolvedPull: { ...pull, head: { ...pull.head, sha: "pushed-sha" } } }),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("proceed"), "false");
assert.deepEqual(core.failures, []);
});
void it("stands down without failing when the label was removed during preflight", async () => {
Object.assign(process.env, { HEAD_SHA: "head-sha", PR_NUMBER: "7" });
const core = makeCore();
await recheck({ github: makeGitHub({ resolvedPull: unlabelled }), context: makeContext(), core });
assert.equal(core.outputs.get("proceed"), "false");
assert.deepEqual(core.failures, []);
});
void it("fails if the head stopped being a branch in this repository during preflight", async () => {
Object.assign(process.env, { HEAD_SHA: "head-sha", PR_NUMBER: "7" });
const core = makeCore();
await recheck({
github: makeGitHub({
resolvedPull: { ...pull, head: { ...pull.head, repo: { full_name: "contributor/fork" } } },
}),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("proceed"), undefined);
assert.equal(core.failures.length, 1);
});
void it("lets a stacked layer through preflight", async () => {
Object.assign(process.env, { HEAD_SHA: "head-sha", PR_NUMBER: "7" });
const core = makeCore();
await recheck({
github: makeGitHub({ resolvedPull: { ...pull, base: { ref: "feat/layer-1" } } }),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("proceed"), "true");
});
void it("lets an unchanged, still-labelled head through", async () => {
Object.assign(process.env, { HEAD_SHA: "head-sha", PR_NUMBER: "7" });
const core = makeCore();
await recheck({ github: makeGitHub(), context: makeContext(), core });
assert.equal(core.outputs.get("proceed"), "true");
});
void it("marks a successful deployment and explicitly inactivates its predecessor", async () => {
Object.assign(process.env, {
DEPLOYMENT_ID: "2",
DESCRIPTION: "Preview ready",
ENVIRONMENT: "preview/pr-7",
FINAL_STATE: "success",
LOG_URL: "https://coolify.example/logs/2",
PREVIEW_URL: "https://pr7.example",
PR_NUMBER: "7",
SOURCE_RUN_URL: "https://github.example/runs/50",
});
const statuses: Record<string, unknown>[] = [];
const deleted: number[] = [];
const baseGitHub = makeGitHub({
deployments: [
{ environment: "preview/pr-7", id: 2, sha: "head-sha" },
{ environment: "preview/pr-7", id: 1, sha: "old" },
],
});
const github: GitHubApi = {
...baseGitHub,
rest: {
...baseGitHub.rest,
repos: {
...baseGitHub.rest.repos,
createDeploymentStatus: (parameters) => {
statuses.push(parameters);
return Promise.resolve({ data: {} });
},
deleteDeployment: (parameters) => {
deleted.push(Number(parameters.deployment_id));
return Promise.resolve({ data: {} });
},
},
},
};
await finalize({ github, context: makeContext(), core: makeCore() });
assert.deepEqual(
statuses.map((status) => [status.deployment_id, status.state]),
[
[2, "success"],
[1, "inactive"],
],
);
assert.deepEqual(deleted, [1]);
});
void it("lets cleanup own the final state when the preview opted out mid-deployment", async () => {
Object.assign(process.env, {
DEPLOYMENT_ID: "2",
DESCRIPTION: "Preview ready",
ENVIRONMENT: "preview/pr-7",
FINAL_STATE: "success",
LOG_URL: "https://coolify.example/logs/2",
PREVIEW_URL: "https://pr7.example",
PR_NUMBER: "7",
SOURCE_RUN_URL: "https://github.example/runs/50",
});
const statuses: Record<string, unknown>[] = [];
const baseGitHub = makeGitHub({ resolvedPull: unlabelled });
const github: GitHubApi = {
...baseGitHub,
rest: {
...baseGitHub.rest,
repos: {
...baseGitHub.rest.repos,
createDeploymentStatus: (parameters) => {
statuses.push(parameters);
return Promise.resolve({ data: {} });
},
},
},
};
await finalize({ github, context: makeContext(), core: makeCore() });
assert.equal(statuses.length, 1);
assert.equal(statuses[0]?.state, "inactive");
});
void it("retires deployment records only after marking them inactive", async () => {
Object.assign(process.env, { ENVIRONMENT: "preview/pr-7" });
const operations: string[] = [];
const baseGitHub = makeGitHub({
deployments: [{ environment: "preview/pr-7", id: 1, sha: "old" }],
defaultStatuses: [{ state: "success" }],
});
const github: GitHubApi = {
...baseGitHub,
rest: {
...baseGitHub.rest,
repos: {
...baseGitHub.rest.repos,
createDeploymentStatus: () => {
operations.push("inactive");
return Promise.resolve({ data: {} });
},
deleteDeployment: () => {
operations.push("delete");
return Promise.resolve({ data: {} });
},
},
},
};
await retire({ github, context: makeContext(), core: makeCore() });
assert.deepEqual(operations, ["inactive", "delete"]);
});
void it("keeps the verified tombstone record when cleanup inactivates a preview", async () => {
Object.assign(process.env, { ENVIRONMENT: "preview/pr-7" });
const descriptions: string[] = [];
let deletions = 0;
const baseGitHub = makeGitHub({
deployments: [{ environment: "preview/pr-7", id: 1, sha: "old" }],
defaultStatuses: [{ state: "inactive" }],
});
const github: GitHubApi = {
...baseGitHub,
rest: {
...baseGitHub.rest,
repos: {
...baseGitHub.rest.repos,
createDeploymentStatus: (parameters) => {
descriptions.push(String(parameters.description));
return Promise.resolve({ data: {} });
},
deleteDeployment: () => {
deletions += 1;
return Promise.resolve({ data: {} });
},
},
},
};
await inactivate({ github, context: makeContext(), core: makeCore() });
assert.deepEqual(descriptions, [TEARDOWN_REQUESTED_DESCRIPTION]);
assert.equal(deletions, 0);
});
void describe("reconcile staleness", () => {
beforeEach(() => {
process.env.PR_NUMBER = "7";
});
void it("leaves an open, labelled, ready pull request alone", async () => {
const core = makeCore();
await assess({ github: makeGitHub(), context: makeContext(), core });
assert.equal(core.outputs.get("stale"), "false");
assert.equal(core.outputs.get("url"), undefined);
});
void it("reclaims a preview whose pull request dropped the label", async () => {
const core = makeCore();
await assess({
github: makeGitHub({ resolvedPull: unlabelled }),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("stale"), "true");
assert.equal(core.outputs.get("head_sha"), "head-sha");
assert.equal(core.outputs.get("base_ref"), "main");
});
void it("reclaims a closed pull request", async () => {
const core = makeCore();
await assess({
github: makeGitHub({ resolvedPull: { ...pull, state: "closed" } }),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("stale"), "true");
});
void it("reclaims a pull request that went back to draft", async () => {
const core = makeCore();
await assess({
github: makeGitHub({ resolvedPull: { ...pull, draft: true } }),
context: makeContext(),
core,
});
assert.equal(core.outputs.get("stale"), "true");
});
});