@rathnasgala2/adapter-github-pages 0.1.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,784 @@
1
+ /**
2
+ * DEC-097 section 6.2 reconciliation recovery: the adapter-side half.
3
+ *
4
+ * Two distinct responsibilities live here.
5
+ *
6
+ * 1. **A pure projection over the attempt fence and its tombstones.** The
7
+ * `pagesRunAttemptGapProof` and the `closed-no-destination-authority`
8
+ * tombstone digests are server-minted inside one atomic authorization
9
+ * transaction. This adapter *validates* a server-supplied
10
+ * `pagesReconciliationRecovery` record and refuses a malformed one; it
11
+ * never mints one, never allocates an epoch and never claims an
12
+ * authority. The builders exported here exist so a fixture (and a
13
+ * reviewer) can recompute the exact digests the server must have
14
+ * produced, and so a missing, extra, reordered or substituted gap row is
15
+ * caught by arithmetic rather than by trust.
16
+ *
17
+ * 2. **The same-operation recovery path's provider sequence.** Before
18
+ * uploading or creating any current carrier, recovery polls the prior
19
+ * attempt's catalog-constructed status endpoint using only
20
+ * `priorPagesBuildVersion` (the `inspect/pages-recovery-prior-status`
21
+ * row), and then takes exactly one of the four admitted branches. Every
22
+ * call it makes is a cataloged recovery-prior row, which `normal` mode
23
+ * forbids outright.
24
+ *
25
+ * @module
26
+ */
27
+
28
+ import {
29
+ canonicalizeJson,
30
+ domainDigest,
31
+ isDigestString,
32
+ } from '@rathnasgala2/adapter-protocol';
33
+
34
+ import {
35
+ DOMAIN_PAGES_NO_AUTHORITY_RUN_ATTEMPT,
36
+ DOMAIN_PAGES_RECONCILIATION_RECOVERY,
37
+ DOMAIN_PAGES_RUN_ATTEMPT_GAP_PROOF,
38
+ PAGES_DEPLOYMENT_STATUSES,
39
+ RECOVERY_MODE,
40
+ RECOVERY_POLL_BUDGET_SECONDS,
41
+ POLL_SCHEDULE_SECONDS,
42
+ POLL_TAIL_SECONDS,
43
+ SUCCESS_STATUS,
44
+ TEMPORARY_STATUSES,
45
+ TERMINAL_FAILURE_STATUSES,
46
+ } from './constants.js';
47
+ import { callProvider } from './rest.js';
48
+
49
+ /** The `profile` const of a `pagesReconciliationRecovery` record. */
50
+ export const RECOVERY_RECORD_PROFILE = 'gala-pages-reconciliation-recovery-v2';
51
+
52
+ /** The `profile` const of a `pagesRunAttemptGapProof` record. */
53
+ export const GAP_PROOF_PROFILE = 'gala-pages-run-attempt-gap-proof-v2';
54
+
55
+ /** The single admitted `authorityState` of an intervening run attempt. */
56
+ export const NO_AUTHORITY_STATE = 'closed-no-destination-authority';
57
+
58
+ /** The inclusive bounds DEC-097 places on the two fence coordinates. */
59
+ export const PRIOR_RUN_ATTEMPT_BOUNDS = Object.freeze({
60
+ minimum: 1,
61
+ maximum: 50,
62
+ });
63
+ /** The inclusive bounds on a claiming run attempt. */
64
+ export const CLAIMING_RUN_ATTEMPT_BOUNDS = Object.freeze({
65
+ minimum: 2,
66
+ maximum: 51,
67
+ });
68
+
69
+ const GITHUB_POSITIVE_DECIMAL = /^[1-9][0-9]{0,18}$/u;
70
+ const BUILD_VERSION_PATTERN = /^[0-9a-f]{40}$/u;
71
+ const RFC3339 =
72
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u;
73
+
74
+ /**
75
+ * Raise a typed recovery failure.
76
+ *
77
+ * @param {string} code the stable error code
78
+ * @param {string} detail the diagnostic detail
79
+ * @returns {never} never returns
80
+ */
81
+ function refuse(code, detail) {
82
+ throw new Error(`${code}: ${detail}`);
83
+ }
84
+
85
+ /**
86
+ * @param {unknown} value the candidate
87
+ * @param {string} name the member name
88
+ * @returns {string} the validated stable identifier
89
+ */
90
+ function requireStableId(value, name) {
91
+ if (typeof value !== 'string' || value === '' || value.length > 200) {
92
+ refuse(
93
+ 'PAGES_RECOVERY_RECORD_INVALID',
94
+ `${JSON.stringify(name)} is not a stable identifier`,
95
+ );
96
+ }
97
+ return /** @type {string} */ (value);
98
+ }
99
+
100
+ /**
101
+ * @param {unknown} value the candidate
102
+ * @param {string} name the member name
103
+ * @returns {string} the validated digest
104
+ */
105
+ function requireDigest(value, name) {
106
+ if (!isDigestString(value)) {
107
+ refuse(
108
+ 'PAGES_RECOVERY_RECORD_INVALID',
109
+ `${JSON.stringify(name)} is not a sha256 digest string`,
110
+ );
111
+ }
112
+ return /** @type {string} */ (value);
113
+ }
114
+
115
+ /**
116
+ * @param {unknown} value the candidate
117
+ * @param {string} name the member name
118
+ * @returns {string} the validated timestamp
119
+ */
120
+ function requireRfc3339(value, name) {
121
+ if (typeof value !== 'string' || !RFC3339.test(value)) {
122
+ refuse(
123
+ 'PAGES_RECOVERY_RECORD_INVALID',
124
+ `${JSON.stringify(name)} is not an RFC 3339 timestamp`,
125
+ );
126
+ }
127
+ return /** @type {string} */ (value);
128
+ }
129
+
130
+ /**
131
+ * @param {unknown} value the candidate
132
+ * @param {string} name the member name
133
+ * @returns {string} the validated `githubPositiveDecimal`
134
+ */
135
+ function requireGithubPositiveDecimal(value, name) {
136
+ const text = typeof value === 'number' ? String(value) : value;
137
+ if (typeof text !== 'string' || !GITHUB_POSITIVE_DECIMAL.test(text)) {
138
+ refuse(
139
+ 'PAGES_RECOVERY_RECORD_INVALID',
140
+ `${JSON.stringify(name)} is not a positive canonical decimal GitHub identifier`,
141
+ );
142
+ }
143
+ return /** @type {string} */ (text);
144
+ }
145
+
146
+ /**
147
+ * @param {unknown} value the candidate
148
+ * @param {string} name the member name
149
+ * @param {{minimum: number, maximum: number}} bounds inclusive bounds
150
+ * @returns {number} the validated integer
151
+ */
152
+ function requireBoundedInteger(value, name, bounds) {
153
+ if (
154
+ typeof value !== 'number' ||
155
+ !Number.isSafeInteger(value) ||
156
+ value < bounds.minimum ||
157
+ value > bounds.maximum
158
+ ) {
159
+ refuse(
160
+ 'PAGES_RECOVERY_RECORD_INVALID',
161
+ `${JSON.stringify(name)} must be an integer in ${bounds.minimum}..${bounds.maximum}`,
162
+ );
163
+ }
164
+ return /** @type {number} */ (value);
165
+ }
166
+
167
+ /**
168
+ * Compute one intervening attempt's immutable tombstone digest:
169
+ * `SHA256(UTF8("GALA-PAGES-NO-AUTHORITY-RUN-ATTEMPT-V2\0") ||
170
+ * JCS({repositoryId,runId,runAttempt,authorityState}))`.
171
+ *
172
+ * @param {{
173
+ * repositoryId: string | number,
174
+ * runId: string | number,
175
+ * runAttempt: number
176
+ * }} input the tombstone coordinates
177
+ * @returns {string} the `decisionDigest`
178
+ */
179
+ export function computeInterveningAttemptDigest(input) {
180
+ return domainDigest(DOMAIN_PAGES_NO_AUTHORITY_RUN_ATTEMPT, {
181
+ repositoryId: String(input.repositoryId),
182
+ runId: String(input.runId),
183
+ runAttempt: input.runAttempt,
184
+ authorityState: NO_AUTHORITY_STATE,
185
+ });
186
+ }
187
+
188
+ /**
189
+ * Build the exact ordered tombstone set for one attempt fence: every integer
190
+ * strictly between the prior and claiming attempts, sorted by `runAttempt`.
191
+ * An adjacent claim carries the exact empty array.
192
+ *
193
+ * @param {{
194
+ * repositoryId: string | number,
195
+ * runId: string | number,
196
+ * priorRunAttempt: number,
197
+ * claimingRunAttempt: number
198
+ * }} input the fence coordinates
199
+ * @returns {readonly Readonly<{
200
+ * runAttempt: number,
201
+ * authorityState: string,
202
+ * decisionDigest: string
203
+ * }>[]} the ordered tombstone rows
204
+ */
205
+ export function buildInterveningAttempts(input) {
206
+ requireBoundedInteger(
207
+ input.priorRunAttempt,
208
+ 'priorRunAttempt',
209
+ PRIOR_RUN_ATTEMPT_BOUNDS,
210
+ );
211
+ requireBoundedInteger(
212
+ input.claimingRunAttempt,
213
+ 'claimingRunAttempt',
214
+ CLAIMING_RUN_ATTEMPT_BOUNDS,
215
+ );
216
+ if (input.claimingRunAttempt <= input.priorRunAttempt) {
217
+ refuse(
218
+ 'PAGES_RUN_ATTEMPT_FENCE_INVALID',
219
+ 'claimingRunAttempt must be strictly greater than priorRunAttempt',
220
+ );
221
+ }
222
+ /** @type {Readonly<Record<string, unknown>>[]} */
223
+ const rows = [];
224
+ for (
225
+ let runAttempt = input.priorRunAttempt + 1;
226
+ runAttempt < input.claimingRunAttempt;
227
+ runAttempt += 1
228
+ ) {
229
+ rows.push(
230
+ Object.freeze({
231
+ runAttempt,
232
+ authorityState: NO_AUTHORITY_STATE,
233
+ decisionDigest: computeInterveningAttemptDigest({
234
+ repositoryId: input.repositoryId,
235
+ runId: input.runId,
236
+ runAttempt,
237
+ }),
238
+ }),
239
+ );
240
+ }
241
+ return Object.freeze(
242
+ /** @type {readonly Readonly<{runAttempt: number, authorityState: string, decisionDigest: string}>[]} */ (
243
+ /** @type {unknown} */ (rows)
244
+ ),
245
+ );
246
+ }
247
+
248
+ /**
249
+ * Compute a gap proof's `proofDigest` over the record with `proofDigest`
250
+ * omitted.
251
+ *
252
+ * @param {Readonly<Record<string, unknown>>} proof the gap proof record
253
+ * @returns {string} the `proofDigest`
254
+ */
255
+ export function computeGapProofDigest(proof) {
256
+ const rest = Object.fromEntries(
257
+ Object.entries(proof).filter(([name]) => name !== 'proofDigest'),
258
+ );
259
+ return domainDigest(DOMAIN_PAGES_RUN_ATTEMPT_GAP_PROOF, rest);
260
+ }
261
+
262
+ /**
263
+ * Build the complete `pagesRunAttemptGapProof` the authorization
264
+ * transaction must have produced for one fence.
265
+ *
266
+ * @param {{
267
+ * repositoryId: string | number,
268
+ * runId: string | number,
269
+ * priorRunAttempt: number,
270
+ * claimingRunAttempt: number
271
+ * }} input the fence coordinates
272
+ * @returns {Readonly<Record<string, unknown>>} the complete gap proof
273
+ */
274
+ export function buildRunAttemptGapProof(input) {
275
+ const withoutDigest = {
276
+ profile: GAP_PROOF_PROFILE,
277
+ runId: requireGithubPositiveDecimal(input.runId, 'runId'),
278
+ priorRunAttempt: input.priorRunAttempt,
279
+ claimingRunAttempt: input.claimingRunAttempt,
280
+ interveningAttempts: [...buildInterveningAttempts(input)],
281
+ };
282
+ return Object.freeze({
283
+ ...withoutDigest,
284
+ proofDigest: computeGapProofDigest(withoutDigest),
285
+ });
286
+ }
287
+
288
+ /**
289
+ * Validate one server-supplied gap proof: exact member set, bounded
290
+ * coordinates, set equality of the intervening attempts with every integer
291
+ * strictly between the two coordinates, `runAttempt` ordering, every
292
+ * tombstone digest, and the `proofDigest` itself.
293
+ *
294
+ * @param {unknown} proof the candidate gap proof
295
+ * @param {{repositoryId: string | number}} binding the repository identity
296
+ * the tombstone digests are bound to
297
+ * @returns {Readonly<Record<string, unknown>>} the validated proof
298
+ */
299
+ export function validateRunAttemptGapProof(proof, binding) {
300
+ if (proof === null || typeof proof !== 'object' || Array.isArray(proof)) {
301
+ refuse(
302
+ 'PAGES_RUN_ATTEMPT_GAP_PROOF_INVALID',
303
+ 'runAttemptGapProof is not an object',
304
+ );
305
+ }
306
+ const record = /** @type {Record<string, unknown>} */ (proof);
307
+ const expectedMembers = [
308
+ 'claimingRunAttempt',
309
+ 'interveningAttempts',
310
+ 'priorRunAttempt',
311
+ 'profile',
312
+ 'proofDigest',
313
+ 'runId',
314
+ ];
315
+ const members = Object.keys(record).sort();
316
+ if (
317
+ members.length !== expectedMembers.length ||
318
+ !expectedMembers.every((name, index) => members[index] === name)
319
+ ) {
320
+ refuse(
321
+ 'PAGES_RUN_ATTEMPT_GAP_PROOF_INVALID',
322
+ `the gap proof must have exactly the members ${expectedMembers.join(', ')}`,
323
+ );
324
+ }
325
+ if (record.profile !== GAP_PROOF_PROFILE) {
326
+ refuse(
327
+ 'PAGES_RUN_ATTEMPT_GAP_PROOF_INVALID',
328
+ `profile must be ${JSON.stringify(GAP_PROOF_PROFILE)}`,
329
+ );
330
+ }
331
+ const runId = requireGithubPositiveDecimal(record.runId, 'runId');
332
+ const priorRunAttempt = requireBoundedInteger(
333
+ record.priorRunAttempt,
334
+ 'priorRunAttempt',
335
+ PRIOR_RUN_ATTEMPT_BOUNDS,
336
+ );
337
+ const claimingRunAttempt = requireBoundedInteger(
338
+ record.claimingRunAttempt,
339
+ 'claimingRunAttempt',
340
+ CLAIMING_RUN_ATTEMPT_BOUNDS,
341
+ );
342
+ if (claimingRunAttempt <= priorRunAttempt) {
343
+ refuse(
344
+ 'PAGES_RUN_ATTEMPT_FENCE_INVALID',
345
+ 'claimingRunAttempt must be strictly greater than priorRunAttempt',
346
+ );
347
+ }
348
+ const expectedRows = buildInterveningAttempts({
349
+ repositoryId: binding.repositoryId,
350
+ runId,
351
+ priorRunAttempt,
352
+ claimingRunAttempt,
353
+ });
354
+ const observedRows = record.interveningAttempts;
355
+ if (!Array.isArray(observedRows)) {
356
+ refuse(
357
+ 'PAGES_RUN_ATTEMPT_GAP_PROOF_INVALID',
358
+ 'interveningAttempts is not an array',
359
+ );
360
+ }
361
+ const rows = /** @type {unknown[]} */ (observedRows);
362
+ if (rows.length !== expectedRows.length) {
363
+ refuse(
364
+ 'PAGES_RUN_ATTEMPT_GAP_PROOF_INCOMPLETE',
365
+ `interveningAttempts has ${rows.length} rows; the fence ${priorRunAttempt}..${claimingRunAttempt} requires exactly ${expectedRows.length}, one for every strictly intervening attempt`,
366
+ );
367
+ }
368
+ rows.forEach((row, index) => {
369
+ if (canonicalizeJson(row) !== canonicalizeJson(expectedRows[index])) {
370
+ refuse(
371
+ 'PAGES_RUN_ATTEMPT_GAP_PROOF_INCOMPLETE',
372
+ `intervening attempt row ${index} is missing, extra, reordered or carries a substituted decisionDigest`,
373
+ );
374
+ }
375
+ });
376
+ const expectedDigest = computeGapProofDigest(record);
377
+ if (record.proofDigest !== expectedDigest) {
378
+ refuse(
379
+ 'PAGES_RUN_ATTEMPT_GAP_PROOF_DIGEST_MISMATCH',
380
+ 'proofDigest does not equal SHA256(UTF8("GALA-PAGES-RUN-ATTEMPT-GAP-PROOF-V2\\0") || JCS(the record with proofDigest omitted))',
381
+ );
382
+ }
383
+ return Object.freeze({ ...record });
384
+ }
385
+
386
+ /** The exact member names of a `pagesReconciliationRecovery` record. */
387
+ const RECOVERY_REQUIRED_MEMBERS = Object.freeze([
388
+ 'priorAttemptId',
389
+ 'priorAuthorityEpoch',
390
+ 'priorAuthorityId',
391
+ 'priorFenceEvidenceDigest',
392
+ 'priorIntentDigest',
393
+ 'priorPagesBuildVersion',
394
+ 'priorProposedGenerationId',
395
+ 'profile',
396
+ 'reconcileCommandDigest',
397
+ 'reconcileCommandExpiresAt',
398
+ 'reconcileCommandId',
399
+ 'recoveryDigest',
400
+ 'runAttemptGapProof',
401
+ ]);
402
+
403
+ /** The one optional member (jointly absent for a first publish). */
404
+ const RECOVERY_OPTIONAL_MEMBERS = Object.freeze(['priorExpectedGenerationId']);
405
+
406
+ /**
407
+ * Compute a recovery record's `recoveryDigest` over the record with
408
+ * `recoveryDigest` omitted.
409
+ *
410
+ * @param {Readonly<Record<string, unknown>>} recovery the recovery record
411
+ * @returns {string} the `recoveryDigest`
412
+ */
413
+ export function computeRecoveryDigest(recovery) {
414
+ const rest = Object.fromEntries(
415
+ Object.entries(recovery).filter(([name]) => name !== 'recoveryDigest'),
416
+ );
417
+ return domainDigest(DOMAIN_PAGES_RECONCILIATION_RECOVERY, rest);
418
+ }
419
+
420
+ /**
421
+ * Seal one otherwise complete recovery record by computing its digest. Only
422
+ * a fixture uses this: the real record is server-minted.
423
+ *
424
+ * @param {Readonly<Record<string, unknown>>} withoutDigest the record with no
425
+ * `recoveryDigest`
426
+ * @returns {Readonly<Record<string, unknown>>} the sealed record
427
+ */
428
+ export function sealRecoveryRecord(withoutDigest) {
429
+ return Object.freeze({
430
+ ...withoutDigest,
431
+ recoveryDigest: computeRecoveryDigest(withoutDigest),
432
+ });
433
+ }
434
+
435
+ /**
436
+ * Validate one server-supplied `pagesReconciliationRecovery` record. This
437
+ * adapter never mints one; a malformed record is refused before any provider
438
+ * call.
439
+ *
440
+ * @param {unknown} recovery the candidate record
441
+ * @param {{repositoryId: string | number}} binding the repository identity
442
+ * @returns {Readonly<Record<string, unknown>>} the validated record
443
+ */
444
+ export function validateReconciliationRecovery(recovery, binding) {
445
+ if (
446
+ recovery === null ||
447
+ typeof recovery !== 'object' ||
448
+ Array.isArray(recovery)
449
+ ) {
450
+ refuse(
451
+ 'PAGES_RECOVERY_RECORD_INVALID',
452
+ 'pagesRecovery is required in pages-reconciliation-recovery mode and must be an object',
453
+ );
454
+ }
455
+ const record = /** @type {Record<string, unknown>} */ (recovery);
456
+ const permitted = new Set([
457
+ ...RECOVERY_REQUIRED_MEMBERS,
458
+ ...RECOVERY_OPTIONAL_MEMBERS,
459
+ ]);
460
+ for (const name of Object.keys(record)) {
461
+ if (!permitted.has(name)) {
462
+ refuse(
463
+ 'PAGES_RECOVERY_RECORD_INVALID',
464
+ `${JSON.stringify(name)} is not a member of pagesReconciliationRecovery`,
465
+ );
466
+ }
467
+ }
468
+ for (const name of RECOVERY_REQUIRED_MEMBERS) {
469
+ if (record[name] === undefined) {
470
+ refuse(
471
+ 'PAGES_RECOVERY_RECORD_INVALID',
472
+ `${JSON.stringify(name)} is required`,
473
+ );
474
+ }
475
+ }
476
+ if (record.profile !== RECOVERY_RECORD_PROFILE) {
477
+ refuse(
478
+ 'PAGES_RECOVERY_RECORD_INVALID',
479
+ `profile must be ${JSON.stringify(RECOVERY_RECORD_PROFILE)}`,
480
+ );
481
+ }
482
+ requireStableId(record.reconcileCommandId, 'reconcileCommandId');
483
+ requireDigest(record.reconcileCommandDigest, 'reconcileCommandDigest');
484
+ requireRfc3339(record.reconcileCommandExpiresAt, 'reconcileCommandExpiresAt');
485
+ requireStableId(record.priorAttemptId, 'priorAttemptId');
486
+ requireDigest(record.priorIntentDigest, 'priorIntentDigest');
487
+ if (
488
+ typeof record.priorAuthorityEpoch !== 'number' ||
489
+ !Number.isSafeInteger(record.priorAuthorityEpoch) ||
490
+ record.priorAuthorityEpoch < 1
491
+ ) {
492
+ refuse(
493
+ 'PAGES_RECOVERY_RECORD_INVALID',
494
+ 'priorAuthorityEpoch must be a positive int64',
495
+ );
496
+ }
497
+ requireStableId(record.priorAuthorityId, 'priorAuthorityId');
498
+ if (record.priorExpectedGenerationId !== undefined) {
499
+ requireStableId(
500
+ record.priorExpectedGenerationId,
501
+ 'priorExpectedGenerationId',
502
+ );
503
+ }
504
+ requireStableId(
505
+ record.priorProposedGenerationId,
506
+ 'priorProposedGenerationId',
507
+ );
508
+ if (
509
+ typeof record.priorPagesBuildVersion !== 'string' ||
510
+ !BUILD_VERSION_PATTERN.test(record.priorPagesBuildVersion)
511
+ ) {
512
+ refuse(
513
+ 'PAGES_RECOVERY_RECORD_INVALID',
514
+ 'priorPagesBuildVersion must be exactly 40 lowercase hexadecimal characters',
515
+ );
516
+ }
517
+ requireDigest(record.priorFenceEvidenceDigest, 'priorFenceEvidenceDigest');
518
+ validateRunAttemptGapProof(record.runAttemptGapProof, binding);
519
+ const expectedDigest = computeRecoveryDigest(record);
520
+ if (record.recoveryDigest !== expectedDigest) {
521
+ refuse(
522
+ 'PAGES_RECOVERY_DIGEST_MISMATCH',
523
+ 'recoveryDigest does not equal SHA256(UTF8("GALA-PAGES-RECONCILIATION-RECOVERY-V2\\0") || JCS(pagesRecovery with recoveryDigest omitted))',
524
+ );
525
+ }
526
+ return Object.freeze({ ...record });
527
+ }
528
+
529
+ /**
530
+ * Refuse a recovery-prior call outside recovery mode. `normal` forbids every
531
+ * recovery-prior call and does not reserve that branch's budget.
532
+ *
533
+ * @param {string} mode the authority mode
534
+ * @returns {void}
535
+ */
536
+ export function assertRecoveryModePermitted(mode) {
537
+ if (mode !== RECOVERY_MODE) {
538
+ throw new Error(
539
+ `PAGES_RECOVERY_CALL_FORBIDDEN: the recovery-prior call plan is admitted only in ${RECOVERY_MODE} mode, not ${JSON.stringify(mode)}`,
540
+ );
541
+ }
542
+ }
543
+
544
+ /**
545
+ * Read the prior attempt's status once through the cataloged
546
+ * `inspect/pages-recovery-prior-status` row.
547
+ *
548
+ * @param {import('./rest.js').RestContext} context the recovery-bound context
549
+ * @returns {Promise<{httpStatus: number, status: string | null}>} the
550
+ * observation; `status` is `null` for a 404 or a malformed body
551
+ */
552
+ async function readPriorStatus(context) {
553
+ const response = await callProvider(
554
+ context,
555
+ 'inspect',
556
+ 'pages-recovery-prior-status',
557
+ { acceptStatuses: [200, 404] },
558
+ );
559
+ if (response.status === 404) {
560
+ return { httpStatus: 404, status: null };
561
+ }
562
+ const body = /** @type {Record<string, unknown>} */ (response.body ?? {});
563
+ const status = body.status;
564
+ return {
565
+ httpStatus: 200,
566
+ status: typeof status === 'string' ? status : null,
567
+ };
568
+ }
569
+
570
+ /**
571
+ * @typedef {Readonly<{
572
+ * profile: 'gala-pages-recovery-observation-v2',
573
+ * priorPagesBuildVersion: string,
574
+ * outcome: 'prior-succeeded' | 'prior-terminal-failure' | 'reconciliation-required',
575
+ * authorityState: 'terminal-candidate' | 'proceed-with-fresh-create' | 'reconciliation-required',
576
+ * priorStatus: string | null,
577
+ * observedStatuses: readonly string[],
578
+ * cancelCallCount: number,
579
+ * reason: string
580
+ * }>} PriorAttemptObservation
581
+ */
582
+
583
+ /**
584
+ * @param {string} outcome the branch taken
585
+ * @param {string} authorityState the resulting authority state
586
+ * @param {string} priorPagesBuildVersion the prior build version
587
+ * @param {string | null} priorStatus the exact prior status
588
+ * @param {readonly string[]} observedStatuses every status observed
589
+ * @param {number} cancelCallCount how many cancels were issued (0 or 1)
590
+ * @param {string} reason a truthful one-line reason
591
+ * @returns {PriorAttemptObservation} the frozen observation
592
+ */
593
+ function observation(
594
+ outcome,
595
+ authorityState,
596
+ priorPagesBuildVersion,
597
+ priorStatus,
598
+ observedStatuses,
599
+ cancelCallCount,
600
+ reason,
601
+ ) {
602
+ return /** @type {PriorAttemptObservation} */ (
603
+ Object.freeze({
604
+ profile: 'gala-pages-recovery-observation-v2',
605
+ priorPagesBuildVersion,
606
+ outcome,
607
+ authorityState,
608
+ priorStatus,
609
+ observedStatuses: Object.freeze([...observedStatuses]),
610
+ cancelCallCount,
611
+ reason,
612
+ })
613
+ );
614
+ }
615
+
616
+ /**
617
+ * Resolve the prior attempt before any current carrier is uploaded or
618
+ * created (DEC-097 section 6.2).
619
+ *
620
+ * - terminal `succeed`: the same operation's proposed generation was already
621
+ * selected. No new create is performed and the current fence terminalizes
622
+ * as `terminal-candidate`.
623
+ * - a terminal non-success: immutable, so the prior create can never
624
+ * activate. The exact prior status is recorded and the caller proceeds
625
+ * with the fresh current carrier/create.
626
+ * - a temporary status or 404: exactly one cataloged cancel of that prior
627
+ * build version, then bounded polling.
628
+ * - still-temporary, 404, malformed, unknown or nonterminal at the recovery
629
+ * deadline: truthful evidence, no current create, authority returns to
630
+ * `reconciliation-required`.
631
+ *
632
+ * @param {import('./rest.js').RestContext} context a REST context already
633
+ * bound to `pages-reconciliation-recovery` mode and the prior build version
634
+ * @param {{
635
+ * sleep?: (seconds: number) => Promise<void>,
636
+ * budgetSeconds?: number
637
+ * }} [options] bounded polling controls
638
+ * @returns {Promise<PriorAttemptObservation>} the truthful observation
639
+ */
640
+ export async function resolvePriorAttempt(context, options = {}) {
641
+ assertRecoveryModePermitted(String(context.mode));
642
+ const priorPagesBuildVersion = String(context.priorPagesBuildVersion);
643
+ const sleep = options.sleep ?? defaultSleep;
644
+ const budget = options.budgetSeconds ?? RECOVERY_POLL_BUDGET_SECONDS;
645
+ /** @type {string[]} */
646
+ const observed = [];
647
+
648
+ const first = await readPriorStatus(context);
649
+ if (first.status !== null) {
650
+ observed.push(first.status);
651
+ }
652
+ if (first.httpStatus === 200 && first.status !== null) {
653
+ if (!PAGES_DEPLOYMENT_STATUSES.includes(first.status)) {
654
+ return observation(
655
+ 'reconciliation-required',
656
+ 'reconciliation-required',
657
+ priorPagesBuildVersion,
658
+ first.status,
659
+ observed,
660
+ 0,
661
+ 'the prior attempt reported a status outside the eleven accepted values; no current create is made',
662
+ );
663
+ }
664
+ if (first.status === SUCCESS_STATUS) {
665
+ return observation(
666
+ 'prior-succeeded',
667
+ 'terminal-candidate',
668
+ priorPagesBuildVersion,
669
+ first.status,
670
+ observed,
671
+ 0,
672
+ "the prior attempt reached terminal succeed, so the same operation's proposed generation was already selected and no new create is performed",
673
+ );
674
+ }
675
+ if (TERMINAL_FAILURE_STATUSES.includes(first.status)) {
676
+ return observation(
677
+ 'prior-terminal-failure',
678
+ 'proceed-with-fresh-create',
679
+ priorPagesBuildVersion,
680
+ first.status,
681
+ observed,
682
+ 0,
683
+ 'the prior attempt reached an immutable terminal non-success, so it can never activate and the fresh current carrier may proceed',
684
+ );
685
+ }
686
+ if (!TEMPORARY_STATUSES.includes(first.status)) {
687
+ return observation(
688
+ 'reconciliation-required',
689
+ 'reconciliation-required',
690
+ priorPagesBuildVersion,
691
+ first.status,
692
+ observed,
693
+ 0,
694
+ 'the prior attempt reported a nonterminal, unpartitioned status; no current create is made',
695
+ );
696
+ }
697
+ } else if (first.httpStatus === 200) {
698
+ return observation(
699
+ 'reconciliation-required',
700
+ 'reconciliation-required',
701
+ priorPagesBuildVersion,
702
+ null,
703
+ observed,
704
+ 0,
705
+ 'the prior attempt status response was malformed; no current create is made',
706
+ );
707
+ }
708
+
709
+ // Temporary status or 404: exactly one cataloged cancel, then bounded
710
+ // polling. The cancel is issued once and only once.
711
+ await callProvider(context, 'cleanup-staged', 'pages-recovery-prior-cancel', {
712
+ acceptStatuses: [200, 202, 204, 404],
713
+ });
714
+ const cancelCallCount = 1;
715
+
716
+ let spent = 0;
717
+ for (let attempt = 0; ; attempt += 1) {
718
+ const wait = POLL_SCHEDULE_SECONDS[attempt] ?? POLL_TAIL_SECONDS;
719
+ if (spent + wait > budget) {
720
+ return observation(
721
+ 'reconciliation-required',
722
+ 'reconciliation-required',
723
+ priorPagesBuildVersion,
724
+ observed[observed.length - 1] ?? null,
725
+ observed,
726
+ cancelCallCount,
727
+ `the prior attempt was still nonterminal at the ${budget}-second recovery deadline; no current create is made and the authority returns to reconciliation-required`,
728
+ );
729
+ }
730
+ spent += wait;
731
+ await sleep(wait);
732
+
733
+ const next = await readPriorStatus(context);
734
+ if (next.status !== null) {
735
+ observed.push(next.status);
736
+ }
737
+ if (next.httpStatus === 404 || next.status === null) {
738
+ continue;
739
+ }
740
+ if (next.status === SUCCESS_STATUS) {
741
+ return observation(
742
+ 'prior-succeeded',
743
+ 'terminal-candidate',
744
+ priorPagesBuildVersion,
745
+ next.status,
746
+ observed,
747
+ cancelCallCount,
748
+ 'the prior attempt reached terminal succeed despite the cancel; no new create is performed',
749
+ );
750
+ }
751
+ if (TERMINAL_FAILURE_STATUSES.includes(next.status)) {
752
+ return observation(
753
+ 'prior-terminal-failure',
754
+ 'proceed-with-fresh-create',
755
+ priorPagesBuildVersion,
756
+ next.status,
757
+ observed,
758
+ cancelCallCount,
759
+ 'the cancel drove the prior attempt to an immutable terminal non-success; the fresh current carrier may proceed',
760
+ );
761
+ }
762
+ if (!PAGES_DEPLOYMENT_STATUSES.includes(next.status)) {
763
+ return observation(
764
+ 'reconciliation-required',
765
+ 'reconciliation-required',
766
+ priorPagesBuildVersion,
767
+ next.status,
768
+ observed,
769
+ cancelCallCount,
770
+ 'the prior attempt reported an unknown status after the cancel; no current create is made',
771
+ );
772
+ }
773
+ }
774
+ }
775
+
776
+ /**
777
+ * @param {number} seconds seconds to wait
778
+ * @returns {Promise<void>} resolves after the wait
779
+ */
780
+ function defaultSleep(seconds) {
781
+ return new Promise((resolve) => {
782
+ setTimeout(resolve, seconds * 1000).unref();
783
+ });
784
+ }