@patronage/factory-ci 1.0.0-alpha.43 → 1.0.0-alpha.45
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.
- package/README.md +73 -5
- package/dist/.build-fingerprint.json +1 -1
- package/dist/alchemy/index.d.ts +7 -23
- package/dist/alchemy/index.js +12 -32
- package/dist/{bundle-alchemy-entry-CT5hCphA.js → bundle-alchemy-entry-BuMrl5fR.js} +3 -6
- package/dist/{execute-alchemy-entry-B397GSk5.d.ts → execute-alchemy-entry-BR5dFO9k.d.ts} +3 -6
- package/dist/{execute-alchemy-entry-C2ZhsNTN.js → execute-alchemy-entry-CDMdbXIi.js} +14 -8
- package/dist/index.d.ts +316 -51
- package/dist/index.js +611 -115
- package/package.json +4 -3
- package/src/actions.ts +0 -7
- package/src/alchemy/child-diagnostics.ts +1 -2
- package/src/alchemy/credential-preflight.ts +0 -9
- package/src/alchemy/destroy-postcondition.ts +1 -5
- package/src/alchemy/first-deploy-authorization.ts +1 -4
- package/src/alchemy/lifecycle.ts +0 -14
- package/src/alchemy/local-emulation.ts +4 -3
- package/src/alchemy/plan-effects.ts +1 -1
- package/src/alchemy/stage-policy.ts +3 -5
- package/src/alchemy/url-implies-auth.ts +1 -5
- package/src/alchemy-baseline.ts +27 -7
- package/src/bundle-alchemy-entry.ts +3 -6
- package/src/disposable-stage.ts +2 -3
- package/src/github-app-token.ts +3 -9
- package/src/index.ts +44 -0
- package/src/preview-cleanup-workflow.ts +422 -0
- package/src/preview-cleanup.ts +688 -0
- package/src/proof-reuse-gate.ts +43 -58
- package/src/proof-reuse-presentation.ts +0 -3
- package/src/push-identity-workflow.ts +1 -5
|
@@ -0,0 +1,688 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isLocalPreviewStage,
|
|
3
|
+
parseLocalPreviewStage,
|
|
4
|
+
} from "./disposable-stage.ts";
|
|
5
|
+
import { GitHubApiError } from "./github-app-token.ts";
|
|
6
|
+
import { githubJson } from "./github-transport.ts";
|
|
7
|
+
import type {
|
|
8
|
+
PreviewProofInventoryAccess,
|
|
9
|
+
PreviewProofInventoryStore,
|
|
10
|
+
} from "./preview-proof-inventory.ts";
|
|
11
|
+
import {
|
|
12
|
+
PreviewProofTransportError,
|
|
13
|
+
previewProofInventory,
|
|
14
|
+
} from "./preview-proof-inventory.ts";
|
|
15
|
+
import type {
|
|
16
|
+
PreviewProofCleanupStatus,
|
|
17
|
+
PreviewProofRegistration,
|
|
18
|
+
} from "./preview-proof-lifecycle.ts";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Closed-PR preview cleanup and the scheduled orphan sweep (#1540).
|
|
22
|
+
*
|
|
23
|
+
* This module owns the consumer-neutral decisions: which stages a closed PR
|
|
24
|
+
* left behind, which stages belong to PRs that are already closed, how a
|
|
25
|
+
* stack-scoped destroy outcome reaches the inventory, and whether a stage is
|
|
26
|
+
* still present afterwards. The consumer keeps its stack list, the destroy
|
|
27
|
+
* command, the residue reader, credentials and protected-stage policy.
|
|
28
|
+
*
|
|
29
|
+
* Every destructive target passes through the one disposable-stage grammar
|
|
30
|
+
* (`local-pr-<pr>-<sha>`) or the consumer's declared hosted grammar
|
|
31
|
+
* (`<prefix><pr>`). Anything else is retained, never destroyed.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
/** One `{ stack, stage }` row from the consumer's residue reader. */
|
|
35
|
+
export interface PreviewCleanupResidue {
|
|
36
|
+
readonly stack: string;
|
|
37
|
+
readonly stage: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** One stack-scoped destroy the cleanup workflow runs. */
|
|
41
|
+
export interface PreviewCleanupTarget {
|
|
42
|
+
/** Present when a registration supplied the head, so the record can bind it. */
|
|
43
|
+
readonly headSha?: string;
|
|
44
|
+
readonly pr: number;
|
|
45
|
+
readonly stack: string;
|
|
46
|
+
readonly stage: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface PreviewCleanupStackPolicy {
|
|
50
|
+
/**
|
|
51
|
+
* The consumer's hosted per-PR stage prefix, such as `"pr-"` for `pr-123`.
|
|
52
|
+
* Omit it when the consumer has no hosted per-PR stage.
|
|
53
|
+
*/
|
|
54
|
+
readonly hostedStagePrefix?: string;
|
|
55
|
+
/**
|
|
56
|
+
* Other names the inventory or the residue reader uses for a declared stack,
|
|
57
|
+
* mapped to that stack. A registration recorded as `preview-deploy-website`
|
|
58
|
+
* resolves to `website` with `{ "preview-deploy-website": "website" }`.
|
|
59
|
+
*/
|
|
60
|
+
readonly stackAliases?: Readonly<Record<string, string>>;
|
|
61
|
+
/** The stacks a cleanup destroys, in the consumer's own names. */
|
|
62
|
+
readonly stacks: readonly string[];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface DiscoverPreviewCleanupTargetsInput extends PreviewCleanupStackPolicy {
|
|
66
|
+
readonly pr: number;
|
|
67
|
+
/** Inventory registrations for the PR, from `previewProofInventory.list`. */
|
|
68
|
+
readonly registrations: readonly PreviewProofRegistration[];
|
|
69
|
+
readonly residue: readonly PreviewCleanupResidue[];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export type PreviewCleanupPullRequestState = "closed" | "open";
|
|
73
|
+
|
|
74
|
+
export interface DiscoverOrphanedPreviewCleanupTargetsInput extends PreviewCleanupStackPolicy {
|
|
75
|
+
/**
|
|
76
|
+
* Targets per run; the rest wait for the next sweep. Default 50. A stage's
|
|
77
|
+
* targets across its stacks are taken whole, so a run exceeds the cap only
|
|
78
|
+
* when its first stage alone has more stacks than the cap.
|
|
79
|
+
*/
|
|
80
|
+
readonly maxTargets?: number;
|
|
81
|
+
/**
|
|
82
|
+
* The state GitHub reported for each PR the residue names. A PR missing
|
|
83
|
+
* from the map is unknown, and its stages are retained.
|
|
84
|
+
*/
|
|
85
|
+
readonly pullRequestStates: ReadonlyMap<
|
|
86
|
+
number,
|
|
87
|
+
PreviewCleanupPullRequestState
|
|
88
|
+
>;
|
|
89
|
+
readonly residue: readonly PreviewCleanupResidue[];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface PreviewCleanupSweep {
|
|
93
|
+
/**
|
|
94
|
+
* Orphaned targets left for the next sweep. A stage is never split: all of
|
|
95
|
+
* its stacks are taken or all are deferred.
|
|
96
|
+
*/
|
|
97
|
+
readonly deferred: number;
|
|
98
|
+
readonly targets: readonly PreviewCleanupTarget[];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface RecordPreviewCleanupOutcomeInput {
|
|
102
|
+
readonly evidence: readonly string[];
|
|
103
|
+
readonly headSha?: string;
|
|
104
|
+
readonly outcome: Exclude<PreviewProofCleanupStatus, "pending">;
|
|
105
|
+
readonly owner: string;
|
|
106
|
+
readonly pr: number;
|
|
107
|
+
readonly repo: string;
|
|
108
|
+
readonly runUrl?: string;
|
|
109
|
+
readonly stack: string;
|
|
110
|
+
readonly stackAliases?: Readonly<Record<string, string>>;
|
|
111
|
+
readonly stage: string;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface RecordPreviewCleanupOutcomeAccess {
|
|
115
|
+
/**
|
|
116
|
+
* Lists registrations. A workflow `GITHUB_TOKEN` with
|
|
117
|
+
* `PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS`: the Factory App token has no
|
|
118
|
+
* contents permission and cannot serve the list (#825).
|
|
119
|
+
*/
|
|
120
|
+
readonly read: PreviewProofInventoryAccess;
|
|
121
|
+
/** Writes the outcome. A Factory App installation token. */
|
|
122
|
+
readonly write: PreviewProofInventoryAccess;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export type RecordPreviewCleanupOutcomeResult =
|
|
126
|
+
| {
|
|
127
|
+
/** Destroyed but never registered: inventory residue or a hosted stage. */
|
|
128
|
+
readonly kind: "unregistered";
|
|
129
|
+
}
|
|
130
|
+
| {
|
|
131
|
+
readonly kind: "recorded" | "recovered";
|
|
132
|
+
readonly registration: PreviewProofRegistration;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
export interface ReadPullRequestStatesInput {
|
|
136
|
+
readonly owner: string;
|
|
137
|
+
readonly prs: readonly number[];
|
|
138
|
+
readonly repo: string;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export interface ReadPullRequestStatesAccess {
|
|
142
|
+
readonly fetch?: typeof fetch;
|
|
143
|
+
readonly timeoutMs?: number;
|
|
144
|
+
/** Needs `pull-requests: read`. */
|
|
145
|
+
readonly token: string;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const DEFAULT_SWEEP_MAX_TARGETS = 50;
|
|
149
|
+
/** GitHub refuses a matrix with more than 256 entries. */
|
|
150
|
+
const MATRIX_ENTRY_LIMIT = 256;
|
|
151
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
152
|
+
const PULL_STATE_CONCURRENCY = 8;
|
|
153
|
+
const STACK_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/u;
|
|
154
|
+
const HOSTED_STAGE_PREFIX_PATTERN = /^[a-z][a-z0-9-]*-$/u;
|
|
155
|
+
const OUTPUT_KEY_UNSAFE = /[^a-z0-9_]+/gu;
|
|
156
|
+
const FULL_SHA_PATTERN = /^[0-9a-f]{40}$/u;
|
|
157
|
+
|
|
158
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
159
|
+
typeof value === "object" && value !== null;
|
|
160
|
+
|
|
161
|
+
/** The GitHub-output key a stack's matrix and presence flag use. */
|
|
162
|
+
export const previewCleanupStackOutputKey = (stack: string): string => {
|
|
163
|
+
const key = stack
|
|
164
|
+
.toLowerCase()
|
|
165
|
+
.replaceAll(OUTPUT_KEY_UNSAFE, "_")
|
|
166
|
+
.replaceAll(/^_+|_+$/gu, "");
|
|
167
|
+
if (key.length === 0) {
|
|
168
|
+
throw new Error(`Cleanup stack "${stack}" has no output-safe characters.`);
|
|
169
|
+
}
|
|
170
|
+
return key;
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Validate a stack policy. Throws on an empty or duplicate stack list, a
|
|
175
|
+
* stack name a shell or GitHub output could misread, an alias to an
|
|
176
|
+
* undeclared stack, or a hosted prefix that is not `<word>-`.
|
|
177
|
+
*/
|
|
178
|
+
export const assertPreviewCleanupStackPolicy = (
|
|
179
|
+
policy: PreviewCleanupStackPolicy
|
|
180
|
+
): void => {
|
|
181
|
+
if (policy.stacks.length === 0) {
|
|
182
|
+
throw new Error("Preview cleanup requires at least one stack.");
|
|
183
|
+
}
|
|
184
|
+
for (const stack of policy.stacks) {
|
|
185
|
+
if (!STACK_NAME_PATTERN.test(stack)) {
|
|
186
|
+
throw new Error(
|
|
187
|
+
`Cleanup stack "${stack}" must match ${STACK_NAME_PATTERN.source}.`
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (new Set(policy.stacks).size !== policy.stacks.length) {
|
|
192
|
+
throw new Error("Cleanup stacks must be distinct.");
|
|
193
|
+
}
|
|
194
|
+
const keys = policy.stacks.map(previewCleanupStackOutputKey);
|
|
195
|
+
if (new Set(keys).size !== keys.length) {
|
|
196
|
+
throw new Error("Cleanup stacks must map to distinct output keys.");
|
|
197
|
+
}
|
|
198
|
+
for (const [alias, stack] of Object.entries(policy.stackAliases ?? {})) {
|
|
199
|
+
if (!STACK_NAME_PATTERN.test(alias)) {
|
|
200
|
+
throw new Error(
|
|
201
|
+
`Cleanup stack alias "${alias}" must match ${STACK_NAME_PATTERN.source}.`
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
if (!policy.stacks.includes(stack)) {
|
|
205
|
+
throw new Error(
|
|
206
|
+
`Cleanup stack alias "${alias}" names undeclared stack "${stack}".`
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
if (
|
|
211
|
+
policy.hostedStagePrefix !== undefined &&
|
|
212
|
+
(!HOSTED_STAGE_PREFIX_PATTERN.test(policy.hostedStagePrefix) ||
|
|
213
|
+
policy.hostedStagePrefix.startsWith("local-"))
|
|
214
|
+
) {
|
|
215
|
+
throw new Error(
|
|
216
|
+
`hostedStagePrefix must look like "pr-" and must not overlap the disposable local grammar, got "${policy.hostedStagePrefix}".`
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
const resolveStack = (
|
|
222
|
+
policy: PreviewCleanupStackPolicy,
|
|
223
|
+
stack: string
|
|
224
|
+
): string | undefined => {
|
|
225
|
+
if (policy.stacks.includes(stack)) {
|
|
226
|
+
return stack;
|
|
227
|
+
}
|
|
228
|
+
const aliased = policy.stackAliases?.[stack];
|
|
229
|
+
return aliased !== undefined && policy.stacks.includes(aliased)
|
|
230
|
+
? aliased
|
|
231
|
+
: undefined;
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
/** The PR a hosted stage belongs to, or `null` when it is not one. */
|
|
235
|
+
export const parseHostedPreviewStage = (
|
|
236
|
+
stage: string,
|
|
237
|
+
prefix: string
|
|
238
|
+
): number | null => {
|
|
239
|
+
if (!stage.startsWith(prefix)) {
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
const digits = stage.slice(prefix.length);
|
|
243
|
+
if (!/^[1-9]\d*$/u.test(digits)) {
|
|
244
|
+
return null;
|
|
245
|
+
}
|
|
246
|
+
const pr = Number(digits);
|
|
247
|
+
return Number.isSafeInteger(pr) ? pr : null;
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
/** The PR that owns a disposable stage, or `null` when it is not disposable. */
|
|
251
|
+
const disposableStageOwner = (
|
|
252
|
+
policy: PreviewCleanupStackPolicy,
|
|
253
|
+
stage: string
|
|
254
|
+
): number | null =>
|
|
255
|
+
parseLocalPreviewStage(stage)?.pr ??
|
|
256
|
+
(policy.hostedStagePrefix === undefined
|
|
257
|
+
? null
|
|
258
|
+
: parseHostedPreviewStage(stage, policy.hostedStagePrefix));
|
|
259
|
+
|
|
260
|
+
const targetKey = (target: Pick<PreviewCleanupTarget, "stack" | "stage">) =>
|
|
261
|
+
`${target.stack}\u0000${target.stage}`;
|
|
262
|
+
|
|
263
|
+
const compareTargets = (
|
|
264
|
+
left: PreviewCleanupTarget,
|
|
265
|
+
right: PreviewCleanupTarget
|
|
266
|
+
): number =>
|
|
267
|
+
left.pr - right.pr ||
|
|
268
|
+
left.stack.localeCompare(right.stack) ||
|
|
269
|
+
left.stage.localeCompare(right.stage);
|
|
270
|
+
|
|
271
|
+
const assertPositivePr = (pr: number): void => {
|
|
272
|
+
if (!Number.isSafeInteger(pr) || pr < 1) {
|
|
273
|
+
throw new Error(`Cleanup PR must be a positive integer, got ${pr}.`);
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Targets for one closed PR: its inventory registrations united with the
|
|
279
|
+
* residue the consumer still sees for it. Only the PR's own `local-pr-<pr>-*`
|
|
280
|
+
* stages and its hosted stage survive, in declared stacks. A registration
|
|
281
|
+
* wins a collision so its head SHA reaches the cleanup record. A registration
|
|
282
|
+
* whose cleanup already passed is skipped unless the residue still lists it.
|
|
283
|
+
*/
|
|
284
|
+
export const discoverPreviewCleanupTargets = (
|
|
285
|
+
input: DiscoverPreviewCleanupTargetsInput
|
|
286
|
+
): readonly PreviewCleanupTarget[] => {
|
|
287
|
+
assertPreviewCleanupStackPolicy(input);
|
|
288
|
+
assertPositivePr(input.pr);
|
|
289
|
+
const hostedStage =
|
|
290
|
+
input.hostedStagePrefix === undefined
|
|
291
|
+
? undefined
|
|
292
|
+
: `${input.hostedStagePrefix}${input.pr}`;
|
|
293
|
+
const byKey = new Map<string, PreviewCleanupTarget>();
|
|
294
|
+
const residueKeys = new Set(
|
|
295
|
+
input.residue.flatMap((row) => {
|
|
296
|
+
const stack = resolveStack(input, row.stack);
|
|
297
|
+
return stack === undefined
|
|
298
|
+
? []
|
|
299
|
+
: [targetKey({ stack, stage: row.stage })];
|
|
300
|
+
})
|
|
301
|
+
);
|
|
302
|
+
|
|
303
|
+
for (const row of input.registrations) {
|
|
304
|
+
const stack = resolveStack(input, row.stack);
|
|
305
|
+
// A passed cleanup is settled: re-destroying it would overwrite that
|
|
306
|
+
// evidence, and fail it if the consumer's destroy refuses an absent
|
|
307
|
+
// stage. Residue still listing the stage reopens it.
|
|
308
|
+
const settled =
|
|
309
|
+
stack !== undefined &&
|
|
310
|
+
row.cleanup.outcome === "passed" &&
|
|
311
|
+
!residueKeys.has(targetKey({ stack, stage: row.stage }));
|
|
312
|
+
if (
|
|
313
|
+
row.pr === input.pr &&
|
|
314
|
+
stack !== undefined &&
|
|
315
|
+
!settled &&
|
|
316
|
+
isLocalPreviewStage(row.stage, input.pr)
|
|
317
|
+
) {
|
|
318
|
+
const target = {
|
|
319
|
+
headSha: row.headSha,
|
|
320
|
+
pr: input.pr,
|
|
321
|
+
stack,
|
|
322
|
+
stage: row.stage,
|
|
323
|
+
};
|
|
324
|
+
byKey.set(targetKey(target), target);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
for (const row of input.residue) {
|
|
328
|
+
const stack = resolveStack(input, row.stack);
|
|
329
|
+
if (
|
|
330
|
+
stack !== undefined &&
|
|
331
|
+
(isLocalPreviewStage(row.stage, input.pr) || row.stage === hostedStage)
|
|
332
|
+
) {
|
|
333
|
+
const target = { pr: input.pr, stack, stage: row.stage };
|
|
334
|
+
if (!byKey.has(targetKey(target))) {
|
|
335
|
+
byKey.set(targetKey(target), target);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
return Object.freeze([...byKey.values()].toSorted(compareTargets));
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* The PRs whose disposable stages appear in the residue. The sweep reads
|
|
345
|
+
* their state before it decides anything.
|
|
346
|
+
*/
|
|
347
|
+
export const previewCleanupResiduePullRequests = (
|
|
348
|
+
policy: PreviewCleanupStackPolicy,
|
|
349
|
+
residue: readonly PreviewCleanupResidue[]
|
|
350
|
+
): readonly number[] => {
|
|
351
|
+
assertPreviewCleanupStackPolicy(policy);
|
|
352
|
+
const prs = new Set<number>();
|
|
353
|
+
for (const row of residue) {
|
|
354
|
+
const pr =
|
|
355
|
+
resolveStack(policy, row.stack) === undefined
|
|
356
|
+
? null
|
|
357
|
+
: disposableStageOwner(policy, row.stage);
|
|
358
|
+
if (pr !== null) {
|
|
359
|
+
prs.add(pr);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return Object.freeze([...prs].toSorted((left, right) => left - right));
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Targets for the scheduled sweep: disposable residue whose PR GitHub
|
|
367
|
+
* reports closed. It fails closed. A stage that does not parse as disposable,
|
|
368
|
+
* a stack the consumer did not declare, and a PR that is open or whose state
|
|
369
|
+
* is unknown are all retained.
|
|
370
|
+
*/
|
|
371
|
+
export const discoverOrphanedPreviewCleanupTargets = (
|
|
372
|
+
input: DiscoverOrphanedPreviewCleanupTargetsInput
|
|
373
|
+
): PreviewCleanupSweep => {
|
|
374
|
+
assertPreviewCleanupStackPolicy(input);
|
|
375
|
+
const maxTargets = input.maxTargets ?? DEFAULT_SWEEP_MAX_TARGETS;
|
|
376
|
+
if (
|
|
377
|
+
!Number.isInteger(maxTargets) ||
|
|
378
|
+
maxTargets < 1 ||
|
|
379
|
+
maxTargets > MATRIX_ENTRY_LIMIT
|
|
380
|
+
) {
|
|
381
|
+
throw new Error(
|
|
382
|
+
`maxTargets must be an integer from 1 through ${MATRIX_ENTRY_LIMIT}, got ${maxTargets}.`
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const byKey = new Map<string, PreviewCleanupTarget>();
|
|
387
|
+
for (const row of input.residue) {
|
|
388
|
+
const stack = resolveStack(input, row.stack);
|
|
389
|
+
const pr = disposableStageOwner(input, row.stage);
|
|
390
|
+
if (
|
|
391
|
+
stack !== undefined &&
|
|
392
|
+
pr !== null &&
|
|
393
|
+
input.pullRequestStates.get(pr) === "closed"
|
|
394
|
+
) {
|
|
395
|
+
const target = { pr, stack, stage: row.stage };
|
|
396
|
+
byKey.set(targetKey(target), target);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// The audit matches residue on the stage alone, so a stage is taken or
|
|
401
|
+
// deferred whole across its stacks. The first stage always goes, so a
|
|
402
|
+
// stage with more stacks than the cap still drains.
|
|
403
|
+
const byStage = new Map<string, PreviewCleanupTarget[]>();
|
|
404
|
+
for (const target of [...byKey.values()].toSorted(compareTargets)) {
|
|
405
|
+
byStage.set(target.stage, [...(byStage.get(target.stage) ?? []), target]);
|
|
406
|
+
}
|
|
407
|
+
const taken: PreviewCleanupTarget[] = [];
|
|
408
|
+
let deferred = 0;
|
|
409
|
+
for (const group of byStage.values()) {
|
|
410
|
+
if (
|
|
411
|
+
deferred === 0 &&
|
|
412
|
+
(taken.length === 0 || taken.length + group.length <= maxTargets)
|
|
413
|
+
) {
|
|
414
|
+
taken.push(...group);
|
|
415
|
+
} else {
|
|
416
|
+
deferred += group.length;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
return Object.freeze({ deferred, targets: Object.freeze(taken) });
|
|
420
|
+
};
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* The `$GITHUB_OUTPUT` lines the cleanup workflow's discover job publishes:
|
|
424
|
+
* `has_targets`, `targets`, and for each declared stack `has_<key>` and
|
|
425
|
+
* `<key>_matrix`. A stack with no target still gets `has_<key>=false`, so
|
|
426
|
+
* its destroy job skips instead of expanding an empty matrix.
|
|
427
|
+
*/
|
|
428
|
+
export const previewCleanupGithubOutput = (
|
|
429
|
+
policy: PreviewCleanupStackPolicy,
|
|
430
|
+
targets: readonly PreviewCleanupTarget[]
|
|
431
|
+
): string => {
|
|
432
|
+
assertPreviewCleanupStackPolicy(policy);
|
|
433
|
+
const lines = [
|
|
434
|
+
`has_targets=${targets.length > 0}`,
|
|
435
|
+
`targets=${JSON.stringify(targets)}`,
|
|
436
|
+
];
|
|
437
|
+
for (const stack of policy.stacks) {
|
|
438
|
+
const key = previewCleanupStackOutputKey(stack);
|
|
439
|
+
const include = targets.filter((target) => target.stack === stack);
|
|
440
|
+
if (include.length > MATRIX_ENTRY_LIMIT) {
|
|
441
|
+
throw new Error(
|
|
442
|
+
`Cleanup stack "${stack}" has ${include.length} targets; a GitHub matrix holds at most ${MATRIX_ENTRY_LIMIT}.`
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
lines.push(
|
|
446
|
+
`has_${key}=${include.length > 0}`,
|
|
447
|
+
`${key}_matrix=${JSON.stringify({ include })}`
|
|
448
|
+
);
|
|
449
|
+
}
|
|
450
|
+
return `${lines.join("\n")}\n`;
|
|
451
|
+
};
|
|
452
|
+
|
|
453
|
+
/** Parse untrusted residue JSON: an array of `{ stack, stage }` rows. */
|
|
454
|
+
export const parsePreviewCleanupResidue = (
|
|
455
|
+
value: unknown
|
|
456
|
+
): readonly PreviewCleanupResidue[] => {
|
|
457
|
+
if (!Array.isArray(value)) {
|
|
458
|
+
throw new TypeError("Preview cleanup residue must be a JSON array.");
|
|
459
|
+
}
|
|
460
|
+
return Object.freeze(
|
|
461
|
+
value.map((row, index) => {
|
|
462
|
+
if (
|
|
463
|
+
!isRecord(row) ||
|
|
464
|
+
typeof row.stack !== "string" ||
|
|
465
|
+
typeof row.stage !== "string"
|
|
466
|
+
) {
|
|
467
|
+
throw new TypeError(
|
|
468
|
+
`Preview cleanup residue row ${index} must have string stack and stage.`
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
return Object.freeze({ stack: row.stack, stage: row.stage });
|
|
472
|
+
})
|
|
473
|
+
);
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Parse untrusted target JSON (the discover job's `targets` output). Every
|
|
478
|
+
* row must still be a disposable stage owned by its own PR, so a tampered
|
|
479
|
+
* output cannot widen the audit or a record.
|
|
480
|
+
*/
|
|
481
|
+
export const parsePreviewCleanupTargets = (
|
|
482
|
+
policy: PreviewCleanupStackPolicy,
|
|
483
|
+
value: unknown
|
|
484
|
+
): readonly PreviewCleanupTarget[] => {
|
|
485
|
+
assertPreviewCleanupStackPolicy(policy);
|
|
486
|
+
if (!Array.isArray(value)) {
|
|
487
|
+
throw new TypeError("Preview cleanup targets must be a JSON array.");
|
|
488
|
+
}
|
|
489
|
+
return Object.freeze(
|
|
490
|
+
value.map((row, index) => {
|
|
491
|
+
if (
|
|
492
|
+
!isRecord(row) ||
|
|
493
|
+
typeof row.pr !== "number" ||
|
|
494
|
+
typeof row.stack !== "string" ||
|
|
495
|
+
typeof row.stage !== "string" ||
|
|
496
|
+
(row.headSha !== undefined &&
|
|
497
|
+
(typeof row.headSha !== "string" ||
|
|
498
|
+
!FULL_SHA_PATTERN.test(row.headSha)))
|
|
499
|
+
) {
|
|
500
|
+
throw new TypeError(`Preview cleanup target ${index} is malformed.`);
|
|
501
|
+
}
|
|
502
|
+
if (
|
|
503
|
+
!policy.stacks.includes(row.stack) ||
|
|
504
|
+
disposableStageOwner(policy, row.stage) !== row.pr
|
|
505
|
+
) {
|
|
506
|
+
throw new Error(
|
|
507
|
+
`Preview cleanup target ${row.stack}/${row.stage} is not a disposable stage of PR #${row.pr} in a declared stack.`
|
|
508
|
+
);
|
|
509
|
+
}
|
|
510
|
+
return Object.freeze({
|
|
511
|
+
...(typeof row.headSha === "string" ? { headSha: row.headSha } : {}),
|
|
512
|
+
pr: row.pr,
|
|
513
|
+
stack: row.stack,
|
|
514
|
+
stage: row.stage,
|
|
515
|
+
});
|
|
516
|
+
})
|
|
517
|
+
);
|
|
518
|
+
};
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* The whole-stage audit after every destroy. Any residue row whose stage
|
|
522
|
+
* is a target stage fails it, whatever stack the reader assigned the row,
|
|
523
|
+
* because a sibling stack's leftovers are the same stage's residue.
|
|
524
|
+
*/
|
|
525
|
+
export const assertPreviewCleanupTargetsAbsent = (
|
|
526
|
+
targets: readonly PreviewCleanupTarget[],
|
|
527
|
+
residue: readonly PreviewCleanupResidue[]
|
|
528
|
+
): void => {
|
|
529
|
+
const stages = new Set(targets.map(({ stage }) => stage));
|
|
530
|
+
const remaining = residue.filter(({ stage }) => stages.has(stage));
|
|
531
|
+
if (remaining.length > 0) {
|
|
532
|
+
throw new Error(
|
|
533
|
+
`Disposable stage residue remains: ${remaining
|
|
534
|
+
.map(({ stack, stage }) => `${stack}/${stage}`)
|
|
535
|
+
.toSorted()
|
|
536
|
+
.join(", ")}`
|
|
537
|
+
);
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
|
|
541
|
+
const storeFor = (
|
|
542
|
+
role: "read" | "write",
|
|
543
|
+
access: PreviewProofInventoryAccess
|
|
544
|
+
): PreviewProofInventoryStore => {
|
|
545
|
+
if (access.store !== undefined) {
|
|
546
|
+
return access.store;
|
|
547
|
+
}
|
|
548
|
+
if (access.token === undefined || access.token.length === 0) {
|
|
549
|
+
throw new Error(`Preview cleanup ${role} access requires a token.`);
|
|
550
|
+
}
|
|
551
|
+
return previewProofInventory.githubStore({
|
|
552
|
+
...(access.fetch === undefined ? {} : { fetch: access.fetch }),
|
|
553
|
+
...(access.timeoutMs === undefined ? {} : { timeoutMs: access.timeoutMs }),
|
|
554
|
+
token: access.token,
|
|
555
|
+
});
|
|
556
|
+
};
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Record one stack destroy's outcome on the inventory registration it
|
|
560
|
+
* cleaned up. A stage nothing registered (residue-only, or a hosted stage)
|
|
561
|
+
* returns `unregistered` without writing. A registration whose last cleanup
|
|
562
|
+
* failed is recovered through the same cleanup transition.
|
|
563
|
+
*/
|
|
564
|
+
export const recordPreviewCleanupOutcome = async (
|
|
565
|
+
input: RecordPreviewCleanupOutcomeInput,
|
|
566
|
+
access: RecordPreviewCleanupOutcomeAccess
|
|
567
|
+
): Promise<RecordPreviewCleanupOutcomeResult> => {
|
|
568
|
+
assertPositivePr(input.pr);
|
|
569
|
+
if (!isLocalPreviewStage(input.stage, input.pr)) {
|
|
570
|
+
return { kind: "unregistered" };
|
|
571
|
+
}
|
|
572
|
+
const readStore = storeFor("read", access.read);
|
|
573
|
+
const writeStore = storeFor("write", access.write);
|
|
574
|
+
const store: PreviewProofInventoryStore = {
|
|
575
|
+
list: (query) => readStore.list(query),
|
|
576
|
+
put: (write) => writeStore.put(write),
|
|
577
|
+
};
|
|
578
|
+
const canonical = (stack: string) => input.stackAliases?.[stack] ?? stack;
|
|
579
|
+
|
|
580
|
+
const listed = await previewProofInventory.list(
|
|
581
|
+
{ owner: input.owner, pr: input.pr, repo: input.repo, stage: input.stage },
|
|
582
|
+
{ store }
|
|
583
|
+
);
|
|
584
|
+
const existing = listed.find(
|
|
585
|
+
(row) =>
|
|
586
|
+
row.pr === input.pr &&
|
|
587
|
+
row.stage === input.stage &&
|
|
588
|
+
canonical(row.stack) === canonical(input.stack)
|
|
589
|
+
);
|
|
590
|
+
if (existing === undefined) {
|
|
591
|
+
return { kind: "unregistered" };
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
const registration = await previewProofInventory.recordCleanup(
|
|
595
|
+
{
|
|
596
|
+
evidence: input.evidence,
|
|
597
|
+
...(input.headSha === undefined ? {} : { headSha: input.headSha }),
|
|
598
|
+
outcome: input.outcome,
|
|
599
|
+
owner: input.owner,
|
|
600
|
+
pr: input.pr,
|
|
601
|
+
repo: input.repo,
|
|
602
|
+
...(input.runUrl === undefined ? {} : { runUrl: input.runUrl }),
|
|
603
|
+
stack: existing.stack,
|
|
604
|
+
stage: existing.stage,
|
|
605
|
+
},
|
|
606
|
+
{ store }
|
|
607
|
+
);
|
|
608
|
+
return {
|
|
609
|
+
kind: existing.cleanup.outcome === "failed" ? "recovered" : "recorded",
|
|
610
|
+
registration,
|
|
611
|
+
};
|
|
612
|
+
};
|
|
613
|
+
|
|
614
|
+
const readPullRequestState = async (
|
|
615
|
+
input: { owner: string; pr: number; repo: string },
|
|
616
|
+
access: ReadPullRequestStatesAccess
|
|
617
|
+
): Promise<PreviewCleanupPullRequestState | null> => {
|
|
618
|
+
let pull: unknown;
|
|
619
|
+
try {
|
|
620
|
+
pull = await githubJson(
|
|
621
|
+
{
|
|
622
|
+
fetch: access.fetch ?? fetch,
|
|
623
|
+
method: "GET",
|
|
624
|
+
timeoutMs: access.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
625
|
+
token: access.token,
|
|
626
|
+
url: `https://api.github.com/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.repo)}/pulls/${input.pr}`,
|
|
627
|
+
},
|
|
628
|
+
{
|
|
629
|
+
refusal: (status, statusText) => new GitHubApiError(status, statusText),
|
|
630
|
+
transport: (failure, attempts) =>
|
|
631
|
+
new PreviewProofTransportError(
|
|
632
|
+
failure.reason,
|
|
633
|
+
attempts,
|
|
634
|
+
failure.status
|
|
635
|
+
),
|
|
636
|
+
}
|
|
637
|
+
);
|
|
638
|
+
} catch (error) {
|
|
639
|
+
// A number that is not a PR (an issue, or nothing) owns no stage we may
|
|
640
|
+
// destroy; any other refusal is a real failure and stops the sweep.
|
|
641
|
+
if (error instanceof GitHubApiError && error.status === 404) {
|
|
642
|
+
return null;
|
|
643
|
+
}
|
|
644
|
+
throw error;
|
|
645
|
+
}
|
|
646
|
+
if (
|
|
647
|
+
!isRecord(pull) ||
|
|
648
|
+
pull.number !== input.pr ||
|
|
649
|
+
(pull.state !== "open" && pull.state !== "closed")
|
|
650
|
+
) {
|
|
651
|
+
throw new Error(`GitHub returned an unreadable pull request #${input.pr}.`);
|
|
652
|
+
}
|
|
653
|
+
return pull.state;
|
|
654
|
+
};
|
|
655
|
+
|
|
656
|
+
/**
|
|
657
|
+
* Ask GitHub for each PR's state. A PR GitHub does not know is left out of
|
|
658
|
+
* the map, so the sweep retains its stages.
|
|
659
|
+
*/
|
|
660
|
+
export const readPullRequestStates = async (
|
|
661
|
+
input: ReadPullRequestStatesInput,
|
|
662
|
+
access: ReadPullRequestStatesAccess
|
|
663
|
+
): Promise<ReadonlyMap<number, PreviewCleanupPullRequestState>> => {
|
|
664
|
+
const states = new Map<number, PreviewCleanupPullRequestState>();
|
|
665
|
+
for (
|
|
666
|
+
let start = 0;
|
|
667
|
+
start < input.prs.length;
|
|
668
|
+
start += PULL_STATE_CONCURRENCY
|
|
669
|
+
) {
|
|
670
|
+
const batch = input.prs.slice(start, start + PULL_STATE_CONCURRENCY);
|
|
671
|
+
// oxlint-disable-next-line no-await-in-loop -- bounded batches stay under GitHub's secondary rate limit
|
|
672
|
+
const read = await Promise.all(
|
|
673
|
+
batch.map(async (pr) => ({
|
|
674
|
+
pr,
|
|
675
|
+
state: await readPullRequestState(
|
|
676
|
+
{ owner: input.owner, pr, repo: input.repo },
|
|
677
|
+
access
|
|
678
|
+
),
|
|
679
|
+
}))
|
|
680
|
+
);
|
|
681
|
+
for (const { pr, state } of read) {
|
|
682
|
+
if (state !== null) {
|
|
683
|
+
states.set(pr, state);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
return states;
|
|
688
|
+
};
|