@rathnasgala2/adapter-github-pages 0.1.0 → 0.1.2

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/src/index.js CHANGED
@@ -21,6 +21,7 @@
21
21
  * @module
22
22
  */
23
23
 
24
+ import { PagesAdapterError } from './errors.js';
24
25
  import {
25
26
  fenceDisagrees,
26
27
  fenceFor,
@@ -48,7 +49,7 @@ import {
48
49
  } from './deployment.js';
49
50
  import { decodeCarrier, encodeCarrier } from './carrier.js';
50
51
  import { buildValidatedMarker, parsePublicMarker } from './marker.js';
51
- import { readPublic } from './public-read.js';
52
+ import { maxAgeSeconds, readPublic } from './public-read.js';
52
53
  import { requireOidcExpectation } from './oidc.js';
53
54
  import {
54
55
  resolvePriorAttempt,
@@ -56,15 +57,17 @@ import {
56
57
  } from './recovery.js';
57
58
  import { GITHUB_API_ORIGIN, buildRequestTemplates } from './request-catalog.js';
58
59
  import { bindIdentity, callProvider } from './rest.js';
59
- import { destinationKey, stateFor } from './store.js';
60
+ import { stateFor } from './store.js';
60
61
 
61
62
  export {
62
63
  EXPECT_NOTHING_SERVED,
63
64
  fenceFor,
64
65
  generateUuidV7,
65
66
  } from '@rathnasgala2/adapter-protocol';
67
+ export { PagesAdapterError } from './errors.js';
66
68
  export { computeArtifactDigest } from './artifact-projection.js';
67
69
  export { decodeCarrier, encodeCarrier } from './carrier.js';
70
+ export { buildValidatedMarker } from './marker.js';
68
71
  export { GENERATION_MARKER_PATH } from './constants.js';
69
72
  export { forgetDestination } from './store.js';
70
73
  export { ADAPTER_VERSION, NORMAL_MODE, RECOVERY_MODE } from './constants.js';
@@ -108,13 +111,16 @@ export {
108
111
  * oidcToken?: string,
109
112
  * oidcClaims?: import('./oidc.js').PagesOidcExpectation,
110
113
  * publicBaseUrl: string,
114
+ * verificationBaseUrl?: string,
111
115
  * token: string,
112
116
  * publishCarrier: (input: {bytes: Buffer, generationId: string, carrierDigest: string}) => Promise<{pagesArtifactId: string | number, artifactDigest?: string, byteCount?: number}>,
113
117
  * fetch?: typeof globalThis.fetch,
114
118
  * publicFetch?: typeof globalThis.fetch,
115
119
  * sleep?: (seconds: number) => Promise<void>,
120
+ * now?: () => number,
116
121
  * runId?: string,
117
- * runAttempt?: number
122
+ * runAttempt?: number,
123
+ * headSha?: string
118
124
  * }>} PagesDestination
119
125
  */
120
126
 
@@ -152,6 +158,14 @@ function restContextFor(destination) {
152
158
  if (!destination.publicBaseUrl.startsWith('https://')) {
153
159
  throw new TypeError('destination.publicBaseUrl must be an https origin');
154
160
  }
161
+ if (
162
+ destination.verificationBaseUrl !== undefined &&
163
+ !destination.verificationBaseUrl.startsWith('https://')
164
+ ) {
165
+ throw new TypeError(
166
+ 'destination.verificationBaseUrl must be an https origin',
167
+ );
168
+ }
155
169
  if (typeof destination.publishCarrier !== 'function') {
156
170
  throw new TypeError(
157
171
  'destination.publishCarrier is required: adapter-github-pages never uploads an Actions artifact itself (DEC-097 section 2.3 makes direct carrier upload workflow-owned)',
@@ -168,13 +182,20 @@ function restContextFor(destination) {
168
182
  }
169
183
 
170
184
  /**
185
+ * The public context every verification read uses: the marker read, the
186
+ * route reads and the inspection. The origin that is serving right now
187
+ * (`verificationBaseUrl`: the `github.io` project path before the Pages CNAME
188
+ * is set, the custom base once the custom domain serves) when the destination
189
+ * names one, else `publicBaseUrl`. Artifact-relative paths are joined to it
190
+ * the same way under either.
191
+ *
171
192
  * @param {PagesDestination} destination the destination
172
193
  * @returns {import('./public-read.js').PublicContext} the public context
173
194
  */
174
195
  function publicContextFor(destination) {
175
196
  const injected = destination.publicFetch ?? destination.fetch;
176
197
  return Object.freeze({
177
- publicBaseUrl: destination.publicBaseUrl,
198
+ publicBaseUrl: destination.verificationBaseUrl ?? destination.publicBaseUrl,
178
199
  ...(injected === undefined ? {} : { fetch: injected }),
179
200
  });
180
201
  }
@@ -190,12 +211,49 @@ export async function describeCapabilities(destination) {
190
211
  return Promise.resolve(buildCapabilities({ apiOrigin: context.apiOrigin }));
191
212
  }
192
213
 
214
+ /**
215
+ * The classified failure the adapter reports when the public origin answers
216
+ * with a redirect instead of the route: the destination's `publicBaseUrl` no
217
+ * longer names the host that serves the site (typically a custom domain was
218
+ * attached while the repository still carries the `github.io` base). The
219
+ * adapter follows no redirect, so it cannot tell what the origin serves.
220
+ *
221
+ * @typedef {Readonly<{
222
+ * code: 'PAGES_PUBLIC_REDIRECT',
223
+ * toHost: string | null,
224
+ * location: string | null
225
+ * }>} PublicRedirectFailure
226
+ */
227
+
228
+ /**
229
+ * @param {{toHost?: string | null, location?: string | null}} redirect a
230
+ * `'redirect'` public read
231
+ * @returns {PublicRedirectFailure} the classified failure
232
+ */
233
+ function publicRedirectFailure(redirect) {
234
+ return Object.freeze({
235
+ code: /** @type {const} */ ('PAGES_PUBLIC_REDIRECT'),
236
+ toHost: redirect.toHost ?? null,
237
+ location: redirect.location ?? null,
238
+ });
239
+ }
240
+
241
+ /**
242
+ * @param {PublicRedirectFailure} failure the classified failure
243
+ * @returns {string} the finding that states it
244
+ */
245
+ function publicRedirectFinding(failure) {
246
+ return `${failure.code}: the public origin answered with a redirect to ${failure.toHost ?? 'a target it did not name as an http(s) URL'} instead of serving the route; the site's base URL no longer names the host that serves it, so set the base URL to the redirect target and publish again`;
247
+ }
248
+
193
249
  /**
194
250
  * Read the generation identity the public origin currently serves, or
195
- * `null` when nothing has ever been activated.
251
+ * `null` when nothing has ever been activated. A redirecting origin is
252
+ * reported as the `PAGES_PUBLIC_REDIRECT` failure with the generation
253
+ * unknown, never thrown.
196
254
  *
197
255
  * @param {PagesDestination} destination the bound destination
198
- * @returns {Promise<{generationId: string | null, artifactDigest: string | null, findings: string[]}>}
256
+ * @returns {Promise<{generationId: string | null, artifactDigest: string | null, findings: string[], cacheControl?: string | null | undefined, failure?: PublicRedirectFailure}>}
199
257
  * the observed public generation
200
258
  */
201
259
  async function readServedGeneration(destination) {
@@ -203,13 +261,28 @@ async function readServedGeneration(destination) {
203
261
  publicContextFor(destination),
204
262
  GENERATION_MARKER_PATH,
205
263
  );
264
+ if (observation.status === 'redirect') {
265
+ const failure = publicRedirectFailure(observation);
266
+ return {
267
+ generationId: null,
268
+ artifactDigest: null,
269
+ findings: [publicRedirectFinding(failure)],
270
+ failure,
271
+ };
272
+ }
206
273
  if (observation.status === 404) {
207
- return { generationId: null, artifactDigest: null, findings: [] };
274
+ return {
275
+ generationId: null,
276
+ artifactDigest: null,
277
+ findings: [],
278
+ cacheControl: observation.cacheControl,
279
+ };
208
280
  }
209
281
  if (observation.status !== 200 || observation.bytes === null) {
210
282
  return {
211
283
  generationId: null,
212
284
  artifactDigest: null,
285
+ cacheControl: observation.cacheControl,
213
286
  findings: [
214
287
  `public generation marker read returned HTTP ${observation.status}; the served generation is unknown, not absent`,
215
288
  ],
@@ -221,12 +294,14 @@ async function readServedGeneration(destination) {
221
294
  generationId: null,
222
295
  artifactDigest: null,
223
296
  findings: parsed.findings,
297
+ cacheControl: observation.cacheControl,
224
298
  };
225
299
  }
226
300
  return {
227
301
  generationId: String(parsed.marker.generationId),
228
302
  artifactDigest: String(parsed.marker.artifactDigest),
229
303
  findings: [],
304
+ cacheControl: observation.cacheControl,
230
305
  };
231
306
  }
232
307
 
@@ -240,7 +315,8 @@ async function readServedGeneration(destination) {
240
315
  * retainedHistory: readonly Readonly<Record<string, unknown>>[],
241
316
  * releaseGenerationsOnDisk: readonly string[],
242
317
  * providerSiteObserved: boolean,
243
- * findings: readonly string[]
318
+ * findings: readonly string[],
319
+ * failure?: PublicRedirectFailure
244
320
  * }>>} the inspection result
245
321
  */
246
322
  export async function inspectDestination(destination) {
@@ -273,6 +349,7 @@ export async function inspectDestination(destination) {
273
349
  ),
274
350
  providerSiteObserved,
275
351
  findings: Object.freeze(findings),
352
+ ...(served.failure === undefined ? {} : { failure: served.failure }),
276
353
  });
277
354
  }
278
355
 
@@ -378,8 +455,9 @@ export async function stage(input) {
378
455
  continue;
379
456
  }
380
457
  if (existing.artifactDigest !== input.artifactDigest) {
381
- throw new Error(
382
- `IDEMPOTENCY_KEY_REUSE_CONFLICT: idempotency key ${JSON.stringify(input.idempotencyKey)} was already used for a different artifact digest`,
458
+ throw new PagesAdapterError(
459
+ `IDEMPOTENCY_KEY_REUSE_CONFLICT`,
460
+ `idempotency key ${JSON.stringify(input.idempotencyKey)} was already used for a different artifact digest`,
383
461
  );
384
462
  }
385
463
  return Object.freeze({
@@ -407,8 +485,9 @@ export async function stage(input) {
407
485
  ];
408
486
  const carrierBytes = encodeCarrier(carrierFiles);
409
487
  if (carrierBytes.byteLength > MAXIMUM_PAGES_CARRIER_BYTES) {
410
- throw new Error(
411
- `PAGES_CARRIER_TOO_LARGE: ${carrierBytes.byteLength} bytes exceed the ${MAXIMUM_PAGES_CARRIER_BYTES}-byte Pages artifact ceiling`,
488
+ throw new PagesAdapterError(
489
+ `PAGES_CARRIER_TOO_LARGE`,
490
+ `${carrierBytes.byteLength} bytes exceed the ${MAXIMUM_PAGES_CARRIER_BYTES}-byte Pages artifact ceiling`,
412
491
  );
413
492
  }
414
493
  const carrierDigest = sha256Hex(carrierBytes);
@@ -423,8 +502,9 @@ export async function stage(input) {
423
502
  published.artifactDigest !== undefined &&
424
503
  published.artifactDigest !== carrierDigest
425
504
  ) {
426
- throw new Error(
427
- `PAGES_CARRIER_HANDOFF_MISMATCH: the artifact publisher reported digest ${published.artifactDigest} for a carrier whose bytes digest to ${carrierDigest}`,
505
+ throw new PagesAdapterError(
506
+ `PAGES_CARRIER_HANDOFF_MISMATCH`,
507
+ `the artifact publisher reported digest ${published.artifactDigest} for a carrier whose bytes digest to ${carrierDigest}`,
428
508
  );
429
509
  }
430
510
 
@@ -441,6 +521,9 @@ export async function stage(input) {
441
521
  artifactId: input.artifactId,
442
522
  artifactDigest: input.artifactDigest,
443
523
  entryPaths: Object.freeze(input.files.map((file) => file.path)),
524
+ entries: Object.freeze(
525
+ input.files.map((file) => projectEntry(file.path, file.bytes)),
526
+ ),
444
527
  carrierBytes,
445
528
  carrierDigest,
446
529
  pagesArtifactId,
@@ -507,8 +590,9 @@ export async function recoverPriorAttempt(input) {
507
590
  function requirePagesOidc(destination, input) {
508
591
  const token = input.pagesOidcToken ?? destination.oidcToken;
509
592
  if (typeof token !== 'string' || token === '') {
510
- throw new Error(
511
- 'PAGES_OIDC_TOKEN_REQUIRED: oidc_token is a mandatory member of the create request entity (DEC-097 section 7). Supply it as input.pagesOidcToken or destination.oidcToken; this repository never mints a credential.',
593
+ throw new PagesAdapterError(
594
+ 'PAGES_OIDC_TOKEN_REQUIRED',
595
+ 'oidc_token is a mandatory member of the create request entity (DEC-097 section 7). Supply it as input.pagesOidcToken or destination.oidcToken; this repository never mints a credential.',
512
596
  );
513
597
  }
514
598
  const claims = requireOidcExpectation(
@@ -518,8 +602,9 @@ function requirePagesOidc(destination, input) {
518
602
  destination.repositoryId === undefined ||
519
603
  destination.repositoryOwnerId === undefined
520
604
  ) {
521
- throw new Error(
522
- 'PAGES_OIDC_EXPECTATION_INVALID: destination.repositoryId and destination.repositoryOwnerId are required so the two admitted subject forms can be recomputed from the verified claims',
605
+ throw new PagesAdapterError(
606
+ 'PAGES_OIDC_EXPECTATION_INVALID',
607
+ 'destination.repositoryId and destination.repositoryOwnerId are required so the two admitted subject forms can be recomputed from the verified claims',
523
608
  );
524
609
  }
525
610
  return {
@@ -577,13 +662,15 @@ export async function activate(input) {
577
662
  );
578
663
  const mode = input.mode ?? NORMAL_MODE;
579
664
  if (!AUTHORITY_MODES.includes(mode)) {
580
- throw new Error(
581
- `PAGES_AUTHORITY_MODE_INVALID: ${JSON.stringify(mode)} is not one of ${AUTHORITY_MODES.join(', ')}`,
665
+ throw new PagesAdapterError(
666
+ `PAGES_AUTHORITY_MODE_INVALID`,
667
+ `${JSON.stringify(mode)} is not one of ${AUTHORITY_MODES.join(', ')}`,
582
668
  );
583
669
  }
584
670
  if (mode === NORMAL_MODE && input.pagesRecovery !== undefined) {
585
- throw new Error(
586
- 'PAGES_RECOVERY_RECORD_FORBIDDEN: normal mode forbids pagesRecovery and every recovery-prior call',
671
+ throw new PagesAdapterError(
672
+ 'PAGES_RECOVERY_RECORD_FORBIDDEN',
673
+ 'normal mode forbids pagesRecovery and every recovery-prior call',
587
674
  );
588
675
  }
589
676
  const oidc = requirePagesOidc(input.destination, input);
@@ -616,6 +703,8 @@ export async function activate(input) {
616
703
  certifiedAt: new Date().toISOString(),
617
704
  entryPaths:
618
705
  state.stages.get(input.stageToken)?.entryPaths ?? Object.freeze([]),
706
+ entries:
707
+ state.stages.get(input.stageToken)?.entries ?? Object.freeze([]),
619
708
  });
620
709
  return Object.freeze({
621
710
  decision: /** @type {'activate'} */ ('activate'),
@@ -673,8 +762,9 @@ export async function activate(input) {
673
762
 
674
763
  const record = state.stages.get(input.stageToken);
675
764
  if (record === undefined) {
676
- throw new Error(
677
- `PAGES_STAGE_NOT_FOUND: stage token ${JSON.stringify(input.stageToken)} has no staged carrier in this run`,
765
+ throw new PagesAdapterError(
766
+ `PAGES_STAGE_NOT_FOUND`,
767
+ `stage token ${JSON.stringify(input.stageToken)} has no staged carrier in this run`,
678
768
  );
679
769
  }
680
770
 
@@ -689,8 +779,9 @@ export async function activate(input) {
689
779
  .map((file) => projectEntry(file.path, file.bytes)),
690
780
  );
691
781
  if (recomputed !== input.expectedArtifactDigest) {
692
- throw new Error(
693
- `STAGE_INTEGRITY_MISMATCH: staged carrier digests to ${recomputed}, which disagrees with the expected artifact digest ${input.expectedArtifactDigest}; refusing to promote a partial or tampered stage`,
782
+ throw new PagesAdapterError(
783
+ `STAGE_INTEGRITY_MISMATCH`,
784
+ `staged carrier digests to ${recomputed}, which disagrees with the expected artifact digest ${input.expectedArtifactDigest}; refusing to promote a partial or tampered stage`,
694
785
  );
695
786
  }
696
787
  }
@@ -703,18 +794,7 @@ export async function activate(input) {
703
794
  }
704
795
 
705
796
  const pagesBuildVersion = derivePagesBuildVersion({
706
- destinationKey: destinationKey(input.destination),
707
- operationId: record.operationId,
708
- attemptId: record.attemptId,
709
- ...(input.destination.runId === undefined
710
- ? {}
711
- : { runId: input.destination.runId }),
712
- ...(input.destination.runAttempt === undefined
713
- ? {}
714
- : { runAttempt: input.destination.runAttempt }),
715
- artifactId: record.artifactId,
716
- artifactDigest: record.artifactDigest,
717
- generationId: input.generationId,
797
+ headSha: input.destination.headSha,
718
798
  });
719
799
 
720
800
  const context = bindIdentity(baseContext, {
@@ -740,8 +820,9 @@ export async function activate(input) {
740
820
  state.inFlight.delete(input.generationId);
741
821
 
742
822
  if (!polled.succeeded) {
743
- throw new Error(
744
- `PAGES_DEPLOYMENT_FAILED: deployment ${pagesBuildVersion} reached terminal status ${polled.status}`,
823
+ throw new PagesAdapterError(
824
+ `PAGES_DEPLOYMENT_FAILED`,
825
+ `deployment ${pagesBuildVersion} reached terminal status ${polled.status}`,
745
826
  );
746
827
  }
747
828
 
@@ -753,6 +834,7 @@ export async function activate(input) {
753
834
  // staged carrier so `cleanupStaged` can discard the carrier without
754
835
  // taking `observe`'s ability to verify the live generation with it.
755
836
  entryPaths: record.entryPaths,
837
+ entries: record.entries,
756
838
  });
757
839
 
758
840
  return Object.freeze({
@@ -787,14 +869,415 @@ export async function activate(input) {
787
869
  * currentGenerationId: string | null,
788
870
  * markerValid: boolean,
789
871
  * claimsCompleteInventory: false,
790
- * findings: readonly string[]
872
+ * findings: readonly string[],
873
+ * failure?: PublicRedirectFailure
791
874
  * }>>} the observation result
792
875
  */
793
876
  export async function observe(input) {
794
877
  restContextFor(input.destination);
878
+ const sleep = input.destination.sleep ?? defaultSleep;
879
+ const clock = input.destination.now ?? Date.now;
880
+ const startedAt = clock();
881
+ let slept = 0;
882
+ let delay = OBSERVE_FIRST_DELAY_SECONDS;
883
+ /** @type {ObserveProgress} */
884
+ const progress = {
885
+ matched: new Map(),
886
+ matchedPass: new Map(),
887
+ latest: new Map(),
888
+ statuses: new Map(),
889
+ served: null,
890
+ markerPass: -1,
891
+ pass: 0,
892
+ cursor: 0,
893
+ confirmed: false,
894
+ errorCode: null,
895
+ errorStreak: 0,
896
+ };
897
+ let attempt = await observeOnce(input, progress);
898
+ let deadline = observeDeadlineSeconds(attempt.maxAgeSeconds);
899
+ for (;;) {
900
+ const result = { ...attempt };
901
+ const retryable = attempt.retryable;
902
+ // @ts-expect-error the retry hints are internal and never returned
903
+ delete result.retryable;
904
+ // @ts-expect-error the retry hints are internal and never returned
905
+ delete result.maxAgeSeconds;
906
+ if (result.verified || !retryable) {
907
+ return Object.freeze(result);
908
+ }
909
+ deadline = Math.max(
910
+ deadline,
911
+ observeDeadlineSeconds(attempt.maxAgeSeconds),
912
+ );
913
+ const elapsed = Math.max(slept, (clock() - startedAt) / 1000);
914
+ const wait = Math.min(delay, deadline - elapsed);
915
+ if (wait <= 0) {
916
+ return Object.freeze(result);
917
+ }
918
+ await sleep(wait);
919
+ slept += wait;
920
+ delay = Math.min(delay * 2, OBSERVE_MAXIMUM_DELAY_SECONDS);
921
+ attempt = await observeOnce(input, progress);
922
+ }
923
+ }
924
+
925
+ /** First wait between observations, doubling up to the maximum. */
926
+ const OBSERVE_FIRST_DELAY_SECONDS = 5;
927
+ /** Longest wait between two observations. */
928
+ const OBSERVE_MAXIMUM_DELAY_SECONDS = 30;
929
+ /** Lifetime assumed when the origin declares no `max-age`. */
930
+ const OBSERVE_DEFAULT_MAX_AGE_SECONDS = 600;
931
+ /** Longest declared `max-age` that is waited out. */
932
+ const OBSERVE_MAXIMUM_MAX_AGE_SECONDS = 900;
933
+ /** Margin added to the cache lifetime. */
934
+ const OBSERVE_MARGIN_SECONDS = 60;
935
+
936
+ /**
937
+ * How long a stale public read may keep disagreeing: the CDN lifetime plus a
938
+ * margin.
939
+ *
940
+ * @param {number | null} declared the largest `max-age` seen, if any
941
+ * @returns {number} the deadline in seconds since the first observation
942
+ */
943
+ function observeDeadlineSeconds(declared) {
944
+ const lifetime = Math.min(
945
+ declared ?? OBSERVE_DEFAULT_MAX_AGE_SECONDS,
946
+ OBSERVE_MAXIMUM_MAX_AGE_SECONDS,
947
+ );
948
+ return Math.max(lifetime, 0) + OBSERVE_MARGIN_SECONDS;
949
+ }
950
+
951
+ /**
952
+ * @param {number} seconds seconds to wait
953
+ * @returns {Promise<void>} resolves after the wait
954
+ */
955
+ function defaultSleep(seconds) {
956
+ return new Promise((resolve) => {
957
+ setTimeout(resolve, seconds * 1000);
958
+ });
959
+ }
960
+
961
+ /**
962
+ * What `observe` keeps between passes so a retry reads only what is still
963
+ * wrong: the routes whose bytes already match the staged entry, the latest
964
+ * bytes of the others, and the marker read until it matches.
965
+ *
966
+ * @typedef {{
967
+ * matched: Map<string, import('./artifact-projection.js').ArtifactEntry>,
968
+ * matchedPass: Map<string, number>,
969
+ * latest: Map<string, import('./artifact-projection.js').ArtifactEntry>,
970
+ * statuses: Map<string, number>,
971
+ * served: Awaited<ReturnType<typeof readServedGeneration>> | null,
972
+ * markerPass: number,
973
+ * pass: number,
974
+ * cursor: number,
975
+ * confirmed: boolean,
976
+ * errorCode: string | null,
977
+ * errorStreak: number
978
+ * }} ObserveProgress
979
+ */
980
+
981
+ /**
982
+ * Stale routes re-read per pass after the first. A pass reads at most this
983
+ * many plus the marker until the sample matches; the request count is about
984
+ * passes x (K + 1) + 2 x routes, with no cap that can fire inside a CDN
985
+ * lifetime.
986
+ */
987
+ const OBSERVE_SAMPLE_ROUTES = 20;
988
+ /** Largest site whose early matches are confirmed again before success. */
989
+ const OBSERVE_CONFIRM_MAXIMUM_ROUTES = 50;
990
+ /** Consecutive passes failing with one transient code before giving up. */
991
+ const OBSERVE_TRANSIENT_STREAK = 3;
992
+ /** Most unmatched routes named individually in the findings. */
993
+ const OBSERVE_FINDINGS_NAMED = 10;
994
+
995
+ const TRANSIENT_CODES = new Set([
996
+ 'ECONNRESET',
997
+ 'ETIMEDOUT',
998
+ 'ECONNREFUSED',
999
+ 'EPIPE',
1000
+ 'EAI_AGAIN',
1001
+ 'UND_ERR_SOCKET',
1002
+ 'UND_ERR_CONNECT_TIMEOUT',
1003
+ 'UND_ERR_HEADERS_TIMEOUT',
1004
+ 'UND_ERR_BODY_TIMEOUT',
1005
+ ]);
1006
+
1007
+ /**
1008
+ * @param {string} code a network error code
1009
+ * @returns {boolean} whether it is a certificate, TLS or name-resolution
1010
+ * failure that waiting cannot cure
1011
+ */
1012
+ function isFatalCode(code) {
1013
+ return (
1014
+ code === 'ENOTFOUND' ||
1015
+ code === 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' ||
1016
+ code === 'DEPTH_ZERO_SELF_SIGNED_CERT' ||
1017
+ code.startsWith('CERT_') ||
1018
+ code.startsWith('ERR_TLS_') ||
1019
+ code.startsWith('ERR_SSL_')
1020
+ );
1021
+ }
1022
+
1023
+ /**
1024
+ * Every error code carried by a thrown fetch failure, its cause and the
1025
+ * causes' aggregated errors.
1026
+ *
1027
+ * @param {unknown} error the thrown value
1028
+ * @returns {string[]} the codes found
1029
+ */
1030
+ function errorCodes(error) {
1031
+ /** @type {string[]} */
1032
+ const codes = [];
1033
+ /** @type {unknown[]} */
1034
+ const queue = [error];
1035
+ for (let depth = 0; queue.length > 0 && depth < 16; depth += 1) {
1036
+ const current = /** @type {any} */ (queue.shift());
1037
+ if (current === null || typeof current !== 'object') {
1038
+ continue;
1039
+ }
1040
+ if (typeof current.code === 'string') {
1041
+ codes.push(current.code);
1042
+ }
1043
+ queue.push(current.cause);
1044
+ if (Array.isArray(current.errors)) {
1045
+ queue.push(...current.errors);
1046
+ }
1047
+ }
1048
+ return codes;
1049
+ }
1050
+
1051
+ /**
1052
+ * Classify a failed public read. Only transient transport failures are
1053
+ * waited out; typed adapter errors, name-resolution, certificate and TLS
1054
+ * failures and programming errors fail fast.
1055
+ *
1056
+ * @param {unknown} error the thrown value
1057
+ * @returns {string | null} the transient code, or null when it must throw
1058
+ */
1059
+ function transientCode(error) {
1060
+ if (error instanceof PagesAdapterError) {
1061
+ return null;
1062
+ }
1063
+ const codes = errorCodes(error);
1064
+ if (codes.some(isFatalCode)) {
1065
+ return null;
1066
+ }
1067
+ const code = codes.find((candidate) => TRANSIENT_CODES.has(candidate));
1068
+ if (code !== undefined) {
1069
+ return code;
1070
+ }
1071
+ if (error instanceof Error && error.name === 'TimeoutError') {
1072
+ return 'TimeoutError';
1073
+ }
1074
+ return null;
1075
+ }
1076
+
1077
+ /**
1078
+ * @param {unknown} error the thrown value
1079
+ * @returns {string} a short, single-line description
1080
+ */
1081
+ function describeReadError(error) {
1082
+ const text = error instanceof Error ? error.message : String(error);
1083
+ return text.replaceAll(/\s+/gu, ' ').slice(0, 200);
1084
+ }
1085
+
1086
+ /**
1087
+ * One observation pass. `retryable` is false for hard failures (a redirect,
1088
+ * a generation this run never staged, a repeating transport failure), which
1089
+ * no waiting can change. The first pass reads the marker and every route.
1090
+ * Later passes read the marker until it matches and a rotating sample of the
1091
+ * still-unmatched routes; once the sample and the marker match, the rest of
1092
+ * the unmatched routes are read in the same pass. Before success a small
1093
+ * site re-reads what matched in earlier passes. The digest is computed over
1094
+ * the whole coherent set.
1095
+ *
1096
+ * @param {Parameters<typeof observe>[0]} input the observe input
1097
+ * @param {ObserveProgress} progress what earlier passes learned
1098
+ * @returns {Promise<Awaited<ReturnType<typeof observe>> & {retryable: boolean, maxAgeSeconds: number | null}>}
1099
+ * the observation and its retry hints
1100
+ */
1101
+ async function observeOnce(input, progress) {
795
1102
  const state = stateFor(input.destination);
796
- const served = await readServedGeneration(input.destination);
1103
+ const staged =
1104
+ state.activations.get(input.generationId) ??
1105
+ [...state.stages.values()].find(
1106
+ (candidate) => candidate.generationId === input.generationId,
1107
+ );
1108
+ const entryPaths = staged?.entryPaths;
1109
+ const pass = progress.pass;
1110
+ progress.pass += 1;
1111
+ /** @type {{text: string, code: string}[]} */
1112
+ const readErrors = [];
1113
+ /** @type {number | null} */
1114
+ let seenMaxAge = null;
1115
+ /** @type {PublicRedirectFailure | undefined} */
1116
+ let failure;
797
1117
 
1118
+ const markerMatches = () =>
1119
+ progress.served !== null &&
1120
+ progress.served.generationId === input.generationId &&
1121
+ progress.served.artifactDigest === input.expectedArtifactDigest;
1122
+
1123
+ const readMarker = async () => {
1124
+ try {
1125
+ progress.served = await readServedGeneration(input.destination);
1126
+ progress.markerPass = pass;
1127
+ } catch (error) {
1128
+ const code = transientCode(error);
1129
+ if (code === null) {
1130
+ throw error;
1131
+ }
1132
+ readErrors.push({
1133
+ text: `${GENERATION_MARKER_PATH}: ${describeReadError(error)}`,
1134
+ code,
1135
+ });
1136
+ progress.served ??= {
1137
+ generationId: null,
1138
+ artifactDigest: null,
1139
+ findings: [],
1140
+ };
1141
+ }
1142
+ if (progress.served.failure !== undefined) {
1143
+ failure = progress.served.failure;
1144
+ }
1145
+ const age = maxAgeSeconds(progress.served.cacheControl);
1146
+ if (age !== null && age > (seenMaxAge ?? -1)) {
1147
+ seenMaxAge = age;
1148
+ }
1149
+ };
1150
+
1151
+ if (!markerMatches()) {
1152
+ await readMarker();
1153
+ }
1154
+
1155
+ /** @type {string | undefined} */
1156
+ let redirectedRoute;
1157
+ if (failure === undefined && entryPaths !== undefined) {
1158
+ const publicContext = publicContextFor(input.destination);
1159
+ const expectedByPath = new Map(
1160
+ (staged?.entries ?? []).map((entry) => [entry.path, entry]),
1161
+ );
1162
+ /**
1163
+ * @param {string} entryPath the route
1164
+ * @returns {Promise<boolean>} false when the origin redirects
1165
+ */
1166
+ const readRoute = async (entryPath) => {
1167
+ /** @type {Awaited<ReturnType<typeof readPublic>>} */
1168
+ let read;
1169
+ try {
1170
+ read = await readPublic(publicContext, entryPath);
1171
+ } catch (error) {
1172
+ const code = transientCode(error);
1173
+ if (code === null) {
1174
+ throw error;
1175
+ }
1176
+ readErrors.push({
1177
+ text: `${entryPath}: ${describeReadError(error)}`,
1178
+ code,
1179
+ });
1180
+ return true;
1181
+ }
1182
+ const age = maxAgeSeconds(read.cacheControl);
1183
+ if (age !== null && age > (seenMaxAge ?? -1)) {
1184
+ seenMaxAge = age;
1185
+ }
1186
+ if (read.status === 'redirect') {
1187
+ failure = publicRedirectFailure(read);
1188
+ redirectedRoute = entryPath;
1189
+ return false;
1190
+ }
1191
+ if (read.status !== 200 || read.bytes === null) {
1192
+ progress.latest.delete(entryPath);
1193
+ progress.matched.delete(entryPath);
1194
+ progress.statuses.set(entryPath, read.status);
1195
+ return true;
1196
+ }
1197
+ progress.statuses.delete(entryPath);
1198
+ const entry = projectEntry(entryPath, read.bytes);
1199
+ const expected = expectedByPath.get(entryPath);
1200
+ if (
1201
+ expected !== undefined &&
1202
+ expected.sha256 === entry.sha256 &&
1203
+ expected.byteLength === entry.byteLength
1204
+ ) {
1205
+ progress.matched.set(entryPath, entry);
1206
+ progress.matchedPass.set(entryPath, pass);
1207
+ progress.latest.delete(entryPath);
1208
+ } else {
1209
+ progress.matched.delete(entryPath);
1210
+ progress.latest.set(entryPath, entry);
1211
+ }
1212
+ return true;
1213
+ };
1214
+
1215
+ const unmatched = entryPaths.filter(
1216
+ (entryPath) => !progress.matched.has(entryPath),
1217
+ );
1218
+ /** @type {string[]} */
1219
+ let sample = unmatched;
1220
+ if (pass > 0 && unmatched.length > OBSERVE_SAMPLE_ROUTES) {
1221
+ const start = progress.cursor % unmatched.length;
1222
+ sample = [];
1223
+ for (let offset = 0; offset < OBSERVE_SAMPLE_ROUTES; offset += 1) {
1224
+ sample.push(
1225
+ /** @type {string} */ (
1226
+ unmatched[(start + offset) % unmatched.length]
1227
+ ),
1228
+ );
1229
+ }
1230
+ progress.cursor += OBSERVE_SAMPLE_ROUTES;
1231
+ }
1232
+ let redirected = false;
1233
+ for (const entryPath of sample) {
1234
+ if (!(await readRoute(entryPath))) {
1235
+ redirected = true;
1236
+ break;
1237
+ }
1238
+ }
1239
+ if (
1240
+ !redirected &&
1241
+ sample.length < unmatched.length &&
1242
+ markerMatches() &&
1243
+ sample.every((entryPath) => progress.matched.has(entryPath))
1244
+ ) {
1245
+ const sampled = new Set(sample);
1246
+ for (const entryPath of unmatched) {
1247
+ if (!sampled.has(entryPath) && !(await readRoute(entryPath))) {
1248
+ redirected = true;
1249
+ break;
1250
+ }
1251
+ }
1252
+ }
1253
+ if (
1254
+ !redirected &&
1255
+ !progress.confirmed &&
1256
+ pass > 0 &&
1257
+ entryPaths.length <= OBSERVE_CONFIRM_MAXIMUM_ROUTES &&
1258
+ readErrors.length === 0 &&
1259
+ markerMatches() &&
1260
+ entryPaths.every((entryPath) => progress.matched.has(entryPath))
1261
+ ) {
1262
+ // About to succeed: re-read what matched only in earlier passes.
1263
+ progress.confirmed = true;
1264
+ if (progress.markerPass < pass) {
1265
+ await readMarker();
1266
+ }
1267
+ for (const entryPath of entryPaths) {
1268
+ if (
1269
+ (progress.matchedPass.get(entryPath) ?? pass) < pass &&
1270
+ !(await readRoute(entryPath))
1271
+ ) {
1272
+ break;
1273
+ }
1274
+ }
1275
+ }
1276
+ }
1277
+
1278
+ const served = /** @type {NonNullable<typeof progress.served>} */ (
1279
+ progress.served
1280
+ );
798
1281
  /** @type {string[]} */
799
1282
  const findings = [...served.findings];
800
1283
  if (served.generationId !== input.generationId) {
@@ -802,43 +1285,82 @@ export async function observe(input) {
802
1285
  `the public marker names generation ${JSON.stringify(served.generationId)}, not the observed generation ${JSON.stringify(input.generationId)}`,
803
1286
  );
804
1287
  }
805
- const markerValid =
806
- served.generationId === input.generationId &&
807
- served.artifactDigest === input.expectedArtifactDigest;
1288
+ const markerValid = markerMatches();
808
1289
  if (!markerValid) {
809
1290
  findings.push(
810
1291
  'the public generation marker is missing, invalid or disagrees with the expected identity',
811
1292
  );
812
1293
  }
813
1294
 
814
- const activation = state.activations.get(input.generationId);
815
- const entryPaths =
816
- activation?.entryPaths ??
817
- [...state.stages.values()].find(
818
- (candidate) => candidate.generationId === input.generationId,
819
- )?.entryPaths;
1295
+ let retryable = true;
820
1296
  /** @type {string | null} */
821
1297
  let observedArtifactDigest = null;
822
- if (entryPaths === undefined) {
1298
+ if (failure !== undefined) {
1299
+ // The origin redirects, so every route would redirect too: say so once
1300
+ // instead of asking for each of them.
1301
+ retryable = false;
1302
+ if (redirectedRoute !== undefined) {
1303
+ findings.push(`${redirectedRoute}: ${publicRedirectFinding(failure)}`);
1304
+ }
1305
+ } else if (entryPaths === undefined) {
1306
+ retryable = false;
823
1307
  findings.push(
824
1308
  'this run did not stage the observed generation, so its route inventory cannot be verified here',
825
1309
  );
826
1310
  } else {
827
- const publicContext = publicContextFor(input.destination);
828
- /** @type {import('./artifact-projection.js').ArtifactEntry[]} */
829
- const entries = [];
830
- for (const entryPath of entryPaths) {
831
- const read = await readPublic(publicContext, entryPath);
832
- if (read.status !== 200 || read.bytes === null) {
833
- findings.push(`${entryPath}: public read returned HTTP ${read.status}`);
834
- continue;
1311
+ const unmatchedNow = entryPaths.filter(
1312
+ (entryPath) => !progress.matched.has(entryPath),
1313
+ );
1314
+ for (const entryPath of unmatchedNow.slice(0, OBSERVE_FINDINGS_NAMED)) {
1315
+ const status = progress.statuses.get(entryPath);
1316
+ if (status !== undefined) {
1317
+ findings.push(`${entryPath}: public read returned HTTP ${status}`);
1318
+ } else if (progress.latest.has(entryPath)) {
1319
+ findings.push(`${entryPath}: bytes do not yet match the staged entry`);
1320
+ } else if (
1321
+ !readErrors.some((error) => error.text.startsWith(`${entryPath}: `))
1322
+ ) {
1323
+ findings.push(`${entryPath}: not yet read`);
835
1324
  }
836
- entries.push(projectEntry(entryPath, read.bytes));
837
1325
  }
838
- observedArtifactDigest = digestEntries(entries);
839
- if (observedArtifactDigest !== input.expectedArtifactDigest) {
1326
+ if (unmatchedNow.length > OBSERVE_FINDINGS_NAMED) {
1327
+ findings.push(
1328
+ `${unmatchedNow.length - OBSERVE_FINDINGS_NAMED} more routes do not yet match the staged entries`,
1329
+ );
1330
+ }
1331
+ for (const readError of readErrors) {
1332
+ findings.push(`public read failed: ${readError.text}`);
1333
+ }
1334
+ const coherent = [
1335
+ ...progress.matched.values(),
1336
+ ...progress.latest.values(),
1337
+ ];
1338
+ if (coherent.length === entryPaths.length) {
1339
+ observedArtifactDigest = digestEntries(coherent);
1340
+ if (observedArtifactDigest !== input.expectedArtifactDigest) {
1341
+ findings.push(
1342
+ `the publicly observed artifact digest ${observedArtifactDigest} disagrees with the expected ${input.expectedArtifactDigest}`,
1343
+ );
1344
+ }
1345
+ }
1346
+ if (unmatchedNow.length === 0 && markerValid) {
1347
+ // Every route matches its staged entry and the marker matches, yet
1348
+ // the digest disagrees: no further reading can change that.
1349
+ retryable = false;
1350
+ }
1351
+ const code = readErrors[0]?.code ?? null;
1352
+ if (code === null) {
1353
+ progress.errorStreak = 0;
1354
+ } else if (code === progress.errorCode) {
1355
+ progress.errorStreak += 1;
1356
+ } else {
1357
+ progress.errorStreak = 1;
1358
+ }
1359
+ progress.errorCode = code;
1360
+ if (progress.errorStreak >= OBSERVE_TRANSIENT_STREAK) {
1361
+ retryable = false;
840
1362
  findings.push(
841
- `the publicly observed artifact digest ${observedArtifactDigest} disagrees with the expected ${input.expectedArtifactDigest}`,
1363
+ `the public read failed with ${code} on ${progress.errorStreak} consecutive passes; giving up`,
842
1364
  );
843
1365
  }
844
1366
  }
@@ -850,6 +1372,9 @@ export async function observe(input) {
850
1372
  markerValid,
851
1373
  claimsCompleteInventory: /** @type {false} */ (false),
852
1374
  findings: Object.freeze(findings),
1375
+ ...(failure === undefined ? {} : { failure }),
1376
+ retryable,
1377
+ maxAgeSeconds: seenMaxAge,
853
1378
  });
854
1379
  }
855
1380
 
@@ -931,8 +1456,9 @@ export async function rollback(input) {
931
1456
  (candidate) => candidate.generationId === input.targetGenerationId,
932
1457
  );
933
1458
  if (record === undefined) {
934
- throw new Error(
935
- `ROLLBACK_INPUT_UNAVAILABLE: generation ${JSON.stringify(input.targetGenerationId)} was not staged by this run and GitHub Pages cannot read a historical artifact back; supply its bytes through "files"`,
1459
+ throw new PagesAdapterError(
1460
+ `ROLLBACK_INPUT_UNAVAILABLE`,
1461
+ `generation ${JSON.stringify(input.targetGenerationId)} was not staged by this run and GitHub Pages cannot read a historical artifact back; supply its bytes through "files"`,
936
1462
  );
937
1463
  }
938
1464
  files = decodeCarrier(record.carrierBytes).filter(