@fastly/compute-js-static-publish 8.0.0-beta.9 → 8.0.0-rc.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.
- package/build/cli/cli/commands/manage/clean.d.ts.map +1 -1
- package/build/cli/cli/commands/manage/clean.js +2 -3
- package/build/cli/cli/commands/manage/collections/delete.d.ts.map +1 -1
- package/build/cli/cli/commands/manage/collections/delete.js +2 -3
- package/build/cli/cli/commands/manage/collections/index.d.ts.map +1 -1
- package/build/cli/cli/commands/manage/collections/index.js +2 -3
- package/build/cli/cli/commands/manage/collections/list.d.ts.map +1 -1
- package/build/cli/cli/commands/manage/collections/list.js +2 -3
- package/build/cli/cli/commands/manage/collections/promote.d.ts.map +1 -1
- package/build/cli/cli/commands/manage/collections/promote.js +2 -3
- package/build/cli/cli/commands/manage/collections/update-expiration.d.ts.map +1 -1
- package/build/cli/cli/commands/manage/collections/update-expiration.js +2 -3
- package/build/cli/cli/commands/manage/index.d.ts.map +1 -1
- package/build/cli/cli/commands/manage/index.js +2 -3
- package/build/cli/cli/commands/manage/publish-content.d.ts.map +1 -1
- package/build/cli/cli/commands/manage/publish-content.js +86 -8
- package/build/cli/cli/commands/scaffold/index.d.ts.map +1 -1
- package/build/cli/cli/commands/scaffold/index.js +3 -2
- package/build/cli/cli/compression/brotli.d.ts +2 -1
- package/build/cli/cli/compression/brotli.d.ts.map +1 -1
- package/build/cli/cli/compression/brotli.js +15 -4
- package/build/cli/cli/compression/gzip.d.ts +2 -1
- package/build/cli/cli/compression/gzip.d.ts.map +1 -1
- package/build/cli/cli/compression/gzip.js +8 -4
- package/build/cli/cli/compression/index.d.ts +4 -1
- package/build/cli/cli/compression/index.d.ts.map +1 -1
- package/build/cli/cli/index.js +8 -0
- package/build/cli/cli/storage/kv-store-local-provider.d.ts +0 -1
- package/build/cli/cli/storage/kv-store-local-provider.d.ts.map +1 -1
- package/build/cli/cli/storage/kv-store-local-provider.js +0 -2
- package/build/cli/cli/storage/kv-store-provider.d.ts +0 -1
- package/build/cli/cli/storage/kv-store-provider.d.ts.map +1 -1
- package/build/cli/cli/storage/kv-store-provider.js +0 -2
- package/build/cli/cli/storage/s3-storage-provider.d.ts +3 -4
- package/build/cli/cli/storage/s3-storage-provider.d.ts.map +1 -1
- package/build/cli/cli/storage/s3-storage-provider.js +20 -45
- package/build/cli/cli/storage/storage-provider.d.ts +2 -1
- package/build/cli/cli/storage/storage-provider.d.ts.map +1 -1
- package/build/cli/cli/storage/storage-provider.js +13 -0
- package/build/cli/cli/util/api-token.d.ts.map +1 -1
- package/build/cli/cli/util/api-token.js +0 -28
- package/build/cli/cli/util/config.d.ts.map +1 -1
- package/build/cli/cli/util/config.js +8 -1
- package/build/cli/cli/util/content-types.js +1 -1
- package/build/cli/cli/util/purge.d.ts +17 -1
- package/build/cli/cli/util/purge.d.ts.map +1 -1
- package/build/cli/cli/util/purge.js +63 -3
- package/build/cli/cli/util/service-id.d.ts +10 -0
- package/build/cli/cli/util/service-id.d.ts.map +1 -0
- package/build/cli/cli/util/service-id.js +27 -0
- package/build/cli/cli/util/variants.d.ts +2 -1
- package/build/cli/cli/util/variants.d.ts.map +1 -1
- package/build/cli/cli/util/variants.js +2 -2
- package/build/cli/models/config/publish-content-config.d.ts +2 -0
- package/build/cli/models/config/publish-content-config.d.ts.map +1 -1
- package/build/server/models/config/publish-content-config.d.ts +2 -0
- package/build/server/models/config/publish-content-config.d.ts.map +1 -1
- package/build/server/server/publisher-server/index.d.ts +15 -1
- package/build/server/server/publisher-server/index.d.ts.map +1 -1
- package/build/server/server/publisher-server/index.js +189 -56
- package/build/server/server/publisher-server/response-cache.d.ts +19 -0
- package/build/server/server/publisher-server/response-cache.d.ts.map +1 -0
- package/build/server/server/publisher-server/response-cache.js +106 -0
- package/build/server/server/storage/s3-storage-provider.d.ts +2 -5
- package/build/server/server/storage/s3-storage-provider.d.ts.map +1 -1
- package/build/server/server/storage/s3-storage-provider.js +95 -38
- package/build/server/server/storage/storage-provider.d.ts +1 -1
- package/build/server/server/storage/storage-provider.d.ts.map +1 -1
- package/build/server/server/storage/storage-provider.js +2 -1
- package/build/server/server/util/server-timing.d.ts +7 -0
- package/build/server/server/util/server-timing.d.ts.map +1 -0
- package/build/server/server/util/server-timing.js +34 -0
- package/package.json +9 -7
|
@@ -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
|
|
17
|
+
if (responseHeaders.has(value)) {
|
|
15
18
|
const responseHeaderValue = responseHeaders.get(value);
|
|
16
19
|
if (responseHeaderValue != null) {
|
|
17
20
|
resultHeaders.set(value, responseHeaderValue);
|
|
@@ -42,34 +45,68 @@ 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);
|
|
48
54
|
return new PublisherServer(config.publishId, storeProvider, config.defaultCollectionName);
|
|
49
55
|
}
|
|
56
|
+
// null selects the default collection. A sandbox can be reused for more than
|
|
57
|
+
// one request, so call this for each request, also when no collection is
|
|
58
|
+
// selected. Otherwise, the collection of the previous request stays active.
|
|
50
59
|
setActiveCollectionName(collectionName) {
|
|
51
|
-
this.activeCollectionName = collectionName;
|
|
60
|
+
this.activeCollectionName = collectionName ?? this.defaultCollectionName;
|
|
52
61
|
this.settingsCached = undefined;
|
|
53
62
|
this.assetEntryMapCache = undefined;
|
|
54
63
|
}
|
|
55
64
|
setCollectionNameHeader(collectionHeader) {
|
|
56
65
|
this.collectionNameHeader = collectionHeader;
|
|
57
66
|
}
|
|
58
|
-
//
|
|
67
|
+
// Set the request header that turns on the Server-Timing response header.
|
|
68
|
+
// null (the default) turns timing off.
|
|
69
|
+
setServerTimingRequestHeader(requestHeader) {
|
|
70
|
+
this.serverTimingRequestHeader = requestHeader;
|
|
71
|
+
}
|
|
72
|
+
// Cache whole responses with the Core Cache API, keyed by collection, path,
|
|
73
|
+
// and the client's Accept-Encoding. A cache hit does not read the settings,
|
|
74
|
+
// the index, or the file from storage. Entries have the surrogate key
|
|
75
|
+
// `<publishId>-<collectionName>`, which publish-content purges. null (the
|
|
76
|
+
// default) turns the cache off.
|
|
77
|
+
setResponseCache(options) {
|
|
78
|
+
this.responseCache = options;
|
|
79
|
+
}
|
|
80
|
+
// Start handling a new request. serveRequest() calls this. If you call
|
|
81
|
+
// getMatchingAsset() and serveAsset() directly, call this first.
|
|
82
|
+
// A sandbox can be reused for more than one request, so this also clears the
|
|
83
|
+
// settings and the index that a previous request read. Without this, a reused
|
|
84
|
+
// sandbox serves an old index after a publish, and serves an expired collection.
|
|
85
|
+
beginRequest(request) {
|
|
86
|
+
this.settingsCached = undefined;
|
|
87
|
+
this.assetEntryMapCache = undefined;
|
|
88
|
+
const header = this.serverTimingRequestHeader;
|
|
89
|
+
this.serverTiming = header != null && request.headers.has(header) ? new ServerTiming() : null;
|
|
90
|
+
}
|
|
91
|
+
timed(name, fn) {
|
|
92
|
+
return this.serverTiming != null ? this.serverTiming.measure(name, fn) : fn();
|
|
93
|
+
}
|
|
94
|
+
// Server config is obtained from storage, and cached until the next beginRequest()
|
|
95
|
+
// or setActiveCollectionName().
|
|
59
96
|
async getServerConfig() {
|
|
60
97
|
if (this.settingsCached !== undefined) {
|
|
61
98
|
return this.settingsCached;
|
|
62
99
|
}
|
|
63
100
|
const settingsFileKey = `${this.publishId}_settings_${this.activeCollectionName}`;
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
}
|
|
101
|
+
this.settingsCached = await this.timed('settings', async () => {
|
|
102
|
+
const settingsFile = await this.storageProvider.getEntry(settingsFileKey, [`${this.publishId}-${this.activeCollectionName}`, 'settings']);
|
|
103
|
+
if (settingsFile == null) {
|
|
104
|
+
console.error(`Settings File not found at ${settingsFileKey}.`);
|
|
105
|
+
console.error(`You may need to publish your application.`);
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
return (await settingsFile.json());
|
|
109
|
+
});
|
|
73
110
|
return this.settingsCached;
|
|
74
111
|
}
|
|
75
112
|
async getStaticItems() {
|
|
@@ -96,7 +133,7 @@ export class PublisherServer {
|
|
|
96
133
|
return this.assetEntryMapCache;
|
|
97
134
|
}
|
|
98
135
|
const indexFileKey = `${this.publishId}_index_${this.activeCollectionName}`;
|
|
99
|
-
const indexFile = await this.storageProvider.getEntry(indexFileKey, [`${this.publishId}-${this.activeCollectionName}`, 'index']);
|
|
136
|
+
const indexFile = await this.timed('index', () => this.storageProvider.getEntry(indexFileKey, [`${this.publishId}-${this.activeCollectionName}`, 'index']));
|
|
100
137
|
if (indexFile == null) {
|
|
101
138
|
console.error(`Index File not found at ${indexFileKey}.`);
|
|
102
139
|
console.error(`You may need to publish your application.`);
|
|
@@ -124,7 +161,9 @@ export class PublisherServer {
|
|
|
124
161
|
this.assetEntryMapCache = null;
|
|
125
162
|
return null;
|
|
126
163
|
}
|
|
127
|
-
|
|
164
|
+
// Read and parse in two steps, so that Server-Timing can report each one.
|
|
165
|
+
const indexText = await this.timed('index-body', () => indexFile.text());
|
|
166
|
+
this.assetEntryMapCache = await this.timed('index-parse', async () => JSON.parse(indexText));
|
|
128
167
|
return this.assetEntryMapCache;
|
|
129
168
|
}
|
|
130
169
|
async getMatchingAsset(assetKey, applyAuto = false) {
|
|
@@ -185,46 +224,7 @@ export class PublisherServer {
|
|
|
185
224
|
if (serverConfig == null || serverConfig.allowedEncodings.length === 0) {
|
|
186
225
|
return [];
|
|
187
226
|
}
|
|
188
|
-
|
|
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));
|
|
227
|
+
return parseAcceptEncodingGroups(request.headers.get('accept-encoding') ?? '', serverConfig.allowedEncodings);
|
|
228
228
|
}
|
|
229
229
|
async testExtendedCache(pathname) {
|
|
230
230
|
const staticItems = await this.getStaticItems();
|
|
@@ -240,6 +240,11 @@ export class PublisherServer {
|
|
|
240
240
|
});
|
|
241
241
|
}
|
|
242
242
|
handlePreconditions(request, asset, responseHeaders) {
|
|
243
|
+
return this.handlePreconditionsForLastModified(request, asset.lastModifiedTime, responseHeaders);
|
|
244
|
+
}
|
|
245
|
+
// lastModifiedTime is in seconds since the epoch, as in AssetEntry. A cached
|
|
246
|
+
// response has its headers, but not its AssetEntry.
|
|
247
|
+
handlePreconditionsForLastModified(request, lastModifiedTime, responseHeaders) {
|
|
243
248
|
// Handle preconditions according to https://httpwg.org/specs/rfc9110.html#rfc.section.13.2.2
|
|
244
249
|
// A recipient cache or origin server MUST evaluate the request preconditions defined by this specification in the following order:
|
|
245
250
|
// 1. When recipient is the origin server and If-Match is present, evaluate the If-Match precondition:
|
|
@@ -276,7 +281,7 @@ export class PublisherServer {
|
|
|
276
281
|
// For us, method is always GET or HEAD here.
|
|
277
282
|
const headerValue = getIfModifiedSinceHeader(request);
|
|
278
283
|
if (headerValue != null) {
|
|
279
|
-
const result = checkIfModifiedSince(
|
|
284
|
+
const result = checkIfModifiedSince(lastModifiedTime, headerValue);
|
|
280
285
|
if (!result) {
|
|
281
286
|
return new Response(null, {
|
|
282
287
|
status: 304,
|
|
@@ -296,7 +301,7 @@ export class PublisherServer {
|
|
|
296
301
|
const baseHash = entry.key.slice(7);
|
|
297
302
|
const baseKey = `${this.publishId}_files_sha256_${baseHash}`;
|
|
298
303
|
const variantKey = variant != null ? `${baseKey}_${variant}` : baseKey;
|
|
299
|
-
const storageEntry = await this.storageProvider.getEntry(variantKey);
|
|
304
|
+
const storageEntry = await this.timed('asset', () => this.storageProvider.getEntry(variantKey));
|
|
300
305
|
if (storageEntry == null) {
|
|
301
306
|
return null;
|
|
302
307
|
}
|
|
@@ -380,6 +385,9 @@ export class PublisherServer {
|
|
|
380
385
|
if (asset.lastModifiedTime !== 0) {
|
|
381
386
|
headers.set('Last-Modified', (new Date(asset.lastModifiedTime * 1000)).toUTCString());
|
|
382
387
|
}
|
|
388
|
+
if (this.serverTiming != null) {
|
|
389
|
+
headers.append('Server-Timing', this.serverTiming.toHeaderValue());
|
|
390
|
+
}
|
|
383
391
|
const preconditionResponse = this.handlePreconditions(request, asset, headers);
|
|
384
392
|
if (preconditionResponse != null) {
|
|
385
393
|
return preconditionResponse;
|
|
@@ -390,7 +398,127 @@ export class PublisherServer {
|
|
|
390
398
|
headers,
|
|
391
399
|
});
|
|
392
400
|
}
|
|
401
|
+
// Serve a response through the response cache (see setResponseCache()).
|
|
402
|
+
// keyPath identifies the response in the active collection. Include in it
|
|
403
|
+
// anything other than the path and the Accept-Encoding that changes the response.
|
|
404
|
+
// On a miss, produce() is called with a GET request that has no conditional or
|
|
405
|
+
// range headers, and its result is cached if it is a 200 or 404 response, or
|
|
406
|
+
// null (not found). Conditional requests and HEAD are then answered from the
|
|
407
|
+
// cached response. If the cache is off, produce() gets the original request.
|
|
408
|
+
async serveCached(request, keyPath, produce) {
|
|
409
|
+
if (this.responseCache == null) {
|
|
410
|
+
return produce(request);
|
|
411
|
+
}
|
|
412
|
+
const key = buildResponseCacheKey(this.publishId, this.activeCollectionName, keyPath, request);
|
|
413
|
+
const lookupStart = performance.now();
|
|
414
|
+
const entry = CoreCache.transactionLookup(key);
|
|
415
|
+
const state = entry.state();
|
|
416
|
+
if (!state.mustInsertOrUpdate()) {
|
|
417
|
+
const metadata = state.found() && state.usable() ? decodeCachedResponseMetadata(entry.userMetadata()) : null;
|
|
418
|
+
if (metadata != null) {
|
|
419
|
+
// age() is in milliseconds. A hit younger than the time since a purge proves the entry was refilled.
|
|
420
|
+
this.serverTiming?.add('cache', performance.now() - lookupStart, `hit age=${Math.round(entry.age() / 1000)}s`);
|
|
421
|
+
return this.responseFromCache(request, metadata, entry.body());
|
|
422
|
+
}
|
|
423
|
+
// Not usable, and another request is not filling it for us: serve without the cache.
|
|
424
|
+
this.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
|
|
425
|
+
return produce(request);
|
|
426
|
+
}
|
|
427
|
+
// This request must fill the entry (a miss, or a stale entry after a soft purge).
|
|
428
|
+
this.serverTiming?.add('cache', performance.now() - lookupStart, 'miss');
|
|
429
|
+
let response;
|
|
430
|
+
try {
|
|
431
|
+
response = await produce(buildCacheFillRequest(request));
|
|
432
|
+
}
|
|
433
|
+
catch (err) {
|
|
434
|
+
entry.cancel();
|
|
435
|
+
throw err;
|
|
436
|
+
}
|
|
437
|
+
const insertOptions = {
|
|
438
|
+
// The Core Cache takes maxAge in milliseconds. ResponseCacheOptions.maxAge is in seconds.
|
|
439
|
+
maxAge: this.responseCache.maxAge * 1000,
|
|
440
|
+
surrogateKeys: [`${this.publishId}-${this.activeCollectionName}`],
|
|
441
|
+
};
|
|
442
|
+
if (response == null) {
|
|
443
|
+
const metadata = { notFound: true };
|
|
444
|
+
const writer = entry.insert({
|
|
445
|
+
...insertOptions,
|
|
446
|
+
userMetadata: encodeCachedResponseMetadata(metadata),
|
|
447
|
+
length: 0,
|
|
448
|
+
});
|
|
449
|
+
writer.close();
|
|
450
|
+
return null;
|
|
451
|
+
}
|
|
452
|
+
if (!CACHEABLE_STATUSES.includes(response.status)) {
|
|
453
|
+
entry.cancel();
|
|
454
|
+
return response;
|
|
455
|
+
}
|
|
456
|
+
const headers = new Headers(response.headers);
|
|
457
|
+
// Server-Timing describes one request, so it is not stored.
|
|
458
|
+
headers.delete('Server-Timing');
|
|
459
|
+
const metadata = { status: response.status, headers: [...headers] };
|
|
460
|
+
const contentLength = Number(headers.get('Content-Length'));
|
|
461
|
+
// Stream the body into the cache entry, and give the client (and any requests
|
|
462
|
+
// waiting on this key) the entry's own stream as it fills. FastlyBody.append()
|
|
463
|
+
// can take only host-backed streams, and the storage providers build their
|
|
464
|
+
// bodies in JavaScript, so copy the chunks.
|
|
465
|
+
const [writer, streamedEntry] = entry.insertAndStreamBack({
|
|
466
|
+
...insertOptions,
|
|
467
|
+
userMetadata: encodeCachedResponseMetadata(metadata),
|
|
468
|
+
length: Number.isInteger(contentLength) && headers.has('Content-Length') ? contentLength : undefined,
|
|
469
|
+
});
|
|
470
|
+
const copied = this.copyBodyToCache(response, writer);
|
|
471
|
+
const cachedResponse = this.responseFromCache(request, metadata, streamedEntry.body());
|
|
472
|
+
// A response without a body (HEAD, 304) does not keep the request running
|
|
473
|
+
// until the copy finishes. If the copy is cut short, the entry can be stored
|
|
474
|
+
// with a partial body, so wait for it.
|
|
475
|
+
if (cachedResponse?.body == null) {
|
|
476
|
+
await copied;
|
|
477
|
+
}
|
|
478
|
+
return cachedResponse;
|
|
479
|
+
}
|
|
480
|
+
async copyBodyToCache(response, writer) {
|
|
481
|
+
try {
|
|
482
|
+
if (response.body != null) {
|
|
483
|
+
const reader = response.body.getReader();
|
|
484
|
+
for (;;) {
|
|
485
|
+
const { done, value } = await reader.read();
|
|
486
|
+
if (done) {
|
|
487
|
+
break;
|
|
488
|
+
}
|
|
489
|
+
writer.append(value);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
writer.close();
|
|
493
|
+
}
|
|
494
|
+
catch (err) {
|
|
495
|
+
// Without close(), the cache treats the insertion as incomplete, so a
|
|
496
|
+
// partial body is not kept. Readers of this entry get a stream error.
|
|
497
|
+
console.error('Could not write the response to the cache:', err);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
responseFromCache(request, metadata, body) {
|
|
501
|
+
if (metadata.notFound) {
|
|
502
|
+
return null;
|
|
503
|
+
}
|
|
504
|
+
const headers = new Headers(metadata.headers);
|
|
505
|
+
if (this.serverTiming != null) {
|
|
506
|
+
headers.append('Server-Timing', this.serverTiming.toHeaderValue());
|
|
507
|
+
}
|
|
508
|
+
const lastModified = headers.get('Last-Modified');
|
|
509
|
+
const lastModifiedMs = lastModified != null ? Date.parse(lastModified) : NaN;
|
|
510
|
+
const lastModifiedTime = Number.isNaN(lastModifiedMs) ? 0 : Math.floor(lastModifiedMs / 1000);
|
|
511
|
+
const preconditionResponse = this.handlePreconditionsForLastModified(request, lastModifiedTime, headers);
|
|
512
|
+
if (preconditionResponse != null) {
|
|
513
|
+
return preconditionResponse;
|
|
514
|
+
}
|
|
515
|
+
return new Response(request.method === 'HEAD' ? null : body, {
|
|
516
|
+
status: metadata.status,
|
|
517
|
+
headers,
|
|
518
|
+
});
|
|
519
|
+
}
|
|
393
520
|
async serveRequest(request) {
|
|
521
|
+
this.beginRequest(request);
|
|
394
522
|
// Only handle GET and HEAD
|
|
395
523
|
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
396
524
|
return null;
|
|
@@ -401,6 +529,11 @@ export class PublisherServer {
|
|
|
401
529
|
if (pathname === '/healthz') {
|
|
402
530
|
return new Response("OK", { status: 200 });
|
|
403
531
|
}
|
|
532
|
+
// The fallback pages (SPA, not found) depend on whether the client accepts HTML.
|
|
533
|
+
const keyPath = requestAcceptsTextHtml(request) ? pathname : `${pathname}|no-html`;
|
|
534
|
+
return this.serveCached(request, keyPath, (fillRequest) => this.serveRequestFromStorage(fillRequest, pathname));
|
|
535
|
+
}
|
|
536
|
+
async serveRequestFromStorage(request, pathname) {
|
|
404
537
|
const serverConfig = await this.getServerConfig();
|
|
405
538
|
if (serverConfig == null) {
|
|
406
539
|
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,5 +1,3 @@
|
|
|
1
|
-
import { Command } from '@smithy/types';
|
|
2
|
-
import { S3ClientResolvedConfig, ServiceInputTypes, ServiceOutputTypes } from '@aws-sdk/client-s3';
|
|
3
1
|
import { type StorageEntry, type StorageProvider, StorageProviderBuilder } from './storage-provider.js';
|
|
4
2
|
export type S3Credentials = {
|
|
5
3
|
accessKeyId: string;
|
|
@@ -16,15 +14,14 @@ export type S3StorageProviderParams = {
|
|
|
16
14
|
s3Endpoint?: string;
|
|
17
15
|
s3FastlyBackendName?: string;
|
|
18
16
|
};
|
|
19
|
-
type S3ClientCommand<InputType extends ServiceInputTypes, OutputType extends ServiceOutputTypes> = Command<ServiceInputTypes, InputType, ServiceOutputTypes, OutputType, S3ClientResolvedConfig>;
|
|
20
17
|
export declare class S3StorageProvider implements StorageProvider {
|
|
21
18
|
constructor(s3Region: string, s3Bucket: string, params?: S3StorageProviderParams);
|
|
22
19
|
private readonly s3Region;
|
|
23
20
|
private readonly s3Bucket;
|
|
24
21
|
private readonly s3Endpoint?;
|
|
25
22
|
private readonly s3FastlyBackendName?;
|
|
26
|
-
|
|
23
|
+
objectUrl(key: string): URL;
|
|
24
|
+
fetchObject(key: string, requestInit: RequestInit): Promise<Response>;
|
|
27
25
|
getEntry(key: string, tags?: string[]): Promise<StorageEntry | null>;
|
|
28
26
|
}
|
|
29
|
-
export {};
|
|
30
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":"
|
|
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"}
|