@fastly/compute-js-static-publish 8.0.0-beta.15 → 8.0.0-beta.16
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/server/server/publisher-server/index.d.ts +7 -0
- package/build/server/server/publisher-server/index.d.ts.map +1 -1
- package/build/server/server/publisher-server/index.js +106 -41
- 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/package.json +1 -1
|
@@ -4,6 +4,7 @@ import { type ContentCompressionTypes } from '../../models/compression/index.js'
|
|
|
4
4
|
import { type AssetEntry, type AssetEntryMap, type AssetVariantMetadata } from '../../models/assets/index.js';
|
|
5
5
|
import { type StorageEntry, type StorageProvider } from '../storage/storage-provider.js';
|
|
6
6
|
import { ServerTiming } from '../util/server-timing.js';
|
|
7
|
+
import { type ResponseCacheOptions } from './response-cache.js';
|
|
7
8
|
type AssetVariant = {
|
|
8
9
|
storageEntry: StorageEntry;
|
|
9
10
|
} & AssetVariantMetadata;
|
|
@@ -23,11 +24,13 @@ export declare class PublisherServer {
|
|
|
23
24
|
collectionNameHeader: string | null;
|
|
24
25
|
serverTimingRequestHeader: string | null;
|
|
25
26
|
serverTiming: ServerTiming | null;
|
|
27
|
+
responseCache: ResponseCacheOptions | null;
|
|
26
28
|
settingsCached: PublisherServerConfigNormalized | null | undefined;
|
|
27
29
|
assetEntryMapCache: AssetEntryMap | null | undefined;
|
|
28
30
|
setActiveCollectionName(collectionName: string): void;
|
|
29
31
|
setCollectionNameHeader(collectionHeader: string | null): void;
|
|
30
32
|
setServerTimingRequestHeader(requestHeader: string | null): void;
|
|
33
|
+
setResponseCache(options: ResponseCacheOptions | null): void;
|
|
31
34
|
beginRequest(request: Request): void;
|
|
32
35
|
private timed;
|
|
33
36
|
getServerConfig(): Promise<PublisherServerConfigNormalized | null>;
|
|
@@ -37,10 +40,14 @@ export declare class PublisherServer {
|
|
|
37
40
|
findAcceptEncodingsGroups(request: Request): Promise<ContentCompressionTypes[][]>;
|
|
38
41
|
testExtendedCache(pathname: string): Promise<boolean>;
|
|
39
42
|
handlePreconditions(request: Request, asset: AssetEntry, responseHeaders: Headers): Response | null;
|
|
43
|
+
private handlePreconditionsForLastModified;
|
|
40
44
|
loadAssetVariant(entry: AssetEntry, variant: ContentCompressionTypes | null): Promise<AssetVariant | null>;
|
|
41
45
|
private findAssetVariantForAcceptEncodingsGroups;
|
|
42
46
|
serveAsset(request: Request, asset: AssetEntry, init?: AssetInit): Promise<Response>;
|
|
47
|
+
serveCached(request: Request, keyPath: string, produce: (request: Request) => Promise<Response | null>): Promise<Response | null>;
|
|
48
|
+
private responseFromCache;
|
|
43
49
|
serveRequest(request: Request): Promise<Response | null>;
|
|
50
|
+
private serveRequestFromStorage;
|
|
44
51
|
}
|
|
45
52
|
export {};
|
|
46
53
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/server/publisher-server/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/server/publisher-server/index.ts"],"names":[],"mappings":"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"}
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
* Copyright Fastly, Inc.
|
|
3
3
|
* Licensed under the MIT license. See LICENSE file for details.
|
|
4
4
|
*/
|
|
5
|
+
/// <reference types="@fastly/js-compute" />
|
|
6
|
+
import { CoreCache } from 'fastly:cache';
|
|
5
7
|
import { decodeAssetVariantMetadata, } from '../../models/assets/index.js';
|
|
6
8
|
import { decodeIndexMetadata, } from '../../models/server/index.js';
|
|
7
9
|
import { isExpired } from '../../models/time/index.js';
|
|
@@ -9,6 +11,7 @@ import { loadStorageProviderFromStaticPublishRc, } from '../storage/storage-prov
|
|
|
9
11
|
import { checkIfModifiedSince, getIfModifiedSinceHeader } from './serve-preconditions/if-modified-since.js';
|
|
10
12
|
import { checkIfNoneMatch, getIfNoneMatchHeader } from './serve-preconditions/if-none-match.js';
|
|
11
13
|
import { ServerTiming } from '../util/server-timing.js';
|
|
14
|
+
import { CACHEABLE_STATUSES, buildCacheFillRequest, buildResponseCacheKey, decodeCachedResponseMetadata, encodeCachedResponseMetadata, parseAcceptEncodingGroups, } from './response-cache.js';
|
|
12
15
|
export function buildHeadersSubset(responseHeaders, keys) {
|
|
13
16
|
const resultHeaders = new Headers();
|
|
14
17
|
for (const value of keys) {
|
|
@@ -45,6 +48,7 @@ export class PublisherServer {
|
|
|
45
48
|
this.collectionNameHeader = 'X-Publisher-Server-Collection';
|
|
46
49
|
this.serverTimingRequestHeader = null;
|
|
47
50
|
this.serverTiming = null;
|
|
51
|
+
this.responseCache = null;
|
|
48
52
|
}
|
|
49
53
|
static fromStaticPublishRc(config) {
|
|
50
54
|
const storeProvider = loadStorageProviderFromStaticPublishRc(config);
|
|
@@ -63,6 +67,14 @@ export class PublisherServer {
|
|
|
63
67
|
setServerTimingRequestHeader(requestHeader) {
|
|
64
68
|
this.serverTimingRequestHeader = requestHeader;
|
|
65
69
|
}
|
|
70
|
+
// Cache whole responses with the Core Cache API, keyed by collection, path,
|
|
71
|
+
// and the client's Accept-Encoding. A cache hit does not read the settings,
|
|
72
|
+
// the index, or the file from storage. Entries have the surrogate key
|
|
73
|
+
// `<publishId>-<collectionName>`, which publish-content purges. null (the
|
|
74
|
+
// default) turns the cache off.
|
|
75
|
+
setResponseCache(options) {
|
|
76
|
+
this.responseCache = options;
|
|
77
|
+
}
|
|
66
78
|
// Start handling a new request. serveRequest() calls this. If you call
|
|
67
79
|
// getMatchingAsset() and serveAsset() directly, call this first.
|
|
68
80
|
beginRequest(request) {
|
|
@@ -204,46 +216,7 @@ export class PublisherServer {
|
|
|
204
216
|
if (serverConfig == null || serverConfig.allowedEncodings.length === 0) {
|
|
205
217
|
return [];
|
|
206
218
|
}
|
|
207
|
-
|
|
208
|
-
if (acceptEncodingHeader == '') {
|
|
209
|
-
return [];
|
|
210
|
-
}
|
|
211
|
-
const priorityMap = new Map;
|
|
212
|
-
for (const headerValue of acceptEncodingHeader.trim().split(',')) {
|
|
213
|
-
let [encodingValue, qValueStr] = headerValue.trim().split(';');
|
|
214
|
-
encodingValue = encodingValue.trim();
|
|
215
|
-
if (!serverConfig.allowedEncodings.includes(encodingValue)) {
|
|
216
|
-
continue;
|
|
217
|
-
}
|
|
218
|
-
let qValue; // q value multiplied by 1000
|
|
219
|
-
if (qValueStr == null || !qValueStr.startsWith('q=')) {
|
|
220
|
-
// use default of 1.0
|
|
221
|
-
qValue = 1000;
|
|
222
|
-
}
|
|
223
|
-
else {
|
|
224
|
-
qValueStr = qValueStr.slice(2); // remove the q=
|
|
225
|
-
qValue = parseFloat(qValueStr);
|
|
226
|
-
if (Number.isNaN(qValue) || qValue > 1) {
|
|
227
|
-
qValue = 1;
|
|
228
|
-
}
|
|
229
|
-
if (qValue < 0) {
|
|
230
|
-
qValue = 0;
|
|
231
|
-
}
|
|
232
|
-
// q values can have up to 3 decimal digits
|
|
233
|
-
qValue = Math.floor(qValue * 1000);
|
|
234
|
-
}
|
|
235
|
-
let typesForQValue = priorityMap.get(qValue);
|
|
236
|
-
if (typesForQValue == null) {
|
|
237
|
-
typesForQValue = [];
|
|
238
|
-
priorityMap.set(qValue, typesForQValue);
|
|
239
|
-
}
|
|
240
|
-
typesForQValue.push(encodingValue);
|
|
241
|
-
}
|
|
242
|
-
// Sort keys, larger numbers to come first
|
|
243
|
-
const keysSorted = [...priorityMap.keys()]
|
|
244
|
-
.sort((qValueA, qValueB) => qValueB - qValueA);
|
|
245
|
-
return keysSorted
|
|
246
|
-
.map(qValue => priorityMap.get(qValue));
|
|
219
|
+
return parseAcceptEncodingGroups(request.headers.get('accept-encoding') ?? '', serverConfig.allowedEncodings);
|
|
247
220
|
}
|
|
248
221
|
async testExtendedCache(pathname) {
|
|
249
222
|
const staticItems = await this.getStaticItems();
|
|
@@ -259,6 +232,11 @@ export class PublisherServer {
|
|
|
259
232
|
});
|
|
260
233
|
}
|
|
261
234
|
handlePreconditions(request, asset, responseHeaders) {
|
|
235
|
+
return this.handlePreconditionsForLastModified(request, asset.lastModifiedTime, responseHeaders);
|
|
236
|
+
}
|
|
237
|
+
// lastModifiedTime is in seconds since the epoch, as in AssetEntry. A cached
|
|
238
|
+
// response has its headers, but not its AssetEntry.
|
|
239
|
+
handlePreconditionsForLastModified(request, lastModifiedTime, responseHeaders) {
|
|
262
240
|
// Handle preconditions according to https://httpwg.org/specs/rfc9110.html#rfc.section.13.2.2
|
|
263
241
|
// A recipient cache or origin server MUST evaluate the request preconditions defined by this specification in the following order:
|
|
264
242
|
// 1. When recipient is the origin server and If-Match is present, evaluate the If-Match precondition:
|
|
@@ -295,7 +273,7 @@ export class PublisherServer {
|
|
|
295
273
|
// For us, method is always GET or HEAD here.
|
|
296
274
|
const headerValue = getIfModifiedSinceHeader(request);
|
|
297
275
|
if (headerValue != null) {
|
|
298
|
-
const result = checkIfModifiedSince(
|
|
276
|
+
const result = checkIfModifiedSince(lastModifiedTime, headerValue);
|
|
299
277
|
if (!result) {
|
|
300
278
|
return new Response(null, {
|
|
301
279
|
status: 304,
|
|
@@ -412,6 +390,88 @@ export class PublisherServer {
|
|
|
412
390
|
headers,
|
|
413
391
|
});
|
|
414
392
|
}
|
|
393
|
+
// Serve a response through the response cache (see setResponseCache()).
|
|
394
|
+
// keyPath identifies the response in the active collection. Include in it
|
|
395
|
+
// anything other than the path and the Accept-Encoding that changes the response.
|
|
396
|
+
// On a miss, produce() is called with a GET request that has no conditional or
|
|
397
|
+
// range headers, and its result is cached if it is a 200 or 404 response, or
|
|
398
|
+
// null (not found). Conditional requests and HEAD are then answered from the
|
|
399
|
+
// cached response. If the cache is off, produce() gets the original request.
|
|
400
|
+
async serveCached(request, keyPath, produce) {
|
|
401
|
+
if (this.responseCache == null) {
|
|
402
|
+
return produce(request);
|
|
403
|
+
}
|
|
404
|
+
const key = buildResponseCacheKey(this.publishId, this.activeCollectionName, keyPath, request);
|
|
405
|
+
const lookupStart = performance.now();
|
|
406
|
+
const entry = CoreCache.transactionLookup(key);
|
|
407
|
+
const state = entry.state();
|
|
408
|
+
if (!state.mustInsertOrUpdate()) {
|
|
409
|
+
const metadata = state.found() && state.usable() ? decodeCachedResponseMetadata(entry.userMetadata()) : null;
|
|
410
|
+
if (metadata != null) {
|
|
411
|
+
this.serverTiming?.add('cache', performance.now() - lookupStart, 'hit');
|
|
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
|
+
let metadata;
|
|
429
|
+
let body;
|
|
430
|
+
if (response == null) {
|
|
431
|
+
metadata = { notFound: true };
|
|
432
|
+
body = new ArrayBuffer(0);
|
|
433
|
+
}
|
|
434
|
+
else if (CACHEABLE_STATUSES.includes(response.status)) {
|
|
435
|
+
const headers = new Headers(response.headers);
|
|
436
|
+
// Server-Timing describes one request, so it is not stored.
|
|
437
|
+
headers.delete('Server-Timing');
|
|
438
|
+
metadata = { status: response.status, headers: [...headers] };
|
|
439
|
+
body = await response.arrayBuffer();
|
|
440
|
+
}
|
|
441
|
+
else {
|
|
442
|
+
entry.cancel();
|
|
443
|
+
return response;
|
|
444
|
+
}
|
|
445
|
+
const writer = entry.insert({
|
|
446
|
+
maxAge: this.responseCache.maxAge,
|
|
447
|
+
surrogateKeys: [`${this.publishId}-${this.activeCollectionName}`],
|
|
448
|
+
userMetadata: encodeCachedResponseMetadata(metadata),
|
|
449
|
+
length: body.byteLength,
|
|
450
|
+
});
|
|
451
|
+
writer.append(body);
|
|
452
|
+
writer.close();
|
|
453
|
+
return this.responseFromCache(request, metadata, body);
|
|
454
|
+
}
|
|
455
|
+
responseFromCache(request, metadata, body) {
|
|
456
|
+
if (metadata.notFound) {
|
|
457
|
+
return null;
|
|
458
|
+
}
|
|
459
|
+
const headers = new Headers(metadata.headers);
|
|
460
|
+
if (this.serverTiming != null) {
|
|
461
|
+
headers.append('Server-Timing', this.serverTiming.toHeaderValue());
|
|
462
|
+
}
|
|
463
|
+
const lastModified = headers.get('Last-Modified');
|
|
464
|
+
const lastModifiedMs = lastModified != null ? Date.parse(lastModified) : NaN;
|
|
465
|
+
const lastModifiedTime = Number.isNaN(lastModifiedMs) ? 0 : Math.floor(lastModifiedMs / 1000);
|
|
466
|
+
const preconditionResponse = this.handlePreconditionsForLastModified(request, lastModifiedTime, headers);
|
|
467
|
+
if (preconditionResponse != null) {
|
|
468
|
+
return preconditionResponse;
|
|
469
|
+
}
|
|
470
|
+
return new Response(request.method === 'HEAD' ? null : body, {
|
|
471
|
+
status: metadata.status,
|
|
472
|
+
headers,
|
|
473
|
+
});
|
|
474
|
+
}
|
|
415
475
|
async serveRequest(request) {
|
|
416
476
|
this.beginRequest(request);
|
|
417
477
|
// Only handle GET and HEAD
|
|
@@ -424,6 +484,11 @@ export class PublisherServer {
|
|
|
424
484
|
if (pathname === '/healthz') {
|
|
425
485
|
return new Response("OK", { status: 200 });
|
|
426
486
|
}
|
|
487
|
+
// The fallback pages (SPA, not found) depend on whether the client accepts HTML.
|
|
488
|
+
const keyPath = requestAcceptsTextHtml(request) ? pathname : `${pathname}|no-html`;
|
|
489
|
+
return this.serveCached(request, keyPath, (fillRequest) => this.serveRequestFromStorage(fillRequest, pathname));
|
|
490
|
+
}
|
|
491
|
+
async serveRequestFromStorage(request, pathname) {
|
|
427
492
|
const serverConfig = await this.getServerConfig();
|
|
428
493
|
if (serverConfig == null) {
|
|
429
494
|
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
|
+
}
|
package/package.json
CHANGED