@fastly/compute-js-static-publish 8.0.0-beta.2 → 8.0.0-beta.21

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.
Files changed (113) hide show
  1. package/README.md +19 -5
  2. package/README.short.md +19 -5
  3. package/build/cli/cli/commands/manage/clean.d.ts.map +1 -1
  4. package/build/cli/cli/commands/manage/clean.js +17 -24
  5. package/build/cli/cli/commands/manage/collections/delete.d.ts.map +1 -1
  6. package/build/cli/cli/commands/manage/collections/delete.js +13 -23
  7. package/build/cli/cli/commands/manage/collections/index.d.ts.map +1 -1
  8. package/build/cli/cli/commands/manage/collections/index.js +7 -15
  9. package/build/cli/cli/commands/manage/collections/list.d.ts.map +1 -1
  10. package/build/cli/cli/commands/manage/collections/list.js +12 -22
  11. package/build/cli/cli/commands/manage/collections/promote.d.ts.map +1 -1
  12. package/build/cli/cli/commands/manage/collections/promote.js +12 -22
  13. package/build/cli/cli/commands/manage/collections/update-expiration.d.ts.map +1 -1
  14. package/build/cli/cli/commands/manage/collections/update-expiration.js +12 -22
  15. package/build/cli/cli/commands/manage/index.d.ts.map +1 -1
  16. package/build/cli/cli/commands/manage/index.js +7 -15
  17. package/build/cli/cli/commands/manage/publish-content.d.ts.map +1 -1
  18. package/build/cli/cli/commands/manage/publish-content.js +201 -92
  19. package/build/cli/cli/commands/scaffold/index.d.ts.map +1 -1
  20. package/build/cli/cli/commands/scaffold/index.js +54 -32
  21. package/build/cli/cli/compression/brotli.d.ts +2 -1
  22. package/build/cli/cli/compression/brotli.d.ts.map +1 -1
  23. package/build/cli/cli/compression/brotli.js +15 -4
  24. package/build/cli/cli/compression/gzip.d.ts +2 -1
  25. package/build/cli/cli/compression/gzip.d.ts.map +1 -1
  26. package/build/cli/cli/compression/gzip.js +8 -4
  27. package/build/cli/cli/compression/index.d.ts +4 -1
  28. package/build/cli/cli/compression/index.d.ts.map +1 -1
  29. package/build/cli/cli/index.js +8 -0
  30. package/build/cli/cli/storage/kv-store-local-provider.d.ts +3 -5
  31. package/build/cli/cli/storage/kv-store-local-provider.d.ts.map +1 -1
  32. package/build/cli/cli/storage/kv-store-local-provider.js +3 -8
  33. package/build/cli/cli/storage/kv-store-provider.d.ts +4 -5
  34. package/build/cli/cli/storage/kv-store-provider.d.ts.map +1 -1
  35. package/build/cli/cli/storage/kv-store-provider.js +38 -66
  36. package/build/cli/cli/storage/s3-storage-provider.d.ts +6 -6
  37. package/build/cli/cli/storage/s3-storage-provider.d.ts.map +1 -1
  38. package/build/cli/cli/storage/s3-storage-provider.js +54 -51
  39. package/build/cli/cli/storage/storage-provider.d.ts +9 -8
  40. package/build/cli/cli/storage/storage-provider.d.ts.map +1 -1
  41. package/build/cli/cli/storage/storage-provider.js +13 -0
  42. package/build/cli/cli/util/api-token.d.ts.map +1 -1
  43. package/build/cli/cli/util/api-token.js +0 -28
  44. package/build/cli/cli/util/config.d.ts.map +1 -1
  45. package/build/cli/cli/util/config.js +8 -1
  46. package/build/cli/cli/util/content-types.d.ts.map +1 -1
  47. package/build/cli/cli/util/content-types.js +5 -2
  48. package/build/cli/cli/util/kv-store-items.d.ts +12 -0
  49. package/build/cli/cli/util/kv-store-items.d.ts.map +1 -1
  50. package/build/cli/cli/util/kv-store-items.js +49 -0
  51. package/build/cli/cli/util/kv-store.d.ts +6 -0
  52. package/build/cli/cli/util/kv-store.d.ts.map +1 -1
  53. package/build/cli/cli/util/kv-store.js +39 -2
  54. package/build/cli/cli/util/purge.d.ts +19 -0
  55. package/build/cli/cli/util/purge.d.ts.map +1 -0
  56. package/build/cli/cli/util/purge.js +83 -0
  57. package/build/cli/cli/util/retryable.d.ts +2 -1
  58. package/build/cli/cli/util/retryable.d.ts.map +1 -1
  59. package/build/cli/cli/util/retryable.js +34 -1
  60. package/build/cli/cli/util/s3-credentials.d.ts +11 -0
  61. package/build/cli/cli/util/s3-credentials.d.ts.map +1 -0
  62. package/build/cli/cli/util/s3-credentials.js +38 -0
  63. package/build/cli/cli/util/s3.d.ts +1 -1
  64. package/build/cli/cli/util/s3.d.ts.map +1 -1
  65. package/build/cli/cli/util/s3.js +1 -1
  66. package/build/cli/cli/util/service-id.d.ts +10 -0
  67. package/build/cli/cli/util/service-id.d.ts.map +1 -0
  68. package/build/cli/cli/util/service-id.js +27 -0
  69. package/build/cli/cli/util/variants.d.ts +2 -1
  70. package/build/cli/cli/util/variants.d.ts.map +1 -1
  71. package/build/cli/cli/util/variants.js +8 -4
  72. package/build/cli/models/assets/index.js +1 -1
  73. package/build/cli/models/config/publish-content-config.d.ts +2 -0
  74. package/build/cli/models/config/publish-content-config.d.ts.map +1 -1
  75. package/build/cli/models/config/s3-storage-config.d.ts +1 -0
  76. package/build/cli/models/config/s3-storage-config.d.ts.map +1 -1
  77. package/build/cli/models/config/s3-storage-config.js +1 -0
  78. package/build/cli/models/config/static-publish-rc.d.ts +1 -0
  79. package/build/cli/models/config/static-publish-rc.d.ts.map +1 -1
  80. package/build/cli/models/config/static-publish-rc.js +3 -1
  81. package/build/cli/models/metadata/index.js +1 -1
  82. package/build/server/models/assets/index.js +1 -1
  83. package/build/server/models/config/publish-content-config.d.ts +2 -0
  84. package/build/server/models/config/publish-content-config.d.ts.map +1 -1
  85. package/build/server/models/config/s3-storage-config.d.ts +1 -0
  86. package/build/server/models/config/s3-storage-config.d.ts.map +1 -1
  87. package/build/server/models/config/s3-storage-config.js +1 -0
  88. package/build/server/models/config/static-publish-rc.d.ts +1 -0
  89. package/build/server/models/config/static-publish-rc.d.ts.map +1 -1
  90. package/build/server/models/config/static-publish-rc.js +3 -1
  91. package/build/server/models/metadata/index.js +1 -1
  92. package/build/server/server/index.d.ts +1 -1
  93. package/build/server/server/index.d.ts.map +1 -1
  94. package/build/server/server/index.js +1 -1
  95. package/build/server/server/publisher-server/index.d.ts +14 -0
  96. package/build/server/server/publisher-server/index.d.ts.map +1 -1
  97. package/build/server/server/publisher-server/index.js +178 -54
  98. package/build/server/server/publisher-server/response-cache.d.ts +19 -0
  99. package/build/server/server/publisher-server/response-cache.d.ts.map +1 -0
  100. package/build/server/server/publisher-server/response-cache.js +106 -0
  101. package/build/server/server/storage/s3-storage-provider.d.ts +16 -15
  102. package/build/server/server/storage/s3-storage-provider.d.ts.map +1 -1
  103. package/build/server/server/storage/s3-storage-provider.js +131 -60
  104. package/build/server/server/storage/storage-provider.d.ts +2 -2
  105. package/build/server/server/storage/storage-provider.d.ts.map +1 -1
  106. package/build/server/server/storage/storage-provider.js +2 -1
  107. package/build/server/server/util/server-timing.d.ts +7 -0
  108. package/build/server/server/util/server-timing.d.ts.map +1 -0
  109. package/build/server/server/util/server-timing.js +34 -0
  110. package/package.json +9 -8
  111. package/build/cli/cli/util/aws-credentials.d.ts +0 -12
  112. package/build/cli/cli/util/aws-credentials.d.ts.map +0 -1
  113. package/build/cli/cli/util/aws-credentials.js +0 -67
@@ -2,16 +2,19 @@
2
2
  * Copyright Fastly, Inc.
3
3
  * Licensed under the MIT license. See LICENSE file for details.
4
4
  */
5
+ import { CoreCache } from 'fastly:cache';
5
6
  import { decodeAssetVariantMetadata, } from '../../models/assets/index.js';
6
7
  import { decodeIndexMetadata, } from '../../models/server/index.js';
7
8
  import { isExpired } from '../../models/time/index.js';
8
9
  import { loadStorageProviderFromStaticPublishRc, } from '../storage/storage-provider.js';
9
10
  import { checkIfModifiedSince, getIfModifiedSinceHeader } from './serve-preconditions/if-modified-since.js';
10
11
  import { checkIfNoneMatch, getIfNoneMatchHeader } from './serve-preconditions/if-none-match.js';
12
+ import { ServerTiming } from '../util/server-timing.js';
13
+ import { CACHEABLE_STATUSES, buildCacheFillRequest, buildResponseCacheKey, decodeCachedResponseMetadata, encodeCachedResponseMetadata, parseAcceptEncodingGroups, } from './response-cache.js';
11
14
  export function buildHeadersSubset(responseHeaders, keys) {
12
15
  const resultHeaders = new Headers();
13
16
  for (const value of keys) {
14
- if (value in responseHeaders) {
17
+ if (responseHeaders.has(value)) {
15
18
  const responseHeaderValue = responseHeaders.get(value);
16
19
  if (responseHeaderValue != null) {
17
20
  resultHeaders.set(value, responseHeaderValue);
@@ -42,6 +45,9 @@ export class PublisherServer {
42
45
  this.defaultCollectionName = defaultCollectionName;
43
46
  this.activeCollectionName = this.defaultCollectionName;
44
47
  this.collectionNameHeader = 'X-Publisher-Server-Collection';
48
+ this.serverTimingRequestHeader = null;
49
+ this.serverTiming = null;
50
+ this.responseCache = null;
45
51
  }
46
52
  static fromStaticPublishRc(config) {
47
53
  const storeProvider = loadStorageProviderFromStaticPublishRc(config);
@@ -55,21 +61,43 @@ export class PublisherServer {
55
61
  setCollectionNameHeader(collectionHeader) {
56
62
  this.collectionNameHeader = collectionHeader;
57
63
  }
64
+ // Set the request header that turns on the Server-Timing response header.
65
+ // null (the default) turns timing off.
66
+ setServerTimingRequestHeader(requestHeader) {
67
+ this.serverTimingRequestHeader = requestHeader;
68
+ }
69
+ // Cache whole responses with the Core Cache API, keyed by collection, path,
70
+ // and the client's Accept-Encoding. A cache hit does not read the settings,
71
+ // the index, or the file from storage. Entries have the surrogate key
72
+ // `<publishId>-<collectionName>`, which publish-content purges. null (the
73
+ // default) turns the cache off.
74
+ setResponseCache(options) {
75
+ this.responseCache = options;
76
+ }
77
+ // Start handling a new request. serveRequest() calls this. If you call
78
+ // getMatchingAsset() and serveAsset() directly, call this first.
79
+ beginRequest(request) {
80
+ const header = this.serverTimingRequestHeader;
81
+ this.serverTiming = header != null && request.headers.has(header) ? new ServerTiming() : null;
82
+ }
83
+ timed(name, fn) {
84
+ return this.serverTiming != null ? this.serverTiming.measure(name, fn) : fn();
85
+ }
58
86
  // Server config is obtained from storage, and cached for the duration of this object.
59
87
  async getServerConfig() {
60
88
  if (this.settingsCached !== undefined) {
61
89
  return this.settingsCached;
62
90
  }
63
91
  const settingsFileKey = `${this.publishId}_settings_${this.activeCollectionName}`;
64
- const settingsFile = await this.storageProvider.getEntry(settingsFileKey);
65
- if (settingsFile == null) {
66
- console.error(`Settings File not found at ${settingsFileKey}.`);
67
- console.error(`You may need to publish your application.`);
68
- this.settingsCached = null;
69
- }
70
- else {
71
- this.settingsCached = (await settingsFile.json());
72
- }
92
+ this.settingsCached = await this.timed('settings', async () => {
93
+ const settingsFile = await this.storageProvider.getEntry(settingsFileKey, [`${this.publishId}-${this.activeCollectionName}`, 'settings']);
94
+ if (settingsFile == null) {
95
+ console.error(`Settings File not found at ${settingsFileKey}.`);
96
+ console.error(`You may need to publish your application.`);
97
+ return null;
98
+ }
99
+ return (await settingsFile.json());
100
+ });
73
101
  return this.settingsCached;
74
102
  }
75
103
  async getStaticItems() {
@@ -96,7 +124,7 @@ export class PublisherServer {
96
124
  return this.assetEntryMapCache;
97
125
  }
98
126
  const indexFileKey = `${this.publishId}_index_${this.activeCollectionName}`;
99
- const indexFile = await this.storageProvider.getEntry(indexFileKey);
127
+ const indexFile = await this.timed('index', () => this.storageProvider.getEntry(indexFileKey, [`${this.publishId}-${this.activeCollectionName}`, 'index']));
100
128
  if (indexFile == null) {
101
129
  console.error(`Index File not found at ${indexFileKey}.`);
102
130
  console.error(`You may need to publish your application.`);
@@ -124,7 +152,9 @@ export class PublisherServer {
124
152
  this.assetEntryMapCache = null;
125
153
  return null;
126
154
  }
127
- this.assetEntryMapCache = (await indexFile.json());
155
+ // Read and parse in two steps, so that Server-Timing can report each one.
156
+ const indexText = await this.timed('index-body', () => indexFile.text());
157
+ this.assetEntryMapCache = await this.timed('index-parse', async () => JSON.parse(indexText));
128
158
  return this.assetEntryMapCache;
129
159
  }
130
160
  async getMatchingAsset(assetKey, applyAuto = false) {
@@ -185,46 +215,7 @@ export class PublisherServer {
185
215
  if (serverConfig == null || serverConfig.allowedEncodings.length === 0) {
186
216
  return [];
187
217
  }
188
- const acceptEncodingHeader = request.headers.get('accept-encoding')?.trim() ?? '';
189
- if (acceptEncodingHeader == '') {
190
- return [];
191
- }
192
- const priorityMap = new Map;
193
- for (const headerValue of acceptEncodingHeader.trim().split(',')) {
194
- let [encodingValue, qValueStr] = headerValue.trim().split(';');
195
- encodingValue = encodingValue.trim();
196
- if (!serverConfig.allowedEncodings.includes(encodingValue)) {
197
- continue;
198
- }
199
- let qValue; // q value multiplied by 1000
200
- if (qValueStr == null || !qValueStr.startsWith('q=')) {
201
- // use default of 1.0
202
- qValue = 1000;
203
- }
204
- else {
205
- qValueStr = qValueStr.slice(2); // remove the q=
206
- qValue = parseFloat(qValueStr);
207
- if (Number.isNaN(qValue) || qValue > 1) {
208
- qValue = 1;
209
- }
210
- if (qValue < 0) {
211
- qValue = 0;
212
- }
213
- // q values can have up to 3 decimal digits
214
- qValue = Math.floor(qValue * 1000);
215
- }
216
- let typesForQValue = priorityMap.get(qValue);
217
- if (typesForQValue == null) {
218
- typesForQValue = [];
219
- priorityMap.set(qValue, typesForQValue);
220
- }
221
- typesForQValue.push(encodingValue);
222
- }
223
- // Sort keys, larger numbers to come first
224
- const keysSorted = [...priorityMap.keys()]
225
- .sort((qValueA, qValueB) => qValueB - qValueA);
226
- return keysSorted
227
- .map(qValue => priorityMap.get(qValue));
218
+ return parseAcceptEncodingGroups(request.headers.get('accept-encoding') ?? '', serverConfig.allowedEncodings);
228
219
  }
229
220
  async testExtendedCache(pathname) {
230
221
  const staticItems = await this.getStaticItems();
@@ -240,6 +231,11 @@ export class PublisherServer {
240
231
  });
241
232
  }
242
233
  handlePreconditions(request, asset, responseHeaders) {
234
+ return this.handlePreconditionsForLastModified(request, asset.lastModifiedTime, responseHeaders);
235
+ }
236
+ // lastModifiedTime is in seconds since the epoch, as in AssetEntry. A cached
237
+ // response has its headers, but not its AssetEntry.
238
+ handlePreconditionsForLastModified(request, lastModifiedTime, responseHeaders) {
243
239
  // Handle preconditions according to https://httpwg.org/specs/rfc9110.html#rfc.section.13.2.2
244
240
  // A recipient cache or origin server MUST evaluate the request preconditions defined by this specification in the following order:
245
241
  // 1. When recipient is the origin server and If-Match is present, evaluate the If-Match precondition:
@@ -276,7 +272,7 @@ export class PublisherServer {
276
272
  // For us, method is always GET or HEAD here.
277
273
  const headerValue = getIfModifiedSinceHeader(request);
278
274
  if (headerValue != null) {
279
- const result = checkIfModifiedSince(asset.lastModifiedTime, headerValue);
275
+ const result = checkIfModifiedSince(lastModifiedTime, headerValue);
280
276
  if (!result) {
281
277
  return new Response(null, {
282
278
  status: 304,
@@ -296,7 +292,7 @@ export class PublisherServer {
296
292
  const baseHash = entry.key.slice(7);
297
293
  const baseKey = `${this.publishId}_files_sha256_${baseHash}`;
298
294
  const variantKey = variant != null ? `${baseKey}_${variant}` : baseKey;
299
- const storageEntry = await this.storageProvider.getEntry(variantKey);
295
+ const storageEntry = await this.timed('asset', () => this.storageProvider.getEntry(variantKey));
300
296
  if (storageEntry == null) {
301
297
  return null;
302
298
  }
@@ -380,6 +376,9 @@ export class PublisherServer {
380
376
  if (asset.lastModifiedTime !== 0) {
381
377
  headers.set('Last-Modified', (new Date(asset.lastModifiedTime * 1000)).toUTCString());
382
378
  }
379
+ if (this.serverTiming != null) {
380
+ headers.append('Server-Timing', this.serverTiming.toHeaderValue());
381
+ }
383
382
  const preconditionResponse = this.handlePreconditions(request, asset, headers);
384
383
  if (preconditionResponse != null) {
385
384
  return preconditionResponse;
@@ -390,7 +389,127 @@ export class PublisherServer {
390
389
  headers,
391
390
  });
392
391
  }
392
+ // Serve a response through the response cache (see setResponseCache()).
393
+ // keyPath identifies the response in the active collection. Include in it
394
+ // anything other than the path and the Accept-Encoding that changes the response.
395
+ // On a miss, produce() is called with a GET request that has no conditional or
396
+ // range headers, and its result is cached if it is a 200 or 404 response, or
397
+ // null (not found). Conditional requests and HEAD are then answered from the
398
+ // cached response. If the cache is off, produce() gets the original request.
399
+ async serveCached(request, keyPath, produce) {
400
+ if (this.responseCache == null) {
401
+ return produce(request);
402
+ }
403
+ const key = buildResponseCacheKey(this.publishId, this.activeCollectionName, keyPath, request);
404
+ const lookupStart = performance.now();
405
+ const entry = CoreCache.transactionLookup(key);
406
+ const state = entry.state();
407
+ if (!state.mustInsertOrUpdate()) {
408
+ const metadata = state.found() && state.usable() ? decodeCachedResponseMetadata(entry.userMetadata()) : null;
409
+ if (metadata != null) {
410
+ // age() is in milliseconds. A hit younger than the time since a purge proves the entry was refilled.
411
+ this.serverTiming?.add('cache', performance.now() - lookupStart, `hit age=${Math.round(entry.age() / 1000)}s`);
412
+ return this.responseFromCache(request, metadata, entry.body());
413
+ }
414
+ // Not usable, and another request is not filling it for us: serve without the cache.
415
+ this.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
416
+ return produce(request);
417
+ }
418
+ // This request must fill the entry (a miss, or a stale entry after a soft purge).
419
+ this.serverTiming?.add('cache', performance.now() - lookupStart, 'miss');
420
+ let response;
421
+ try {
422
+ response = await produce(buildCacheFillRequest(request));
423
+ }
424
+ catch (err) {
425
+ entry.cancel();
426
+ throw err;
427
+ }
428
+ const insertOptions = {
429
+ // The Core Cache takes maxAge in milliseconds. ResponseCacheOptions.maxAge is in seconds.
430
+ maxAge: this.responseCache.maxAge * 1000,
431
+ surrogateKeys: [`${this.publishId}-${this.activeCollectionName}`],
432
+ };
433
+ if (response == null) {
434
+ const metadata = { notFound: true };
435
+ const writer = entry.insert({
436
+ ...insertOptions,
437
+ userMetadata: encodeCachedResponseMetadata(metadata),
438
+ length: 0,
439
+ });
440
+ writer.close();
441
+ return null;
442
+ }
443
+ if (!CACHEABLE_STATUSES.includes(response.status)) {
444
+ entry.cancel();
445
+ return response;
446
+ }
447
+ const headers = new Headers(response.headers);
448
+ // Server-Timing describes one request, so it is not stored.
449
+ headers.delete('Server-Timing');
450
+ const metadata = { status: response.status, headers: [...headers] };
451
+ const contentLength = Number(headers.get('Content-Length'));
452
+ // Stream the body into the cache entry, and give the client (and any requests
453
+ // waiting on this key) the entry's own stream as it fills. FastlyBody.append()
454
+ // can take only host-backed streams, and the storage providers build their
455
+ // bodies in JavaScript, so copy the chunks.
456
+ const [writer, streamedEntry] = entry.insertAndStreamBack({
457
+ ...insertOptions,
458
+ userMetadata: encodeCachedResponseMetadata(metadata),
459
+ length: Number.isInteger(contentLength) && headers.has('Content-Length') ? contentLength : undefined,
460
+ });
461
+ const copied = this.copyBodyToCache(response, writer);
462
+ const cachedResponse = this.responseFromCache(request, metadata, streamedEntry.body());
463
+ // A response without a body (HEAD, 304) does not keep the request running
464
+ // until the copy finishes. If the copy is cut short, the entry can be stored
465
+ // with a partial body, so wait for it.
466
+ if (cachedResponse?.body == null) {
467
+ await copied;
468
+ }
469
+ return cachedResponse;
470
+ }
471
+ async copyBodyToCache(response, writer) {
472
+ try {
473
+ if (response.body != null) {
474
+ const reader = response.body.getReader();
475
+ for (;;) {
476
+ const { done, value } = await reader.read();
477
+ if (done) {
478
+ break;
479
+ }
480
+ writer.append(value);
481
+ }
482
+ }
483
+ writer.close();
484
+ }
485
+ catch (err) {
486
+ // Without close(), the cache treats the insertion as incomplete, so a
487
+ // partial body is not kept. Readers of this entry get a stream error.
488
+ console.error('Could not write the response to the cache:', err);
489
+ }
490
+ }
491
+ responseFromCache(request, metadata, body) {
492
+ if (metadata.notFound) {
493
+ return null;
494
+ }
495
+ const headers = new Headers(metadata.headers);
496
+ if (this.serverTiming != null) {
497
+ headers.append('Server-Timing', this.serverTiming.toHeaderValue());
498
+ }
499
+ const lastModified = headers.get('Last-Modified');
500
+ const lastModifiedMs = lastModified != null ? Date.parse(lastModified) : NaN;
501
+ const lastModifiedTime = Number.isNaN(lastModifiedMs) ? 0 : Math.floor(lastModifiedMs / 1000);
502
+ const preconditionResponse = this.handlePreconditionsForLastModified(request, lastModifiedTime, headers);
503
+ if (preconditionResponse != null) {
504
+ return preconditionResponse;
505
+ }
506
+ return new Response(request.method === 'HEAD' ? null : body, {
507
+ status: metadata.status,
508
+ headers,
509
+ });
510
+ }
393
511
  async serveRequest(request) {
512
+ this.beginRequest(request);
394
513
  // Only handle GET and HEAD
395
514
  if (request.method !== 'GET' && request.method !== 'HEAD') {
396
515
  return null;
@@ -401,6 +520,11 @@ export class PublisherServer {
401
520
  if (pathname === '/healthz') {
402
521
  return new Response("OK", { status: 200 });
403
522
  }
523
+ // The fallback pages (SPA, not found) depend on whether the client accepts HTML.
524
+ const keyPath = requestAcceptsTextHtml(request) ? pathname : `${pathname}|no-html`;
525
+ return this.serveCached(request, keyPath, (fillRequest) => this.serveRequestFromStorage(fillRequest, pathname));
526
+ }
527
+ async serveRequestFromStorage(request, pathname) {
404
528
  const serverConfig = await this.getServerConfig();
405
529
  if (serverConfig == null) {
406
530
  return new Response(`Settings not found. You may need to publish your application.`, {
@@ -0,0 +1,19 @@
1
+ import { type ContentCompressionTypes } from '../../models/compression/index.js';
2
+ export type ResponseCacheOptions = {
3
+ maxAge: number;
4
+ };
5
+ export type CachedResponseMetadata = {
6
+ notFound: true;
7
+ } | {
8
+ notFound?: false;
9
+ status: number;
10
+ headers: [string, string][];
11
+ };
12
+ export declare const CACHEABLE_STATUSES: Readonly<number[]>;
13
+ export declare function parseAcceptEncodingGroups(headerValue: string, allowedEncodings: Readonly<ContentCompressionTypes[]>): ContentCompressionTypes[][];
14
+ export declare function acceptEncodingCacheKeyPart(request: Request): string;
15
+ export declare function buildResponseCacheKey(publishId: string, collectionName: string, keyPath: string, request: Request): string;
16
+ export declare function buildCacheFillRequest(request: Request): Request;
17
+ export declare function encodeCachedResponseMetadata(metadata: CachedResponseMetadata): string;
18
+ export declare function decodeCachedResponseMetadata(buffer: ArrayBuffer): CachedResponseMetadata | null;
19
+ //# sourceMappingURL=response-cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response-cache.d.ts","sourceRoot":"","sources":["../../../../src/server/publisher-server/response-cache.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,KAAK,uBAAuB,EAE7B,MAAM,mCAAmC,CAAC;AAE3C,MAAM,MAAM,oBAAoB,GAAG;IAIjC,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAIF,MAAM,MAAM,sBAAsB,GAC9B;IAAE,QAAQ,EAAE,IAAI,CAAA;CAAE,GAClB;IAAE,QAAQ,CAAC,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAA;CAAE,CAAC;AAItE,eAAO,MAAM,kBAAkB,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAgB,CAAC;AAgBnE,wBAAgB,yBAAyB,CACvC,WAAW,EAAE,MAAM,EACnB,gBAAgB,EAAE,QAAQ,CAAC,uBAAuB,EAAE,CAAC,GACpD,uBAAuB,EAAE,EAAE,CA2C7B;AAOD,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAQnE;AAED,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,MAAM,EACjB,cAAc,EAAE,MAAM,EACtB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,OAAO,UAGjB;AAID,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAM/D;AAED,wBAAgB,4BAA4B,CAAC,QAAQ,EAAE,sBAAsB,GAAG,MAAM,CAErF;AAED,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,WAAW,GAAG,sBAAsB,GAAG,IAAI,CAa/F"}
@@ -0,0 +1,106 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
5
+ import { compressionTypes, } from '../../models/compression/index.js';
6
+ // Statuses that serveAsset() produces for a found file or a not-found page.
7
+ // Anything else (for example, a 500 when the settings are missing) is not cached.
8
+ export const CACHEABLE_STATUSES = [200, 404];
9
+ // Request headers that make a response depend on the client's cached copy.
10
+ // The response that is stored is always the full one.
11
+ const CONDITIONAL_REQUEST_HEADERS = [
12
+ 'If-Match',
13
+ 'If-None-Match',
14
+ 'If-Modified-Since',
15
+ 'If-Unmodified-Since',
16
+ 'If-Range',
17
+ 'Range',
18
+ ];
19
+ // Parses an Accept-Encoding header value into groups of the allowed encodings
20
+ // that have the same q value, highest first. For example, with both br and
21
+ // gzip allowed, 'br;q=1, gzip;q=0.5' gives [['br'], ['gzip']].
22
+ export function parseAcceptEncodingGroups(headerValue, allowedEncodings) {
23
+ const trimmed = headerValue.trim();
24
+ if (trimmed === '' || allowedEncodings.length === 0) {
25
+ return [];
26
+ }
27
+ const priorityMap = new Map;
28
+ for (const item of trimmed.split(',')) {
29
+ let [encodingValue, qValueStr] = item.trim().split(';');
30
+ encodingValue = encodingValue.trim();
31
+ if (!allowedEncodings.includes(encodingValue)) {
32
+ continue;
33
+ }
34
+ let qValue; // q value multiplied by 1000
35
+ if (qValueStr == null || !qValueStr.startsWith('q=')) {
36
+ // use default of 1.0
37
+ qValue = 1000;
38
+ }
39
+ else {
40
+ qValueStr = qValueStr.slice(2); // remove the q=
41
+ qValue = parseFloat(qValueStr);
42
+ if (Number.isNaN(qValue) || qValue > 1) {
43
+ qValue = 1;
44
+ }
45
+ if (qValue < 0) {
46
+ qValue = 0;
47
+ }
48
+ // q values can have up to 3 decimal digits
49
+ qValue = Math.floor(qValue * 1000);
50
+ }
51
+ let typesForQValue = priorityMap.get(qValue);
52
+ if (typesForQValue == null) {
53
+ typesForQValue = [];
54
+ priorityMap.set(qValue, typesForQValue);
55
+ }
56
+ typesForQValue.push(encodingValue);
57
+ }
58
+ // Sort keys, larger numbers to come first
59
+ return [...priorityMap.keys()]
60
+ .sort((qValueA, qValueB) => qValueB - qValueA)
61
+ .map(qValue => priorityMap.get(qValue));
62
+ }
63
+ // Normalizes the request's Accept-Encoding into a short string for the cache
64
+ // key, using every encoding that the publisher can produce. The collection's
65
+ // allowedEncodings is left out on purpose: it would need the settings, and it
66
+ // only changes when the collection is published again, which purges the cache.
67
+ // For example, 'gzip, deflate, br' gives 'br+gzip'.
68
+ export function acceptEncodingCacheKeyPart(request) {
69
+ const groups = parseAcceptEncodingGroups(request.headers.get('Accept-Encoding') ?? '', compressionTypes);
70
+ if (groups.length === 0) {
71
+ return 'identity';
72
+ }
73
+ return groups
74
+ .map(group => [...group].sort().join('+'))
75
+ .join('>');
76
+ }
77
+ export function buildResponseCacheKey(publishId, collectionName, keyPath, request) {
78
+ return `${publishId}_response_${collectionName}_${acceptEncodingCacheKeyPart(request)}_${keyPath}`;
79
+ }
80
+ // The request used to produce a response for the cache: always a GET, without
81
+ // conditional or range headers, so that the stored response is the full one.
82
+ export function buildCacheFillRequest(request) {
83
+ const headers = new Headers(request.headers);
84
+ for (const name of CONDITIONAL_REQUEST_HEADERS) {
85
+ headers.delete(name);
86
+ }
87
+ return new Request(request.url, { method: 'GET', headers });
88
+ }
89
+ export function encodeCachedResponseMetadata(metadata) {
90
+ return JSON.stringify(metadata);
91
+ }
92
+ export function decodeCachedResponseMetadata(buffer) {
93
+ try {
94
+ const value = JSON.parse(new TextDecoder().decode(buffer));
95
+ if (value?.notFound === true) {
96
+ return { notFound: true };
97
+ }
98
+ if (typeof value?.status === 'number' && Array.isArray(value.headers)) {
99
+ return { status: value.status, headers: value.headers };
100
+ }
101
+ }
102
+ catch {
103
+ // Not valid JSON: treat the entry as a miss.
104
+ }
105
+ return null;
106
+ }
@@ -1,26 +1,27 @@
1
- import { S3Client } from '@aws-sdk/client-s3';
2
1
  import { type StorageEntry, type StorageProvider, StorageProviderBuilder } from './storage-provider.js';
3
- export type AwsCredentials = {
2
+ export type S3Credentials = {
4
3
  accessKeyId: string;
5
4
  secretAccessKey: string;
6
5
  };
7
- export type AwsCredentialsBuilder = () => (AwsCredentials | Promise<AwsCredentials>);
6
+ export type S3CredentialsBuilder = () => (S3Credentials | Promise<S3Credentials>);
8
7
  export declare const buildStoreProvider: StorageProviderBuilder;
9
- export declare function setSecretStoreForAwsCredentials(secretStoreName: string): void;
10
- export declare function setSecretStoreKeyForAwsAccessKeyId(secretStoreKey: string): void;
11
- export declare function setSecretStoreKeyForAwsSecretAccessKey(secretStoreKey: string): void;
12
- export declare function buildAwsCredentialsFromSecretStore(): Promise<{
13
- accessKeyId: string;
14
- secretAccessKey: string;
15
- }>;
16
- export declare function setAwsCredentialsBuilder(awsCredentialsBuilder: AwsCredentialsBuilder): void;
8
+ export declare function setSecretStoreForS3Credentials(secretStoreName: string): void;
9
+ export declare function setSecretStoreKeyForS3AccessKeyId(secretStoreKey: string): void;
10
+ export declare function setSecretStoreKeyForS3SecretAccessKey(secretStoreKey: string): void;
11
+ export declare function buildS3CredentialsFromSecretStore(): Promise<S3Credentials>;
12
+ export declare function setS3CredentialsBuilder(s3CredentialsBuilder: S3CredentialsBuilder): void;
13
+ export type S3StorageProviderParams = {
14
+ s3Endpoint?: string;
15
+ s3FastlyBackendName?: string;
16
+ };
17
17
  export declare class S3StorageProvider implements StorageProvider {
18
- constructor(s3Region: string, s3Bucket: string, s3Endpoint?: string);
18
+ constructor(s3Region: string, s3Bucket: string, params?: S3StorageProviderParams);
19
19
  private readonly s3Region;
20
20
  private readonly s3Bucket;
21
21
  private readonly s3Endpoint?;
22
- private s3Client?;
23
- getS3Client(): Promise<S3Client>;
24
- getEntry(key: string): Promise<StorageEntry | null>;
22
+ private readonly s3FastlyBackendName?;
23
+ objectUrl(key: string): URL;
24
+ fetchObject(key: string, requestInit: RequestInit): Promise<Response>;
25
+ getEntry(key: string, tags?: string[]): Promise<StorageEntry | null>;
25
26
  }
26
27
  //# sourceMappingURL=s3-storage-provider.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"s3-storage-provider.d.ts","sourceRoot":"","sources":["../../../../src/server/storage/s3-storage-provider.ts"],"names":[],"mappings":"AAOA,OAAO,EAIL,QAAQ,EAET,MAAM,oBAAoB,CAAC;AAS5B,OAAO,EAEL,KAAK,YAAY,EAEjB,KAAK,eAAe,EACpB,sBAAsB,EACvB,MAAM,uBAAuB,CAAC;AAE/B,MAAM,MAAM,cAAc,GAAG;IAC3B,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG,MAAM,CAAC,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC;AAErF,eAAO,MAAM,kBAAkB,EAAE,sBAUhC,CAAC;AAMF,wBAAgB,+BAA+B,CAAC,eAAe,EAAE,MAAM,QAEtE;AAED,wBAAgB,kCAAkC,CAAC,cAAc,EAAE,MAAM,QAExE;AAED,wBAAgB,sCAAsC,CAAC,cAAc,EAAE,MAAM,QAE5E;AAED,wBAAsB,kCAAkC;;;GAuBvD;AAGD,wBAAgB,wBAAwB,CAAC,qBAAqB,EAAE,qBAAqB,QAEpF;AAED,qBAAa,iBAAkB,YAAW,eAAe;gBAErD,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,EAChB,UAAU,CAAC,EAAE,MAAM;IAOrB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAS;IAErC,OAAO,CAAC,QAAQ,CAAC,CAAW;IACtB,WAAW;IAqBX,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;CA4B1D"}
1
+ {"version":3,"file":"s3-storage-provider.d.ts","sourceRoot":"","sources":["../../../../src/server/storage/s3-storage-provider.ts"],"names":[],"mappings":"AAiBA,OAAO,EAEL,KAAK,YAAY,EAEjB,KAAK,eAAe,EACpB,sBAAsB,EACvB,MAAM,uBAAuB,CAAC;AAE/B,MAAM,MAAM,aAAa,GAAG;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG,MAAM,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC;AAElF,eAAO,MAAM,kBAAkB,EAAE,sBAahC,CAAC;AAMF,wBAAgB,8BAA8B,CAAC,eAAe,EAAE,MAAM,QAErE;AAED,wBAAgB,iCAAiC,CAAC,cAAc,EAAE,MAAM,QAEvE;AAED,wBAAgB,qCAAqC,CAAC,cAAc,EAAE,MAAM,QAE3E;AAGD,wBAAsB,iCAAiC,2BA2BtD;AAGD,wBAAgB,uBAAuB,CAAC,oBAAoB,EAAE,oBAAoB,QAEjF;AAED,MAAM,MAAM,uBAAuB,GAAG;IACpC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B,CAAC;AAuBF,qBAAa,iBAAkB,YAAW,eAAe;gBAErD,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,uBAAuB;IAQlC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAC,CAAS;IAI9C,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG;IAYrB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC;IAqDrE,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;CAkC3E"}