This repository has been archived by the owner on Jan 28, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 463
/
Copy pathindex.ts
434 lines (394 loc) · 15.9 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import * as cdk from "@aws-cdk/core";
import * as lambda from "@aws-cdk/aws-lambda";
import * as s3 from "@aws-cdk/aws-s3";
import * as logs from "@aws-cdk/aws-logs";
import * as s3Deploy from "@aws-cdk/aws-s3-deployment";
import * as cloudfront from "@aws-cdk/aws-cloudfront";
import * as origins from "@aws-cdk/aws-cloudfront-origins";
import { ARecord, RecordTarget } from "@aws-cdk/aws-route53";
import {
OriginRequestImageHandlerManifest,
OriginRequestApiHandlerManifest,
OriginRequestDefaultHandlerManifest,
RoutesManifest
} from "@sls-next/lambda-at-edge";
import * as fs from "fs-extra";
import * as path from "path";
import {
Role,
ManagedPolicy,
ServicePrincipal,
CompositePrincipal
} from "@aws-cdk/aws-iam";
import { Duration, RemovalPolicy } from "@aws-cdk/core";
import { CloudFrontTarget } from "@aws-cdk/aws-route53-targets";
import { OriginRequestQueryStringBehavior } from "@aws-cdk/aws-cloudfront";
import { Props } from "./props";
import { toLambdaOption } from "./utils/toLambdaOption";
import { readAssetsDirectory } from "./utils/readAssetsDirectory";
import { readInvalidationPathsFromManifest } from "./utils/readInvalidationPathsFromManifest";
import { reduceInvalidationPaths } from "./utils/reduceInvalidationPaths";
export * from "./props";
export class NextJSLambdaEdge extends cdk.Construct {
private routesManifest: RoutesManifest | null;
private apiBuildManifest: OriginRequestApiHandlerManifest | null;
private imageManifest: OriginRequestImageHandlerManifest | null;
private defaultManifest: OriginRequestDefaultHandlerManifest;
public distribution: cloudfront.Distribution;
public bucket: s3.Bucket;
public edgeLambdaRole: Role;
public defaultNextLambda: lambda.Function;
public nextApiLambda: lambda.Function | null;
public nextImageLambda: lambda.Function | null;
public nextStaticsCachePolicy: cloudfront.CachePolicy;
public nextImageCachePolicy: cloudfront.CachePolicy;
public nextLambdaCachePolicy: cloudfront.CachePolicy;
public aRecord?: ARecord;
constructor(scope: cdk.Construct, id: string, private props: Props) {
super(scope, id);
this.apiBuildManifest = this.readApiBuildManifest();
this.routesManifest = this.readRoutesManifest();
this.imageManifest = this.readImageBuildManifest();
this.defaultManifest = this.readDefaultManifest();
this.bucket = new s3.Bucket(this, "PublicAssets", {
publicReadAccess: true,
// Given this resource is created internally and also should only contain
// assets uploaded by this library we should be able to safely delete all
// contents along with the bucket its self upon stack deletion.
autoDeleteObjects: true,
removalPolicy: cdk.RemovalPolicy.DESTROY,
// Override props.
...(props.s3Props || {})
});
this.edgeLambdaRole = new Role(this, "NextEdgeLambdaRole", {
assumedBy: new CompositePrincipal(
new ServicePrincipal("lambda.amazonaws.com"),
new ServicePrincipal("edgelambda.amazonaws.com")
),
managedPolicies: [
ManagedPolicy.fromManagedPolicyArn(
this,
"NextApiLambdaPolicy",
"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
)
]
});
this.defaultNextLambda = new lambda.Function(this, "NextLambda", {
functionName: toLambdaOption("defaultLambda", props.name),
description: `Default Lambda@Edge for Next CloudFront distribution`,
handler: "index.handler",
currentVersionOptions: {
removalPolicy: RemovalPolicy.DESTROY // destroy old versions
},
logRetention: logs.RetentionDays.THREE_DAYS,
code: lambda.Code.fromAsset(
path.join(this.props.serverlessBuildOutDir, "default-lambda")
),
role: this.edgeLambdaRole,
runtime:
toLambdaOption("defaultLambda", props.runtime) ||
lambda.Runtime.NODEJS_12_X,
memorySize: toLambdaOption("defaultLambda", props.memory),
timeout: toLambdaOption("defaultLambda", props.timeout)
});
this.defaultNextLambda.currentVersion.addAlias("live");
const apis = this.apiBuildManifest?.apis;
const hasAPIPages =
apis &&
(Object.keys(apis.nonDynamic).length > 0 ||
Object.keys(apis.dynamic).length > 0);
this.nextApiLambda = null;
if (hasAPIPages) {
this.nextApiLambda = new lambda.Function(this, "NextApiLambda", {
functionName: toLambdaOption("apiLambda", props.name),
description: `Default Lambda@Edge for Next API CloudFront distribution`,
handler: "index.handler",
currentVersionOptions: {
removalPolicy: RemovalPolicy.DESTROY, // destroy old versions
retryAttempts: 1 // async retry attempts
},
logRetention: logs.RetentionDays.THREE_DAYS,
code: lambda.Code.fromAsset(
path.join(this.props.serverlessBuildOutDir, "api-lambda")
),
role: this.edgeLambdaRole,
runtime:
toLambdaOption("apiLambda", props.runtime) ||
lambda.Runtime.NODEJS_12_X,
memorySize: toLambdaOption("apiLambda", props.memory),
timeout: toLambdaOption("apiLambda", props.timeout)
});
this.nextApiLambda.currentVersion.addAlias("live");
}
this.nextImageLambda = null;
if (this.imageManifest) {
this.nextImageLambda = new lambda.Function(this, "NextImageLambda", {
functionName: toLambdaOption("imageLambda", props.name),
description: `Default Lambda@Edge for Next Image CloudFront distribution`,
handler: "index.handler",
currentVersionOptions: {
removalPolicy: RemovalPolicy.DESTROY, // destroy old versions
retryAttempts: 1 // async retry attempts
},
logRetention: logs.RetentionDays.THREE_DAYS,
code: lambda.Code.fromAsset(
path.join(this.props.serverlessBuildOutDir, "image-lambda")
),
role: this.edgeLambdaRole,
runtime:
toLambdaOption("imageLambda", props.runtime) ||
lambda.Runtime.NODEJS_12_X,
memorySize: toLambdaOption("imageLambda", props.memory),
timeout: toLambdaOption("imageLambda", props.timeout)
});
this.nextImageLambda.currentVersion.addAlias("live");
}
this.nextStaticsCachePolicy = new cloudfront.CachePolicy(
this,
"NextStaticsCache",
{
cachePolicyName: props.cachePolicyName?.staticsCache,
queryStringBehavior: cloudfront.CacheQueryStringBehavior.none(),
headerBehavior: cloudfront.CacheHeaderBehavior.none(),
cookieBehavior: cloudfront.CacheCookieBehavior.none(),
defaultTtl: Duration.days(30),
maxTtl: Duration.days(30),
minTtl: Duration.days(30),
enableAcceptEncodingBrotli: true,
enableAcceptEncodingGzip: true
}
);
this.nextImageCachePolicy = new cloudfront.CachePolicy(
this,
"NextImageCache",
{
cachePolicyName: props.cachePolicyName?.imageCache,
queryStringBehavior: cloudfront.CacheQueryStringBehavior.all(),
headerBehavior: cloudfront.CacheHeaderBehavior.allowList("Accept"),
cookieBehavior: cloudfront.CacheCookieBehavior.none(),
defaultTtl: Duration.days(1),
maxTtl: Duration.days(365),
minTtl: Duration.days(0),
enableAcceptEncodingBrotli: true,
enableAcceptEncodingGzip: true
}
);
this.nextLambdaCachePolicy = new cloudfront.CachePolicy(
this,
"NextLambdaCache",
{
cachePolicyName: props.cachePolicyName?.lambdaCache,
queryStringBehavior: cloudfront.CacheQueryStringBehavior.all(),
headerBehavior: cloudfront.CacheHeaderBehavior.none(),
cookieBehavior: {
behavior: props.whiteListedCookies?.length ? "whitelist" : "all",
cookies: props.whiteListedCookies
},
defaultTtl: Duration.seconds(0),
maxTtl: Duration.days(365),
minTtl: Duration.seconds(0),
enableAcceptEncodingBrotli: true,
enableAcceptEncodingGzip: true
}
);
const edgeLambdas = [
{
includeBody: true,
eventType: cloudfront.LambdaEdgeEventType.ORIGIN_REQUEST,
functionVersion: this.defaultNextLambda.currentVersion
},
{
eventType: cloudfront.LambdaEdgeEventType.ORIGIN_RESPONSE,
functionVersion: this.defaultNextLambda.currentVersion
}
];
this.distribution = new cloudfront.Distribution(
this,
"NextJSDistribution",
{
enableLogging: props.withLogging ? true : undefined,
certificate: props.domain?.certificate,
domainNames: props.domain ? props.domain.domainNames : undefined,
defaultRootObject: "",
defaultBehavior: {
viewerProtocolPolicy:
cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
origin: new origins.S3Origin(this.bucket),
allowedMethods: cloudfront.AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
cachedMethods: cloudfront.CachedMethods.CACHE_GET_HEAD_OPTIONS,
compress: true,
cachePolicy: this.nextLambdaCachePolicy,
edgeLambdas,
...(props.defaultBehavior || {})
},
additionalBehaviors: {
...(this.nextImageLambda
? {
[this.pathPattern("_next/image*")]: {
viewerProtocolPolicy:
cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
origin: new origins.S3Origin(this.bucket),
allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
cachedMethods:
cloudfront.CachedMethods.CACHE_GET_HEAD_OPTIONS,
compress: true,
cachePolicy: this.nextImageCachePolicy,
originRequestPolicy: new cloudfront.OriginRequestPolicy(
this,
"ImageOriginRequest",
{
queryStringBehavior: OriginRequestQueryStringBehavior.all()
}
),
edgeLambdas: [
{
eventType: cloudfront.LambdaEdgeEventType.ORIGIN_REQUEST,
functionVersion: this.nextImageLambda.currentVersion
}
]
}
}
: {}),
[this.pathPattern("_next/data/*")]: {
viewerProtocolPolicy:
cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
origin: new origins.S3Origin(this.bucket),
allowedMethods: cloudfront.AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
cachedMethods: cloudfront.CachedMethods.CACHE_GET_HEAD_OPTIONS,
compress: true,
cachePolicy: this.nextLambdaCachePolicy,
edgeLambdas
},
[this.pathPattern("_next/*")]: {
viewerProtocolPolicy:
cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
origin: new origins.S3Origin(this.bucket),
allowedMethods: cloudfront.AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
cachedMethods: cloudfront.CachedMethods.CACHE_GET_HEAD_OPTIONS,
compress: true,
cachePolicy: this.nextStaticsCachePolicy
},
[this.pathPattern("static/*")]: {
viewerProtocolPolicy:
cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
origin: new origins.S3Origin(this.bucket),
allowedMethods: cloudfront.AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
cachedMethods: cloudfront.CachedMethods.CACHE_GET_HEAD_OPTIONS,
compress: true,
cachePolicy: this.nextStaticsCachePolicy
},
...(this.nextApiLambda
? {
[this.pathPattern("api/*")]: {
viewerProtocolPolicy:
cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
origin: new origins.S3Origin(this.bucket),
allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
cachedMethods:
cloudfront.CachedMethods.CACHE_GET_HEAD_OPTIONS,
compress: true,
cachePolicy: this.nextLambdaCachePolicy,
edgeLambdas: [
{
includeBody: true,
eventType: cloudfront.LambdaEdgeEventType.ORIGIN_REQUEST,
functionVersion: this.nextApiLambda.currentVersion
}
]
}
}
: {}),
...(props.behaviours || {})
}
}
);
const assetsDirectory = path.join(props.serverlessBuildOutDir, "assets");
const assets = readAssetsDirectory({ assetsDirectory });
// This `BucketDeployment` deploys just the BUILD_ID file. We don't actually
// use the BUILD_ID file at runtime, however in this case we use it as a
// file to allow us to create an invalidation of all the routes as evaluated
// in the function `readInvalidationPathsFromManifest`.
new s3Deploy.BucketDeployment(this, `AssetDeploymentBuildID`, {
destinationBucket: this.bucket,
sources: [
s3Deploy.Source.asset(assetsDirectory, { exclude: ["**", "!BUILD_ID"] })
],
// This will actually cause the file to exist at BUILD_ID, we do this so
// that the prune will only prune /BUILD_ID/*, rather than all files fromm
// the root upwards.
destinationKeyPrefix: "/BUILD_ID",
distribution: this.distribution,
distributionPaths:
props.invalidationPaths ||
reduceInvalidationPaths(
readInvalidationPathsFromManifest(this.defaultManifest)
)
});
Object.keys(assets).forEach((key) => {
const { path: assetPath, cacheControl } = assets[key];
new s3Deploy.BucketDeployment(this, `AssetDeployment_${key}`, {
destinationBucket: this.bucket,
sources: [s3Deploy.Source.asset(assetPath)],
cacheControl: [s3Deploy.CacheControl.fromString(cacheControl)],
// The source contents will be unzipped to and loaded into the S3 bucket
// at the root '/', we don't want this, we want to maintain the same
// path on S3 as their local path.
destinationKeyPrefix: path.relative(assetsDirectory, assetPath),
// Source directories are uploaded with `--sync` this means that any
// files that don't exist in the source directory, but do in the S3
// bucket, will be removed.
prune: true
});
});
if (props.domain) {
props.domain.domainNames.forEach((domainName, index) => {
this.aRecord = new ARecord(this, `AliasRecord_${index}`, {
recordName: domainName,
zone: props.domain!.hostedZone, // not sure why ! is needed here
target: RecordTarget.fromAlias(
new CloudFrontTarget(this.distribution)
)
});
});
}
}
private pathPattern(pattern: string): string {
const { basePath } = this.routesManifest || {};
return basePath && basePath.length > 0
? `${basePath.slice(1)}/${pattern}`
: pattern;
}
private readRoutesManifest(): RoutesManifest {
return fs.readJSONSync(
path.join(
this.props.serverlessBuildOutDir,
"default-lambda/routes-manifest.json"
)
);
}
private readDefaultManifest(): OriginRequestDefaultHandlerManifest {
return fs.readJSONSync(
path.join(
this.props.serverlessBuildOutDir,
"default-lambda/manifest.json"
)
);
}
private readApiBuildManifest(): OriginRequestApiHandlerManifest | null {
const apiPath = path.join(
this.props.serverlessBuildOutDir,
"api-lambda/manifest.json"
);
if (!fs.existsSync(apiPath)) return null;
return fs.readJsonSync(apiPath);
}
private readImageBuildManifest(): OriginRequestImageHandlerManifest | null {
const imageLambdaPath = path.join(
this.props.serverlessBuildOutDir,
"image-lambda/manifest.json"
);
return fs.existsSync(imageLambdaPath)
? fs.readJSONSync(imageLambdaPath)
: null;
}
}