@fastly/compute-js-static-publish 8.0.0-beta.15 → 8.0.0-beta.17
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/publish-content.d.ts.map +1 -1
- package/build/cli/cli/commands/manage/publish-content.js +38 -4
- 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 +1 -4
- package/build/cli/cli/storage/s3-storage-provider.d.ts.map +1 -1
- package/build/cli/cli/storage/s3-storage-provider.js +2 -45
- package/build/cli/cli/storage/storage-provider.d.ts +0 -2
- package/build/cli/cli/storage/storage-provider.d.ts.map +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/server/server/publisher-server/index.d.ts +8 -0
- package/build/server/server/publisher-server/index.d.ts.map +1 -1
- package/build/server/server/publisher-server/index.js +135 -42
- 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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"publish-content.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/manage/publish-content.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"publish-content.d.ts","sourceRoot":"","sources":["../../../../../src/cli/commands/manage/publish-content.ts"],"names":[],"mappings":"AAyHA,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBAikBhD"}
|
|
@@ -13,6 +13,7 @@ import { applyDefaults } from '../../util/data.js';
|
|
|
13
13
|
import { calculateFileSizeAndHash, enumerateFiles, rootRelative } from '../../util/files.js';
|
|
14
14
|
import { ensureVariantFileExists } from '../../util/variants.js';
|
|
15
15
|
import { concurrentMap } from '../../util/retryable.js';
|
|
16
|
+
import { loadPurgeTarget, purgeSurrogateKey } from '../../util/purge.js';
|
|
16
17
|
import { getStorageKeysByHexPrefix, loadStorageProviderFromStaticPublishRc, StorageProviderBatch, } from '../../storage/storage-provider.js';
|
|
17
18
|
// Storage key format:
|
|
18
19
|
// <publishId>_index_<preview_id>.json
|
|
@@ -47,12 +48,16 @@ Optional:
|
|
|
47
48
|
If not set, the tool uses the FASTLY_API_TOKEN
|
|
48
49
|
environment variable.
|
|
49
50
|
|
|
50
|
-
--fastly-service-id=<id> Fastly Service ID to purge after publishing (
|
|
51
|
+
--fastly-service-id=<id> Fastly Service ID to purge after publishing (not with --local).
|
|
51
52
|
If not set, the tool will check:
|
|
52
53
|
1. service_id in fastly.toml
|
|
53
54
|
2. FASTLY_SERVICE_ID environment variable
|
|
54
55
|
If none is found, the purge is skipped.
|
|
55
56
|
|
|
57
|
+
--purge-environment=<env> Environment to purge: production, staging, or a
|
|
58
|
+
comma-separated list of both. Can be repeated.
|
|
59
|
+
Default: production
|
|
60
|
+
|
|
56
61
|
--overwrite-existing Always overwrite existing entries in storage, even if unchanged.
|
|
57
62
|
|
|
58
63
|
--brotli-quality=<0-11> Brotli quality for the 'br' variants. Overrides
|
|
@@ -111,6 +116,7 @@ export async function action(actionArgs) {
|
|
|
111
116
|
{ name: 'local', type: Boolean },
|
|
112
117
|
{ name: 'fastly-api-token', type: String, },
|
|
113
118
|
{ name: 'fastly-service-id', type: String, },
|
|
119
|
+
{ name: 'purge-environment', type: String, multiple: true, },
|
|
114
120
|
{ name: 'kv-overwrite', type: Boolean },
|
|
115
121
|
{ name: 's3-access-key-id', type: String, },
|
|
116
122
|
{ name: 's3-secret-access-key', type: String, },
|
|
@@ -126,7 +132,7 @@ export async function action(actionArgs) {
|
|
|
126
132
|
help();
|
|
127
133
|
return;
|
|
128
134
|
}
|
|
129
|
-
const { verbose, config: configFilePathValue, ['collection-name']: collectionNameValue, ['root-dir']: rootDir, ['overwrite-existing']: _overwriteExisting, ['brotli-quality']: brotliQualityValue, ['expires-in']: expiresIn, ['expires-at']: expiresAt, ['expires-never']: expiresNever, local: localMode, ['fastly-api-token']: fastlyApiToken, ['fastly-service-id']: fastlyServiceId, ['kv-overwrite']: _kvOverwrite, ['s3-access-key-id']: s3AccessKeyId, ['s3-secret-access-key']: s3SecretAccessKey, ['s3-upload-concurrency']: s3UploadConcurrencyValue, } = parsed.commandLineOptions;
|
|
135
|
+
const { verbose, config: configFilePathValue, ['collection-name']: collectionNameValue, ['root-dir']: rootDir, ['overwrite-existing']: _overwriteExisting, ['brotli-quality']: brotliQualityValue, ['expires-in']: expiresIn, ['expires-at']: expiresAt, ['expires-never']: expiresNever, local: localMode, ['fastly-api-token']: fastlyApiToken, ['fastly-service-id']: fastlyServiceId, ['purge-environment']: purgeEnvironmentValues, ['kv-overwrite']: _kvOverwrite, ['s3-access-key-id']: s3AccessKeyId, ['s3-secret-access-key']: s3SecretAccessKey, ['s3-upload-concurrency']: s3UploadConcurrencyValue, } = parsed.commandLineOptions;
|
|
130
136
|
let s3UploadConcurrency;
|
|
131
137
|
if (s3UploadConcurrencyValue !== undefined) {
|
|
132
138
|
if (typeof s3UploadConcurrencyValue !== 'string' || !/^\d+$/.test(s3UploadConcurrencyValue) ||
|
|
@@ -219,7 +225,6 @@ export async function action(actionArgs) {
|
|
|
219
225
|
computeAppDir,
|
|
220
226
|
localMode,
|
|
221
227
|
fastlyApiToken,
|
|
222
|
-
fastlyServiceId,
|
|
223
228
|
s3AccessKeyId,
|
|
224
229
|
s3SecretAccessKey,
|
|
225
230
|
s3UploadConcurrency,
|
|
@@ -231,6 +236,22 @@ export async function action(actionArgs) {
|
|
|
231
236
|
process.exitCode = 1;
|
|
232
237
|
return;
|
|
233
238
|
}
|
|
239
|
+
// Purge target: checked now, so that a missing API token fails before anything is uploaded.
|
|
240
|
+
let purgeTarget;
|
|
241
|
+
try {
|
|
242
|
+
purgeTarget = loadPurgeTarget({
|
|
243
|
+
localMode: localMode ?? false,
|
|
244
|
+
computeAppDir,
|
|
245
|
+
fastlyServiceId,
|
|
246
|
+
fastlyApiToken,
|
|
247
|
+
purgeEnvironments: purgeEnvironmentValues,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
catch (err) {
|
|
251
|
+
console.error(String(err));
|
|
252
|
+
process.exitCode = 1;
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
234
255
|
// Load content types
|
|
235
256
|
const contentTypes = mergeContentTypes(publishContentConfig.contentTypes);
|
|
236
257
|
// #### Collect all file paths
|
|
@@ -532,6 +553,19 @@ export async function action(actionArgs) {
|
|
|
532
553
|
const settingsFilePath = path.resolve(storageContentDir, settingsFileName);
|
|
533
554
|
await storageProvider.submitStorageEntry(settingsFileKey, settingsFilePath, JSON.stringify(serverSettings));
|
|
534
555
|
console.log(`✅ Settings have been saved.`);
|
|
535
|
-
|
|
556
|
+
if (purgeTarget != null) {
|
|
557
|
+
const surrogateKey = `${publishId}-${collectionName}`;
|
|
558
|
+
for (const environment of purgeTarget.environments) {
|
|
559
|
+
console.log(`Purging surrogate key [${surrogateKey}] on service [${purgeTarget.serviceId}] (${environment})...`);
|
|
560
|
+
const purged = await purgeSurrogateKey(purgeTarget.fastlyApiContext, purgeTarget.serviceId, surrogateKey, true, environment);
|
|
561
|
+
if (purged) {
|
|
562
|
+
console.log('Purged');
|
|
563
|
+
}
|
|
564
|
+
else {
|
|
565
|
+
// The content is published. Only the cached copies may be stale until they expire.
|
|
566
|
+
console.warn(`⚠️ Warning: Failed purging (${environment}). Cached copies may be served until they expire.`);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
536
570
|
console.log(`🎉 Completed.`);
|
|
537
571
|
}
|
|
@@ -14,6 +14,5 @@ export declare class KvStoreLocalProvider implements StorageProvider {
|
|
|
14
14
|
key: string;
|
|
15
15
|
}>(objects: TObject[], fn: (obj: TObject, key: string, index: number) => Promise<void>, maxConcurrent?: number, throwOnError?: boolean): Promise<void>;
|
|
16
16
|
calculateNumChunks(size: number): number;
|
|
17
|
-
purgeSurrogateKey(_surrogateKey: string): Promise<void>;
|
|
18
17
|
}
|
|
19
18
|
//# sourceMappingURL=kv-store-local-provider.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kv-store-local-provider.d.ts","sourceRoot":"","sources":["../../../../src/cli/storage/kv-store-local-provider.ts"],"names":[],"mappings":"AA0BA,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAE3B,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EACvB,MAAM,uBAAuB,CAAC;AAK/B,eAAO,MAAM,kBAAkB,EAAE,sBAkBhC,CAAC;AAEF,qBAAa,oBAAqB,YAAW,eAAe;gBAExD,SAAS,EAAE,MAAM,EACjB,aAAa,EAAE,MAAM;IAMvB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAEzB,cAAc,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC;IAQzD,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAc1D,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAe9D,kBAAkB,CACtB,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,UAAU,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,EACzE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,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AG,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAe9D,kBAAkB,CACtB,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,UAAU,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,EACzE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAChC,OAAO,CAAC,IAAI,CAAC;IAsBV,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAS9C,UAAU,CAAC,KAAK,EAAE,oBAAoB,EAAE,QAAQ,GAAE,iBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC;IAmBxF,oBAAoB,CAAC,OAAO,SAAS;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,EACxD,OAAO,EAAE,OAAO,EAAE,EAClB,EAAE,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,EAC/D,aAAa,CAAC,EAAE,MAAM,EACtB,YAAY,GAAE,OAAe,GAC5B,OAAO,CAAC,IAAI,CAAC;IAYhB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAGzC"}
|
|
@@ -17,7 +17,6 @@ export declare class KvStoreProvider implements StorageProvider {
|
|
|
17
17
|
key: string;
|
|
18
18
|
}>(objects: TObject[], fn: (obj: TObject, key: string, index: number) => Promise<void>, maxConcurrent?: number, throwOnError?: boolean): Promise<void>;
|
|
19
19
|
calculateNumChunks(size: number): number;
|
|
20
|
-
purgeSurrogateKey(_surrogateKey: string): Promise<void>;
|
|
21
20
|
}
|
|
22
21
|
export declare function kvStoreEntryToStorageEntry(kvStoreEntry: KvStoreEntryInfo): StorageEntry;
|
|
23
22
|
export declare function parseKvStoreMetadata(metadata: string): Record<string, string> | null;
|
|
@@ -1 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AAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAiB9D,kBAAkB,CACtB,GAAG,EAAE,MAAM,EACX,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,UAAU,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,EACzE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAChC,OAAO,CAAC,IAAI,CAAC;IAYV,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAU9C,UAAU,CAAC,KAAK,EAAE,oBAAoB,EAAE,OAAO,GAAE,iBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC;IAsBvF,aAAa,CAAC,OAAO,EAAE,yBAAyB,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IA0ClE,oBAAoB,CAAC,OAAO,SAAS;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,EACxD,OAAO,EAAE,OAAO,EAAE,EAClB,EAAE,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,EAC/D,aAAa,GAAE,MAAW,EAC1B,YAAY,GAAE,OAAe,GAC5B,OAAO,CAAC,IAAI,CAAC;IAqBhB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAIzC;AAED,wBAAgB,0BAA0B,CACxC,YAAY,EAAE,gBAAgB,gBAuB/B;AAED,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,iCAiCpD"}
|
|
@@ -107,8 +107,6 @@ export class KvStoreProvider {
|
|
|
107
107
|
calculateNumChunks(size) {
|
|
108
108
|
return Math.ceil(size / KV_STORE_CHUNK_SIZE);
|
|
109
109
|
}
|
|
110
|
-
async purgeSurrogateKey(_surrogateKey) {
|
|
111
|
-
}
|
|
112
110
|
}
|
|
113
111
|
export function kvStoreEntryToStorageEntry(kvStoreEntry) {
|
|
114
112
|
const storageEntry = {};
|
|
@@ -5,9 +5,7 @@ type CommandOutput<C> = C extends Command<any, any, any, infer O, any> ? O : nev
|
|
|
5
5
|
export declare const DEFAULT_S3_UPLOAD_CONCURRENCY = 64;
|
|
6
6
|
export declare const buildStoreProvider: StorageProviderBuilder;
|
|
7
7
|
export declare class S3StorageProvider implements StorageProvider {
|
|
8
|
-
constructor(
|
|
9
|
-
private readonly fastlyServiceId?;
|
|
10
|
-
private readonly fastlyApiContext?;
|
|
8
|
+
constructor(s3Region: string, accessKeyId: string, secretAccessKey: string, s3Bucket: string, s3Endpoint?: string, uploadConcurrency?: number);
|
|
11
9
|
private readonly s3Region;
|
|
12
10
|
private readonly accessKeyId;
|
|
13
11
|
private readonly secretAccessKey;
|
|
@@ -27,7 +25,6 @@ export declare class S3StorageProvider implements StorageProvider {
|
|
|
27
25
|
key: string;
|
|
28
26
|
}>(objects: TObject[], fn: (obj: TObject, key: string, index: number) => Promise<void>, maxConcurrent?: number, throwOnError?: boolean): Promise<void>;
|
|
29
27
|
calculateNumChunks(_size: number): number;
|
|
30
|
-
purgeSurrogateKey(surrogateKey: string): Promise<void>;
|
|
31
28
|
}
|
|
32
29
|
export {};
|
|
33
30
|
//# sourceMappingURL=s3-storage-provider.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"s3-storage-provider.d.ts","sourceRoot":"","sources":["../../../../src/cli/storage/s3-storage-provider.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"s3-storage-provider.d.ts","sourceRoot":"","sources":["../../../../src/cli/storage/s3-storage-provider.ts"],"names":[],"mappings":"AAQA,OAAO,EAUL,QAAQ,EAIT,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,KAAK,OAAO,EACZ,KAAK,kBAAkB,EACxB,MAAM,gBAAgB,CAAC;AASxB,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,sBAAsB,EA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GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAwB9D,kBAAkB,CACtB,GAAG,EAAE,MAAM,EACX,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,UAAU,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,EACzE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAChC,OAAO,CAAC,IAAI,CAAC;IAaV,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAW9C,UAAU,CAAC,KAAK,EAAE,oBAAoB,EAAE,OAAO,GAAE,iBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC;IA8BvF,oBAAoB,CAAC,OAAO,SAAS;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,EACxD,OAAO,EAAE,OAAO,EAAE,EAClB,EAAE,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,EAC/D,aAAa,GAAE,MAAW,EAC1B,YAAY,GAAE,OAAe,GAC5B,OAAO,CAAC,IAAI,CAAC;IAmBhB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;CAI1C"}
|
|
@@ -5,7 +5,6 @@
|
|
|
5
5
|
import fs from 'node:fs';
|
|
6
6
|
import http from 'node:http';
|
|
7
7
|
import https from 'node:https';
|
|
8
|
-
import path from 'node:path';
|
|
9
8
|
import { DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, PutObjectCommand, S3Client, S3ServiceException, paginateListObjectsV2, } from '@aws-sdk/client-s3';
|
|
10
9
|
import { isS3StorageConfigRc, } from '../../models/config/static-publish-rc.js';
|
|
11
10
|
import { getS3StorageConfigFromRc, } from '../../models/config/s3-storage-config.js';
|
|
@@ -13,9 +12,6 @@ import { entriesToUpload } from '../util/kv-store-items.js';
|
|
|
13
12
|
import { loadS3Credentials, } from '../util/s3-credentials.js';
|
|
14
13
|
import { concurrentParallel, makeRetryable, } from '../util/retryable.js';
|
|
15
14
|
import { rootRelative, } from '../util/files.js';
|
|
16
|
-
import { loadApiToken, } from '../util/api-token.js';
|
|
17
|
-
import { loadServiceId, } from '../util/service-id.js';
|
|
18
|
-
import { purgeSurrogateKey, } from '../util/purge.js';
|
|
19
15
|
// The number of objects to upload at the same time. S3 accepts many parallel
|
|
20
16
|
// requests, and each request mostly waits for the network. In a test with small
|
|
21
17
|
// objects, 64 was approximately 4 times faster than 12.
|
|
@@ -40,31 +36,11 @@ export const buildStoreProvider = async (config, context) => {
|
|
|
40
36
|
throw new Error("❌ S3 Credentials not provided.\nProvide an access key ID and secret access key that have write access to the S3 or compatible storage.\nRefer to the README file and --help for additional information.");
|
|
41
37
|
}
|
|
42
38
|
console.log(`✔️ S3 Credentials: ${s3CredentialsResult.s3AccessKeyId.slice(0, 4)}${'*'.repeat(s3CredentialsResult.s3AccessKeyId.length - 4)} from '${s3CredentialsResult.source}'`);
|
|
43
|
-
|
|
44
|
-
commandLine: context.fastlyServiceId,
|
|
45
|
-
fastlyTomlPath: path.resolve(context.computeAppDir, 'fastly.toml'),
|
|
46
|
-
});
|
|
47
|
-
const serviceId = serviceIdResult?.serviceId;
|
|
48
|
-
let apiToken = undefined;
|
|
49
|
-
if (serviceIdResult == null) {
|
|
50
|
-
console.log(`- Service ID not found (--fastly-service-id, fastly.toml, or FASTLY_SERVICE_ID). Will skip purge step after publish.`);
|
|
51
|
-
}
|
|
52
|
-
else {
|
|
53
|
-
console.log(`✔️ Service ID from ${serviceIdResult.source}: ${serviceIdResult.serviceId}`);
|
|
54
|
-
const apiTokenResult = loadApiToken({ commandLine: context.fastlyApiToken });
|
|
55
|
-
if (apiTokenResult == null) {
|
|
56
|
-
throw new Error("❌ Fastly API Token not provided.\nSet the FASTLY_API_TOKEN environment variable to an API token that has write access to the KV Store.");
|
|
57
|
-
}
|
|
58
|
-
console.log(`✔️ Fastly API Token: ${apiTokenResult.apiToken.slice(0, 4)}${'*'.repeat(apiTokenResult.apiToken.length - 4)} from '${apiTokenResult.source}'`);
|
|
59
|
-
apiToken = apiTokenResult.apiToken;
|
|
60
|
-
}
|
|
61
|
-
return new S3StorageProvider(serviceId, apiToken, region, s3CredentialsResult.s3AccessKeyId, s3CredentialsResult.s3SecretAccessKey, bucket, endpoint, context.s3UploadConcurrency ?? DEFAULT_S3_UPLOAD_CONCURRENCY);
|
|
39
|
+
return new S3StorageProvider(region, s3CredentialsResult.s3AccessKeyId, s3CredentialsResult.s3SecretAccessKey, bucket, endpoint, context.s3UploadConcurrency ?? DEFAULT_S3_UPLOAD_CONCURRENCY);
|
|
62
40
|
};
|
|
63
41
|
export class S3StorageProvider {
|
|
64
|
-
constructor(
|
|
42
|
+
constructor(s3Region, accessKeyId, secretAccessKey, s3Bucket, s3Endpoint, uploadConcurrency = DEFAULT_S3_UPLOAD_CONCURRENCY) {
|
|
65
43
|
this.uploadConcurrency = uploadConcurrency;
|
|
66
|
-
this.fastlyServiceId = fastlyServiceId;
|
|
67
|
-
this.fastlyApiContext = fastlyApiToken != null ? { apiToken: fastlyApiToken } : undefined;
|
|
68
44
|
this.s3Region = s3Region;
|
|
69
45
|
this.accessKeyId = accessKeyId;
|
|
70
46
|
this.secretAccessKey = secretAccessKey;
|
|
@@ -202,7 +178,6 @@ export class S3StorageProvider {
|
|
|
202
178
|
toWrite = entriesToUpload(toWrite, existingKeys);
|
|
203
179
|
}
|
|
204
180
|
console.log(`📤 Uploading ${toWrite.length} entries to S3 storage (${this.uploadConcurrency} at a time).`);
|
|
205
|
-
// fastlyApiContext is non-null if useKvStore is true
|
|
206
181
|
await this.doConcurrentParallel(toWrite, async ({ filePath, metadataJson }, key) => {
|
|
207
182
|
// const fileStream = fs.createReadStream(filePath);
|
|
208
183
|
const fileData = fs.readFileSync(filePath);
|
|
@@ -225,22 +200,4 @@ export class S3StorageProvider {
|
|
|
225
200
|
calculateNumChunks(_size) {
|
|
226
201
|
return 1;
|
|
227
202
|
}
|
|
228
|
-
async purgeSurrogateKey(surrogateKey) {
|
|
229
|
-
if (this.fastlyServiceId == null) {
|
|
230
|
-
console.log('Fastly Service ID not set, skipping purge...');
|
|
231
|
-
return;
|
|
232
|
-
}
|
|
233
|
-
if (this.fastlyApiContext?.apiToken == null) {
|
|
234
|
-
console.log('Fastly API token not set, skipping purge...');
|
|
235
|
-
return;
|
|
236
|
-
}
|
|
237
|
-
console.log(`Purging surrogate key [${surrogateKey}] on service [${this.fastlyServiceId}]...`);
|
|
238
|
-
const result = await purgeSurrogateKey(this.fastlyApiContext, this.fastlyServiceId, surrogateKey, true);
|
|
239
|
-
if (result) {
|
|
240
|
-
console.log('Purged');
|
|
241
|
-
}
|
|
242
|
-
else {
|
|
243
|
-
console.log('Failed purging');
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
203
|
}
|
|
@@ -15,7 +15,6 @@ export interface StorageProvider {
|
|
|
15
15
|
key: string;
|
|
16
16
|
}>(objects: TObject[], fn: (obj: TObject, key: string, index: number) => Promise<void>, maxConcurrent?: number, throwOnError?: boolean): Promise<void>;
|
|
17
17
|
calculateNumChunks(size: number): number;
|
|
18
|
-
purgeSurrogateKey(surrogateKey: string): Promise<void>;
|
|
19
18
|
}
|
|
20
19
|
export type StorageProviderBatchEntry = {
|
|
21
20
|
size: number;
|
|
@@ -35,7 +34,6 @@ export type StorageProviderBuilderContext = {
|
|
|
35
34
|
computeAppDir: string;
|
|
36
35
|
localMode?: boolean;
|
|
37
36
|
fastlyApiToken?: string;
|
|
38
|
-
fastlyServiceId?: string;
|
|
39
37
|
s3AccessKeyId?: string;
|
|
40
38
|
s3SecretAccessKey?: string;
|
|
41
39
|
s3UploadConcurrency?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage-provider.d.ts","sourceRoot":"","sources":["../../../../src/cli/storage/storage-provider.ts"],"names":[],"mappings":"AAKA,OA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,wBAAsB,yBAAyB,CAAC,eAAe,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,CAQ1H;AAGD,wBAAgB,8BAA8B,CAAC,OAAO,EAAE,sBAAsB,QAE7E;AAED,wBAAsB,sCAAsC,CAAC,MAAM,EAAE,eAAe,EAAE,OAAO,EAAE,6BAA6B,4BAS3H"}
|
|
@@ -1,3 +1,19 @@
|
|
|
1
1
|
import { type FastlyApiContext } from './api-token.js';
|
|
2
|
-
export declare
|
|
2
|
+
export declare const purgeEnvironments: readonly ["production", "staging"];
|
|
3
|
+
export type PurgeEnvironment = typeof purgeEnvironments[number];
|
|
4
|
+
export declare function parsePurgeEnvironments(values: unknown): PurgeEnvironment[];
|
|
5
|
+
export type PurgeTarget = {
|
|
6
|
+
serviceId: string;
|
|
7
|
+
fastlyApiContext: FastlyApiContext;
|
|
8
|
+
environments: PurgeEnvironment[];
|
|
9
|
+
};
|
|
10
|
+
export type LoadPurgeTargetParams = {
|
|
11
|
+
localMode: boolean;
|
|
12
|
+
computeAppDir: string;
|
|
13
|
+
fastlyServiceId: unknown;
|
|
14
|
+
fastlyApiToken: unknown;
|
|
15
|
+
purgeEnvironments: unknown;
|
|
16
|
+
};
|
|
17
|
+
export declare function loadPurgeTarget(params: LoadPurgeTargetParams): PurgeTarget | null;
|
|
18
|
+
export declare function purgeSurrogateKey(fastlyApiContext: FastlyApiContext, fastlyServiceId: string, surrogateKey: string, softPurge?: boolean, environment?: PurgeEnvironment): Promise<boolean>;
|
|
3
19
|
//# sourceMappingURL=purge.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"purge.d.ts","sourceRoot":"","sources":["../../../../src/cli/util/purge.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"purge.d.ts","sourceRoot":"","sources":["../../../../src/cli/util/purge.ts"],"names":[],"mappings":"AAOA,OAAO,EAAiB,KAAK,gBAAgB,EAA4B,MAAM,gBAAgB,CAAC;AAGhG,eAAO,MAAM,iBAAiB,oCAAuC,CAAC;AACtE,MAAM,MAAM,gBAAgB,GAAG,OAAO,iBAAiB,CAAC,MAAM,CAAC,CAAC;AAIhE,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,OAAO,GAAG,gBAAgB,EAAE,CAkB1E;AAED,MAAM,MAAM,WAAW,GAAG;IACxB,SAAS,EAAE,MAAM,CAAC;IAClB,gBAAgB,EAAE,gBAAgB,CAAC;IACnC,YAAY,EAAE,gBAAgB,EAAE,CAAC;CAClC,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG;IAClC,SAAS,EAAE,OAAO,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,OAAO,CAAC;IACzB,cAAc,EAAE,OAAO,CAAC;IACxB,iBAAiB,EAAE,OAAO,CAAC;CAC5B,CAAC;AAMF,wBAAgB,eAAe,CAAC,MAAM,EAAE,qBAAqB,GAAG,WAAW,GAAG,IAAI,CAgCjF;AAED,wBAAsB,iBAAiB,CACrC,gBAAgB,EAAE,gBAAgB,EAClC,eAAe,EAAE,MAAM,EACvB,YAAY,EAAE,MAAM,EACpB,SAAS,GAAE,OAAe,EAC1B,WAAW,GAAE,gBAA+B,oBA4B7C"}
|
|
@@ -2,8 +2,63 @@
|
|
|
2
2
|
* Copyright Fastly, Inc.
|
|
3
3
|
* Licensed under the MIT license. See LICENSE file for details.
|
|
4
4
|
*/
|
|
5
|
-
import
|
|
6
|
-
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { callFastlyApi, FetchError, loadApiToken } from './api-token.js';
|
|
7
|
+
import { loadServiceId } from './service-id.js';
|
|
8
|
+
export const purgeEnvironments = ['production', 'staging'];
|
|
9
|
+
// Parses the values of --purge-environment. The option can be repeated, and
|
|
10
|
+
// each value can be a comma-separated list. The default is production.
|
|
11
|
+
export function parsePurgeEnvironments(values) {
|
|
12
|
+
const list = Array.isArray(values) ? values : values == null ? [] : [values];
|
|
13
|
+
const result = [];
|
|
14
|
+
for (const value of list) {
|
|
15
|
+
for (const item of String(value).split(',')) {
|
|
16
|
+
const name = item.trim();
|
|
17
|
+
if (name === '') {
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
if (!purgeEnvironments.includes(name)) {
|
|
21
|
+
throw new Error(`❌ Unknown --purge-environment '${name}'. Use ${purgeEnvironments.join(', ')}, or a comma-separated list of them.`);
|
|
22
|
+
}
|
|
23
|
+
if (!result.includes(name)) {
|
|
24
|
+
result.push(name);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return result.length > 0 ? result : ['production'];
|
|
29
|
+
}
|
|
30
|
+
// Finds the service to purge after publishing, so that it stops serving cached
|
|
31
|
+
// copies of the collection. Returns null, and logs why, if the purge is skipped.
|
|
32
|
+
// Throws if a Service ID is found but an API token is not, so that this fails
|
|
33
|
+
// before anything is uploaded.
|
|
34
|
+
export function loadPurgeTarget(params) {
|
|
35
|
+
// Check the option even when the purge is skipped, so that a typo is reported.
|
|
36
|
+
const environments = parsePurgeEnvironments(params.purgeEnvironments);
|
|
37
|
+
if (params.localMode) {
|
|
38
|
+
console.log(`- Local mode: will skip purge step after publish.`);
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
const serviceIdResult = loadServiceId({
|
|
42
|
+
commandLine: params.fastlyServiceId,
|
|
43
|
+
fastlyTomlPath: path.resolve(params.computeAppDir, 'fastly.toml'),
|
|
44
|
+
});
|
|
45
|
+
if (serviceIdResult == null) {
|
|
46
|
+
console.log(`- Service ID not found (--fastly-service-id, fastly.toml, or FASTLY_SERVICE_ID). Will skip purge step after publish.`);
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
console.log(`✔️ Service ID from ${serviceIdResult.source}: ${serviceIdResult.serviceId}`);
|
|
50
|
+
const apiTokenResult = loadApiToken({ commandLine: params.fastlyApiToken });
|
|
51
|
+
if (apiTokenResult == null) {
|
|
52
|
+
throw new Error("❌ Fastly API Token not provided.\nSet the FASTLY_API_TOKEN environment variable to an API token that can purge the service.");
|
|
53
|
+
}
|
|
54
|
+
console.log(`✔️ Purge environments: ${environments.join(', ')}`);
|
|
55
|
+
return {
|
|
56
|
+
serviceId: serviceIdResult.serviceId,
|
|
57
|
+
fastlyApiContext: { apiToken: apiTokenResult.apiToken },
|
|
58
|
+
environments,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
export async function purgeSurrogateKey(fastlyApiContext, fastlyServiceId, surrogateKey, softPurge = false, environment = 'production') {
|
|
7
62
|
const endpoint = `/service/${encodeURIComponent(fastlyServiceId)}/purge`;
|
|
8
63
|
try {
|
|
9
64
|
const headers = new Headers();
|
|
@@ -11,7 +66,12 @@ export async function purgeSurrogateKey(fastlyApiContext, fastlyServiceId, surro
|
|
|
11
66
|
if (softPurge) {
|
|
12
67
|
headers.set('fastly-soft-purge', '1');
|
|
13
68
|
}
|
|
14
|
-
|
|
69
|
+
// A purge without this header applies to production. Staging needs it.
|
|
70
|
+
// See https://www.fastly.com/documentation/guides/getting-started/services/working-with-staging/
|
|
71
|
+
if (environment === 'staging') {
|
|
72
|
+
headers.set('fastly-purge-environment', 'staging');
|
|
73
|
+
}
|
|
74
|
+
await callFastlyApi(fastlyApiContext, endpoint, `Purging surrogate key [${surrogateKey}] on service [${fastlyServiceId}] (${environment})`, null, { method: 'POST', headers });
|
|
15
75
|
}
|
|
16
76
|
catch (err) {
|
|
17
77
|
if (err instanceof FetchError) {
|
|
@@ -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,15 @@ 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 copyBodyToCache;
|
|
49
|
+
private responseFromCache;
|
|
43
50
|
serveRequest(request: Request): Promise<Response | null>;
|
|
51
|
+
private serveRequestFromStorage;
|
|
44
52
|
}
|
|
45
53
|
export {};
|
|
46
54
|
//# 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":"AAUA,OAAO,EACL,KAAK,eAAe,EACrB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,KAAK,+BAA+B,EACrC,MAAM,gDAAgD,CAAC;AACxD,OAAO,EACL,KAAK,uBAAuB,EAC7B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,KAAK,UAAU,EACf,KAAK,aAAa,EAClB,KAAK,oBAAoB,EAE1B,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,eAAe,EAErB,MAAM,gCAAgC,CAAC;AAGxC,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAEL,KAAK,oBAAoB,EAO1B,MAAM,qBAAqB,CAAC;AAE7B,KAAK,YAAY,GAAG;IAClB,YAAY,EAAE,YAAY,CAAC;CAC5B,GAAG,oBAAoB,CAAC;AAEzB,wBAAgB,kBAAkB,CAAC,eAAe,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC,WAWpF;AAmBD,KAAK,SAAS,GAAG;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,KAAK,CAAC,EAAE,UAAU,GAAG,OAAO,GAAG,IAAI,CAAC;CACrC,CAAC;AAEF,qBAAa,eAAe;gBAExB,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,eAAe,EAChC,qBAAqB,EAAE,MAAM;IAY/B,MAAM,CAAC,mBAAmB,CAAC,MAAM,EAAE,eAAe;IASlD,SAAS,EAAE,MAAM,CAAC;IAClB,eAAe,EAAE,eAAe,CAAC;IACjC,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AAE,IAAI,CAAC,EAAE,SAAS,GAAG,OAAO,CAAC,QAAQ,CAAC;IA4DpF,WAAW,CACf,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,GACtD,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;YAyEb,eAAe;IAoB7B,OAAO,CAAC,iBAAiB;IAwBnB,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;YAsBhD,uBAAuB;CAwDtC"}
|
|
@@ -2,6 +2,7 @@
|
|
|
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';
|
|
@@ -9,10 +10,11 @@ import { loadStorageProviderFromStaticPublishRc, } from '../storage/storage-prov
|
|
|
9
10
|
import { checkIfModifiedSince, getIfModifiedSinceHeader } from './serve-preconditions/if-modified-since.js';
|
|
10
11
|
import { checkIfNoneMatch, getIfNoneMatchHeader } from './serve-preconditions/if-none-match.js';
|
|
11
12
|
import { ServerTiming } from '../util/server-timing.js';
|
|
13
|
+
import { CACHEABLE_STATUSES, buildCacheFillRequest, buildResponseCacheKey, decodeCachedResponseMetadata, encodeCachedResponseMetadata, parseAcceptEncodingGroups, } from './response-cache.js';
|
|
12
14
|
export function buildHeadersSubset(responseHeaders, keys) {
|
|
13
15
|
const resultHeaders = new Headers();
|
|
14
16
|
for (const value of keys) {
|
|
15
|
-
if (value
|
|
17
|
+
if (responseHeaders.has(value)) {
|
|
16
18
|
const responseHeaderValue = responseHeaders.get(value);
|
|
17
19
|
if (responseHeaderValue != null) {
|
|
18
20
|
resultHeaders.set(value, responseHeaderValue);
|
|
@@ -45,6 +47,7 @@ export class PublisherServer {
|
|
|
45
47
|
this.collectionNameHeader = 'X-Publisher-Server-Collection';
|
|
46
48
|
this.serverTimingRequestHeader = null;
|
|
47
49
|
this.serverTiming = null;
|
|
50
|
+
this.responseCache = null;
|
|
48
51
|
}
|
|
49
52
|
static fromStaticPublishRc(config) {
|
|
50
53
|
const storeProvider = loadStorageProviderFromStaticPublishRc(config);
|
|
@@ -63,6 +66,14 @@ export class PublisherServer {
|
|
|
63
66
|
setServerTimingRequestHeader(requestHeader) {
|
|
64
67
|
this.serverTimingRequestHeader = requestHeader;
|
|
65
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
|
+
}
|
|
66
77
|
// Start handling a new request. serveRequest() calls this. If you call
|
|
67
78
|
// getMatchingAsset() and serveAsset() directly, call this first.
|
|
68
79
|
beginRequest(request) {
|
|
@@ -204,46 +215,7 @@ export class PublisherServer {
|
|
|
204
215
|
if (serverConfig == null || serverConfig.allowedEncodings.length === 0) {
|
|
205
216
|
return [];
|
|
206
217
|
}
|
|
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));
|
|
218
|
+
return parseAcceptEncodingGroups(request.headers.get('accept-encoding') ?? '', serverConfig.allowedEncodings);
|
|
247
219
|
}
|
|
248
220
|
async testExtendedCache(pathname) {
|
|
249
221
|
const staticItems = await this.getStaticItems();
|
|
@@ -259,6 +231,11 @@ export class PublisherServer {
|
|
|
259
231
|
});
|
|
260
232
|
}
|
|
261
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) {
|
|
262
239
|
// Handle preconditions according to https://httpwg.org/specs/rfc9110.html#rfc.section.13.2.2
|
|
263
240
|
// A recipient cache or origin server MUST evaluate the request preconditions defined by this specification in the following order:
|
|
264
241
|
// 1. When recipient is the origin server and If-Match is present, evaluate the If-Match precondition:
|
|
@@ -295,7 +272,7 @@ export class PublisherServer {
|
|
|
295
272
|
// For us, method is always GET or HEAD here.
|
|
296
273
|
const headerValue = getIfModifiedSinceHeader(request);
|
|
297
274
|
if (headerValue != null) {
|
|
298
|
-
const result = checkIfModifiedSince(
|
|
275
|
+
const result = checkIfModifiedSince(lastModifiedTime, headerValue);
|
|
299
276
|
if (!result) {
|
|
300
277
|
return new Response(null, {
|
|
301
278
|
status: 304,
|
|
@@ -412,6 +389,117 @@ export class PublisherServer {
|
|
|
412
389
|
headers,
|
|
413
390
|
});
|
|
414
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
|
+
maxAge: this.responseCache.maxAge,
|
|
430
|
+
surrogateKeys: [`${this.publishId}-${this.activeCollectionName}`],
|
|
431
|
+
};
|
|
432
|
+
if (response == null) {
|
|
433
|
+
const metadata = { notFound: true };
|
|
434
|
+
const writer = entry.insert({
|
|
435
|
+
...insertOptions,
|
|
436
|
+
userMetadata: encodeCachedResponseMetadata(metadata),
|
|
437
|
+
length: 0,
|
|
438
|
+
});
|
|
439
|
+
writer.close();
|
|
440
|
+
return null;
|
|
441
|
+
}
|
|
442
|
+
if (!CACHEABLE_STATUSES.includes(response.status)) {
|
|
443
|
+
entry.cancel();
|
|
444
|
+
return response;
|
|
445
|
+
}
|
|
446
|
+
const headers = new Headers(response.headers);
|
|
447
|
+
// Server-Timing describes one request, so it is not stored.
|
|
448
|
+
headers.delete('Server-Timing');
|
|
449
|
+
const metadata = { status: response.status, headers: [...headers] };
|
|
450
|
+
const contentLength = Number(headers.get('Content-Length'));
|
|
451
|
+
// Stream the body into the cache entry, and give the client (and any requests
|
|
452
|
+
// waiting on this key) the entry's own stream as it fills. FastlyBody.append()
|
|
453
|
+
// can take only host-backed streams, and the storage providers build their
|
|
454
|
+
// bodies in JavaScript, so copy the chunks.
|
|
455
|
+
const [writer, streamedEntry] = entry.insertAndStreamBack({
|
|
456
|
+
...insertOptions,
|
|
457
|
+
userMetadata: encodeCachedResponseMetadata(metadata),
|
|
458
|
+
length: Number.isInteger(contentLength) && headers.has('Content-Length') ? contentLength : undefined,
|
|
459
|
+
});
|
|
460
|
+
void this.copyBodyToCache(response, writer);
|
|
461
|
+
return this.responseFromCache(request, metadata, streamedEntry.body());
|
|
462
|
+
}
|
|
463
|
+
async copyBodyToCache(response, writer) {
|
|
464
|
+
try {
|
|
465
|
+
if (response.body != null) {
|
|
466
|
+
const reader = response.body.getReader();
|
|
467
|
+
for (;;) {
|
|
468
|
+
const { done, value } = await reader.read();
|
|
469
|
+
if (done) {
|
|
470
|
+
break;
|
|
471
|
+
}
|
|
472
|
+
writer.append(value);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
writer.close();
|
|
476
|
+
}
|
|
477
|
+
catch (err) {
|
|
478
|
+
// Without close(), the cache treats the insertion as incomplete, so a
|
|
479
|
+
// partial body is not kept. Readers of this entry get a stream error.
|
|
480
|
+
console.error('Could not write the response to the cache:', err);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
responseFromCache(request, metadata, body) {
|
|
484
|
+
if (metadata.notFound) {
|
|
485
|
+
return null;
|
|
486
|
+
}
|
|
487
|
+
const headers = new Headers(metadata.headers);
|
|
488
|
+
if (this.serverTiming != null) {
|
|
489
|
+
headers.append('Server-Timing', this.serverTiming.toHeaderValue());
|
|
490
|
+
}
|
|
491
|
+
const lastModified = headers.get('Last-Modified');
|
|
492
|
+
const lastModifiedMs = lastModified != null ? Date.parse(lastModified) : NaN;
|
|
493
|
+
const lastModifiedTime = Number.isNaN(lastModifiedMs) ? 0 : Math.floor(lastModifiedMs / 1000);
|
|
494
|
+
const preconditionResponse = this.handlePreconditionsForLastModified(request, lastModifiedTime, headers);
|
|
495
|
+
if (preconditionResponse != null) {
|
|
496
|
+
return preconditionResponse;
|
|
497
|
+
}
|
|
498
|
+
return new Response(request.method === 'HEAD' ? null : body, {
|
|
499
|
+
status: metadata.status,
|
|
500
|
+
headers,
|
|
501
|
+
});
|
|
502
|
+
}
|
|
415
503
|
async serveRequest(request) {
|
|
416
504
|
this.beginRequest(request);
|
|
417
505
|
// Only handle GET and HEAD
|
|
@@ -424,6 +512,11 @@ export class PublisherServer {
|
|
|
424
512
|
if (pathname === '/healthz') {
|
|
425
513
|
return new Response("OK", { status: 200 });
|
|
426
514
|
}
|
|
515
|
+
// The fallback pages (SPA, not found) depend on whether the client accepts HTML.
|
|
516
|
+
const keyPath = requestAcceptsTextHtml(request) ? pathname : `${pathname}|no-html`;
|
|
517
|
+
return this.serveCached(request, keyPath, (fillRequest) => this.serveRequestFromStorage(fillRequest, pathname));
|
|
518
|
+
}
|
|
519
|
+
async serveRequestFromStorage(request, pathname) {
|
|
427
520
|
const serverConfig = await this.getServerConfig();
|
|
428
521
|
if (serverConfig == null) {
|
|
429
522
|
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