-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
RemixSite.ts
1508 lines (1339 loc) · 48.6 KB
/
RemixSite.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import chalk from "chalk";
import path from "path";
import url from "url";
import fs from "fs-extra";
import glob from "glob";
import crypto from "crypto";
import spawn from "cross-spawn";
import * as esbuild from "esbuild";
import indent from "indent-string";
import { createRequire } from "module";
const require = createRequire(import.meta.url);
import { Construct } from "constructs";
import {
Fn,
Duration,
CfnOutput,
RemovalPolicy,
CustomResource,
} from "aws-cdk-lib";
import * as s3 from "aws-cdk-lib/aws-s3";
import * as iam from "aws-cdk-lib/aws-iam";
import * as logs from "aws-cdk-lib/aws-logs";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as route53 from "aws-cdk-lib/aws-route53";
import * as s3Assets from "aws-cdk-lib/aws-s3-assets";
import * as cloudfront from "aws-cdk-lib/aws-cloudfront";
import * as acm from "aws-cdk-lib/aws-certificatemanager";
import { AwsCliLayer } from "aws-cdk-lib/lambda-layer-awscli";
import * as origins from "aws-cdk-lib/aws-cloudfront-origins";
import * as route53Targets from "aws-cdk-lib/aws-route53-targets";
import * as route53Patterns from "aws-cdk-lib/aws-route53-patterns";
import { getChildLogger } from "@serverless-stack/core";
const logger = getChildLogger("RemixSite");
import { App } from "./App.js";
import { Stack } from "./Stack.js";
import { SSTConstruct } from "./Construct.js";
import {
BaseSiteDomainProps,
BaseSiteReplaceProps,
BaseSiteCdkDistributionProps,
BaseSiteEnvironmentOutputsInfo,
getBuildCmdEnvironment,
buildErrorResponsesForRedirectToIndex,
} from "./BaseSite.js";
import { Permissions, attachPermissionsToRole } from "./util/permission.js";
import * as crossRegionHelper from "./nextjs-site/cross-region-helper.js";
const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
type RemixConfig = {
assetsBuildDirectory: string;
publicPath: string;
serverBuildPath: string;
serverBuildTarget: string;
server?: string;
};
export interface RemixDomainProps extends BaseSiteDomainProps {}
export interface RemixCdkDistributionProps
extends BaseSiteCdkDistributionProps {}
export interface RemixSiteProps {
cdk?: {
/**
* Pass in bucket information to override the default settings this
* construct uses to create the CDK Bucket internally.
*/
bucket?: s3.BucketProps;
/**
* Pass in a value to override the default settings this construct uses to
* create the CDK `Distribution` internally.
*/
distribution?: RemixCdkDistributionProps;
/**
* Override the default CloudFront cache policies created internally.
*/
cachePolicies?: {
/**
* Override the CloudFront cache policy properties for browser build files.
*/
buildCachePolicy?: cloudfront.ICachePolicy;
/**
* Override the CloudFront cache policy properties for "public" folder
* static files.
*
* Note: This will not include the browser build files, which have a seperate
* cache policy; @see `buildCachePolicy`.
*/
staticsCachePolicy?: cloudfront.ICachePolicy;
/**
* Override the CloudFront cache policy properties for responses from the
* server rendering Lambda.
*
* @note The default cache policy that is used in the abscene of this property
* is one that performs no caching of the server response.
*/
serverCachePolicy?: cloudfront.ICachePolicy;
};
};
/**
* The Remix app server is deployed to a Lambda function behind an API Gateway
* HTTP API. Alternatively, you can choose to deploy to Lambda@Edge.
*
* @default false
*/
edge?: boolean;
/**
* Path to the directory where the website source is located.
*/
path: string;
/**
* The customDomain for this website. SST supports domains that are hosted
* either on [Route 53](https://aws.amazon.com/route53/) or externally.
*
* Note that you can also migrate externally hosted domains to Route 53 by
* [following this guide](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/MigratingDNS.html).
*
* @example
* ```js {3}
* new RemixSite(stack, "RemixSite", {
* path: "path/to/site",
* customDomain: "domain.com",
* });
* ```
*
* ```js {3-6}
* new RemixSite(stack, "RemixSite", {
* path: "path/to/site",
* customDomain: {
* domainName: "domain.com",
* domainAlias: "www.domain.com",
* hostedZone: "domain.com"
* },
* });
* ```
*/
customDomain?: string | RemixDomainProps;
/**
* An object with the key being the environment variable name.
*
* @example
* ```js {3-6}
* new RemixSite(stack, "RemixSite", {
* path: "path/to/site",
* environment: {
* API_URL: api.url,
* USER_POOL_CLIENT: auth.cognitoUserPoolClient.userPoolClientId,
* },
* });
* ```
*/
environment?: Record<string, string>;
/**
* When running `sst start`, a placeholder site is deployed. This is to ensure
* that the site content remains unchanged, and subsequent `sst start` can
* start up quickly.
*
* @example
* ```js {3}
* new RemixSite(stack, "RemixSite", {
* path: "path/to/site",
* disablePlaceholder: true,
* });
* ```
*/
disablePlaceholder?: boolean;
defaults?: {
function?: {
timeout?: number;
memorySize?: number;
permissions?: Permissions;
};
};
/**
* While deploying, SST waits for the CloudFront cache invalidation process to finish. This ensures that the new content will be served once the deploy command finishes. However, this process can sometimes take more than 5 mins. For non-prod environments it might make sense to pass in `false`. That'll skip waiting for the cache to invalidate and speed up the deploy process.
*/
waitForInvalidation?: boolean;
}
/**
* The `RemixSite` construct is a higher level CDK construct that makes it easy to create a Remix app. It provides a simple way to build and deploy the site to an S3 bucket; setup a CloudFront CDN for fast content delivery; and configure a custom domain for the website URL.
*
* By default, the Remix app server is deployed to a Lambda function behind API Gateway HTTP API Lambda. Alternatively, you can choose to deploy to Lambda@Edge.
*
* In the case you have a centralized database, Edge locations are often far away from your database. If you are making multiple queries in your data loader, you might experience long latency.
*
* The browser build and public statics are backed by an S3 Bucket. CloudFront cache policies are configured, whilst also allowing for customization, and we include cache invalidation on deployment.
*
* It also enables you to [automatically set the environment variables](#configuring-environment-variables) for your Remix app directly from the outputs in your SST app.
*/
export class RemixSite extends Construct implements SSTConstruct {
/**
* The default CloudFront cache policy properties for browser build files.
*/
public static buildCachePolicyProps: cloudfront.CachePolicyProps = {
queryStringBehavior: cloudfront.CacheQueryStringBehavior.none(),
headerBehavior: cloudfront.CacheHeaderBehavior.none(),
cookieBehavior: cloudfront.CacheCookieBehavior.none(),
// The browser build file names all contain unique hashes based on their
// content, we can therefore aggressively cache them as we shouldn't hit
// unexpected collisions.
defaultTtl: Duration.days(365),
maxTtl: Duration.days(365),
minTtl: Duration.days(365),
enableAcceptEncodingBrotli: true,
enableAcceptEncodingGzip: true,
comment: "SST RemixSite Browser Build Default Cache Policy",
};
/**
* The default CloudFront cache policy properties for "public" folder
* static files.
*
* @note This policy is not applied to the browser build files; they have a seperate
* cache policy; @see `buildCachePolicyProps`.
*/
public static staticsCachePolicyProps: cloudfront.CachePolicyProps = {
queryStringBehavior: cloudfront.CacheQueryStringBehavior.none(),
headerBehavior: cloudfront.CacheHeaderBehavior.none(),
cookieBehavior: cloudfront.CacheCookieBehavior.none(),
defaultTtl: Duration.hours(1),
maxTtl: Duration.hours(1),
minTtl: Duration.hours(1),
enableAcceptEncodingBrotli: true,
enableAcceptEncodingGzip: true,
comment: "SST RemixSite Public Folder Default Cache Policy",
};
/**
* The default CloudFront cache policy properties for responses from the
* server rendering Lambda.
*
* @note By default no caching is performed on the server rendering Lambda response.
*/
public static serverCachePolicyProps: cloudfront.CachePolicyProps = {
queryStringBehavior: cloudfront.CacheQueryStringBehavior.all(),
headerBehavior: cloudfront.CacheHeaderBehavior.none(),
cookieBehavior: cloudfront.CacheCookieBehavior.all(),
defaultTtl: Duration.seconds(0),
maxTtl: Duration.days(365),
minTtl: Duration.seconds(0),
enableAcceptEncodingBrotli: true,
enableAcceptEncodingGzip: true,
comment: "SST RemixSite Server Response Default Cache Policy",
};
/**
* Exposes CDK instances created within the construct.
*/
public readonly cdk: {
/**
* The internally created CDK `Bucket` instance.
*/
bucket: s3.Bucket;
/**
* The internally created CDK `Distribution` instance.
*/
distribution: cloudfront.Distribution;
/**
* The Route 53 hosted zone for the custom domain.
*/
hostedZone?: route53.IHostedZone;
/**
* The AWS Certificate Manager certificate for the custom domain.
*/
certificate?: acm.ICertificate;
};
private props: RemixSiteProps;
/**
* Determines if a placeholder site should be deployed instead. We will set
* this to `true` by default when performing local development, although the
* user can choose to override this value.
*/
private isPlaceholder: boolean;
/**
* The root SST directory used for builds.
*/
private sstBuildDir: string;
/**
* The remix site config. It contains user configuration overrides which we
* will need to consider when resolving Remix's build output.
*/
private remixConfig: RemixConfig;
private serverLambdaRole: iam.Role;
private serverLambdaForEdge?: lambda.IVersion;
private serverLambdaForRegional?: lambda.Function;
private awsCliLayer: AwsCliLayer;
constructor(scope: Construct, id: string, props: RemixSiteProps) {
super(scope, id);
const app = scope.node.root as App;
try {
this.isPlaceholder =
(app.local || app.skipBuild) && !props.disablePlaceholder;
this.sstBuildDir = app.buildDir;
this.props = props;
this.cdk = {} as any;
this.awsCliLayer = new AwsCliLayer(this, "AwsCliLayer");
this.registerSiteEnvironment();
// Prepare app
if (this.isPlaceholder) {
// Minimal configuration for the placeholder site
this.remixConfig = {} as any;
} else {
this.remixConfig = this.readRemixConfig();
this.buildApp();
}
// Create Bucket which will be utilised to contain the statics
this.cdk.bucket = this.createS3Bucket();
// Create Server functions
if (props.edge) {
const bundlePath = this.isPlaceholder
? this.createServerLambdaBundleWithStub()
: this.createServerLambdaBundleForEdge();
this.serverLambdaRole = this.createServerFunctionRoleForEdge();
this.serverLambdaForEdge = this.createServerFunctionForEdge(bundlePath);
}
else {
const bundlePath = this.isPlaceholder
? this.createServerLambdaBundleWithStub()
: this.createServerLambdaBundleForRegional();
this.serverLambdaRole = this.createServerFunctionRoleForRegional();
this.serverLambdaForRegional = this.createServerFunctionForRegional(bundlePath);
}
// Create Custom Domain
this.validateCustomDomainSettings();
this.cdk.hostedZone = this.lookupHostedZone();
this.cdk.certificate = this.createCertificate();
// Create S3 Deployment
const assets = this.isPlaceholder
? this.createStaticsS3AssetsWithStub()
: this.createStaticsS3Assets();
const s3deployCR = this.createS3Deployment(assets);
// Create CloudFront
this.validateCloudFrontDistributionSettings();
if (props.edge) {
this.cdk.distribution = this.isPlaceholder
? this.createCloudFrontDistributionForStub()
: this.createCloudFrontDistributionForEdge();
}
else {
this.cdk.distribution = this.isPlaceholder
? this.createCloudFrontDistributionForStub()
: this.createCloudFrontDistributionForRegional();
}
this.cdk.distribution.node.addDependency(s3deployCR);
// Invalidate CloudFront
const invalidationCR = this.createCloudFrontInvalidation();
invalidationCR.node.addDependency(this.cdk.distribution);
// Connect Custom Domain to CloudFront Distribution
this.createRoute53Records();
} catch (error) {
// If running an SST test then re-throw the error so that it can be
// tested
if (app.isRunningSSTTest()) {
throw error;
}
console.error(
chalk.red(
`\nError: There was a problem synthesizing the RemixSite at "${props.path}".`
)
);
if (error instanceof Error) {
if (error.stack) {
console.error(chalk.red(indent(`\n${error.stack}`, 2)));
} else if (error.message) {
console.error(chalk.bold.red(indent(`\n${error.message}`, 2)));
} else {
console.error(chalk.bold.red(indent("\nAn unknown error occurred")));
}
}
process.exit(1);
}
}
/////////////////////
// Public Properties
/////////////////////
/**
* The CloudFront URL of the website.
*/
public get url(): string {
return `https://${this.cdk.distribution.distributionDomainName}`;
}
/**
* If the custom domain is enabled, this is the URL of the website with the
* custom domain.
*/
public get customDomainUrl(): string | undefined {
const { customDomain } = this.props;
if (!customDomain) {
return;
}
if (typeof customDomain === "string") {
return `https://${customDomain}`;
} else {
return `https://${customDomain.domainName}`;
}
}
/**
* The ARN of the internally created S3 Bucket.
*/
public get bucketArn(): string {
return this.cdk.bucket.bucketArn;
}
/**
* The name of the internally created S3 Bucket.
*/
public get bucketName(): string {
return this.cdk.bucket.bucketName;
}
/**
* The ID of the internally created CloudFront Distribution.
*/
public get distributionId(): string {
return this.cdk.distribution.distributionId;
}
/**
* The domain name of the internally created CloudFront Distribution.
*/
public get distributionDomain(): string {
return this.cdk.distribution.distributionDomainName;
}
/////////////////////
// Public Methods
/////////////////////
/**
* Attaches the given list of permissions to allow the Remix server side
* rendering to access other AWS resources.
*
* @example
* ### Attaching permissions
*
* ```js {5}
* const site = new RemixSite(stack, "Site", {
* path: "path/to/site",
* });
*
* site.attachPermissions(["sns"]);
* ```
*/
public attachPermissions(permissions: Permissions): void {
attachPermissionsToRole(this.serverLambdaRole, permissions);
}
public getConstructMetadata() {
return {
type: "RemixSite" as const,
data: {
distributionId: this.cdk.distribution.distributionId,
customDomainUrl: this.customDomainUrl,
},
};
}
/////////////////////
// Build App
/////////////////////
private buildApp() {
// Build
const app = this.node.root as App;
if (!app.isRunningSSTTest()) {
this.runNpmBuild();
}
// Validate build output exists
const serverBuildFile = path.join(
this.props.path,
this.remixConfig.serverBuildPath
);
if (!fs.existsSync(serverBuildFile)) {
throw new Error(
`No server build output found at "${serverBuildFile}"`
);
}
}
private runNpmBuild() {
// Given that Remix apps tend to involve concatenation of other commands
// such as Tailwind compilation, we feel that it is safest to target the
// "build" script for the app in order to ensure all outputs are generated.
const { path: sitePath } = this.props;
// validate site path exists
if (!fs.existsSync(sitePath)) {
throw new Error(`No path found at "${path.resolve(sitePath)}"`);
}
// Ensure that the site has a build script defined
if (!fs.existsSync(path.join(sitePath, "package.json"))) {
throw new Error(`No package.json found at "${sitePath}".`);
}
const packageJson = fs.readJsonSync(path.join(sitePath, "package.json"));
if (!packageJson.scripts || !packageJson.scripts.build) {
throw new Error(
`No "build" script found within package.json in "${sitePath}".`
);
}
// Run build
logger.debug(`Running "npm build" script`);
const buildResult = spawn.sync("npm", ["run", "build"], {
cwd: sitePath,
stdio: "inherit",
env: {
...process.env,
...getBuildCmdEnvironment(this.props.environment),
},
});
if (buildResult.status !== 0) {
throw new Error('The app "build" script failed.');
}
}
/////////////////////
// Bundle S3 Assets
/////////////////////
private createStaticsS3Assets(): s3Assets.Asset[] {
const app = this.node.root as App;
const fileSizeLimit = app.isRunningSSTTest()
? // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: "sstTestFileSizeLimitOverride" not exposed in props
this.props.sstTestFileSizeLimitOverride || 200
: 200;
// First we need to create zip files containing the statics
const script = path.resolve(__dirname, "../assets/BaseSite/archiver.cjs");
const zipOutDir = path.resolve(
path.join(this.sstBuildDir, `RemixSite-${this.node.id}-${this.node.addr}`)
);
// Remove zip dir to ensure no partX.zip remain from previous build
fs.removeSync(zipOutDir);
const result = spawn.sync(
"node",
[
script,
path.join(this.props.path, "public"),
zipOutDir,
`${fileSizeLimit}`,
],
{
stdio: "inherit",
}
);
if (result.status !== 0) {
throw new Error(`There was a problem generating the assets package.`);
}
// Create S3 Assets for each zip file
const assets = [];
for (let partId = 0; ; partId++) {
const zipFilePath = path.join(zipOutDir, `part${partId}.zip`);
if (!fs.existsSync(zipFilePath)) {
break;
}
assets.push(
new s3Assets.Asset(this, `Asset${partId}`, {
path: zipFilePath,
})
);
}
return assets;
}
private createStaticsS3AssetsWithStub(): s3Assets.Asset[] {
return [
new s3Assets.Asset(this, "Asset", {
path: path.resolve(__dirname, "../assets/RemixSite/site-sub"),
}),
];
}
private createS3Bucket(): s3.Bucket {
const { cdk } = this.props;
return new s3.Bucket(this, "S3Bucket", {
publicReadAccess: true,
autoDeleteObjects: true,
removalPolicy: RemovalPolicy.DESTROY,
...cdk?.bucket,
});
}
private createS3Deployment(assets: s3Assets.Asset[]): CustomResource {
// Create a Lambda function that will be doing the uploading
const uploader = new lambda.Function(this, "S3Uploader", {
code: lambda.Code.fromAsset(
path.join(__dirname, "../assets/BaseSite/custom-resource")
),
layers: [this.awsCliLayer],
runtime: lambda.Runtime.PYTHON_3_7,
handler: "s3-upload.handler",
timeout: Duration.minutes(15),
memorySize: 1024,
});
this.cdk.bucket.grantReadWrite(uploader);
assets.forEach((asset) =>
asset.grantRead(uploader)
);
// Create the custom resource function
const handler = new lambda.Function(this, "S3Handler", {
code: lambda.Code.fromAsset(
path.join(__dirname, "../assets/BaseSite/custom-resource")
),
layers: [this.awsCliLayer],
runtime: lambda.Runtime.PYTHON_3_7,
handler: "s3-handler.handler",
timeout: Duration.minutes(15),
memorySize: 1024,
environment: {
UPLOADER_FUNCTION_NAME: uploader.functionName,
},
});
this.cdk.bucket.grantReadWrite(handler);
uploader.grantInvoke(handler);
// Build file options
const fileOptions = [];
const publicPath = path.join(this.props.path, "public");
for (const item of fs.readdirSync(publicPath)) {
if (item === "build") {
fileOptions.push({
exclude: "*",
include: "build/*",
cacheControl: "public,max-age=31536000,immutable",
});
} else {
const itemPath = path.join(publicPath, item);
fileOptions.push({
exclude: "*",
include: fs.statSync(itemPath).isDirectory()
? `${item}/*`
: `${item}`,
cacheControl: "public,max-age=3600,must-revalidate",
});
}
}
// Create custom resource
return new CustomResource(this, "S3Deployment", {
serviceToken: handler.functionArn,
resourceType: "Custom::SSTBucketDeployment",
properties: {
Sources: assets.map((asset) => ({
BucketName: asset.s3BucketName,
ObjectKey: asset.s3ObjectKey,
})),
DestinationBucketName: this.cdk.bucket.bucketName,
FileOptions: (fileOptions || []).map(
({ exclude, include, cacheControl }) => {
return [
"--exclude",
exclude,
"--include",
include,
"--cache-control",
cacheControl,
];
}
),
},
});
}
/////////////////////
// Bundle Lambda Server
/////////////////////
private createServerLambdaBundleForRegional(): string {
const templatePath = path.resolve(
__dirname,
"../assets/RemixSite/server-lambda/regional-server.js"
);
return this.createServerLambdaBundle(templatePath);
}
private createServerLambdaBundleForEdge(): string {
const templatePath = path.resolve(
__dirname,
"../assets/RemixSite/server-lambda/edge-server.js"
);
return this.createServerLambdaBundle(templatePath);
}
private createServerLambdaBundle(templatePath: string): string {
// Create a Lambda@Edge handler for the Remix server bundle.
//
// Note: Remix does perform their own internal ESBuild process, but it
// doesn't bundle 3rd party dependencies by default. In the interest of
// keeping deployments seamless for users we will create a server bundle
// with all dependencies included. We will still need to consider how to
// address any need for external dependencies, although I think we should
// possibly consider this at a later date.
let serverPath: string;
if (this.remixConfig.server != null) {
// In this path we are using a user-specified server. We'll assume
// that they have built an appropriate CloudFront Lambda@Edge handler
// for the Remix "core server build".
//
// The Remix compiler will have bundled their server implementation into
// the server build ouput path. We therefore need to reference the
// serverBuildPath from the remix.config.js to determine our server build
// entry.
//
// Supporting this customisation of the server supports two cases:
// 1. It enables power users to override our own implementation with an
// implementation that meets their specific needs.
// 2. It provides us with the required stepping stone to enable a
// "Serverless Stack" template within the Remix repository (we would
// still need to reach out to the Remix team for this).
serverPath = this.remixConfig.serverBuildPath;
} else {
// In this path we are assuming that the Remix build only outputs the
// "core server build". We can safely assume this as we have guarded the
// remix.config.js to ensure it matches our expectations for the build
// configuration.
// We need to ensure that the "core server build" is wrapped with an
// appropriate Lambda@Edge handler. We will utilise an internal asset
// template to create this wrapper within the "core server build" output
// directory.
logger.debug(`Creating Lambda@Edge handler for server`);
// Resolve the path to create the server lambda handler at.
serverPath = path.join(this.props.path, "build/server.js");
// Write the server lambda
fs.copyFileSync(templatePath, serverPath);
}
logger.debug(`Bundling server`);
// Create a directory that we will use to create the bundled version
// of the "core server build" along with our custom Lamba@Edge handler.
const outputPath = path.resolve(
path.join(this.sstBuildDir, `RemixSiteLambdaServer-${this.node.id}-${this.node.addr}`)
);
const result = esbuild.buildSync({
entryPoints: [serverPath],
bundle: true,
target: "node16",
platform: "node",
external: ["aws-sdk"],
outfile: path.join(outputPath, "server.js"),
// Need to add the --ignore-annotations flag to ESBuild. It appears Remix templates by default include the "sideEffects": false, flag in their package.json. This causes ESBuild to remove the required polyfill module. I had removed the flag so it was working fine for me, but likely we will want to avoid having everyone update their Remix app like this. Remix includes polyfills so it is always going to be by nature with side effects. I've asked on their GH the reasoning for the flag being there in the first place. There is also an active PR to remove the need for this flag in their package.json, although the PR doesn't provide the original motivation for the flag being there. I will do more research and get back to ya'll. For sure we will want to address this. https://esbuild.github.io/api/#ignore-annotations
ignoreAnnotations: true,
})
if (result.errors.length > 0) {
result.errors.forEach((error) => console.error(error));
throw new Error(`There was a problem bundling the server.`);
}
return outputPath;
}
private createServerLambdaBundleWithStub(): string {
// Use existing stub bundle in assets
return path.resolve(__dirname, "../assets/RemixSite/server-lambda-stub");
}
private createServerFunctionRoleForRegional(): iam.Role {
return this.createServerFunctionRole([
"lambda.amazonaws.com",
]);
}
private createServerFunctionRoleForEdge(): iam.Role {
return this.createServerFunctionRole([
"lambda.amazonaws.com",
"edgelambda.amazonaws.com",
]);
}
private createServerFunctionRole(principals: string[]): iam.Role {
const { defaults } = this.props;
// Create function role
const role = new iam.Role(this, `ServerLambdaRole`, {
assumedBy: new iam.CompositePrincipal(
...principals.map((principal) => new iam.ServicePrincipal(principal))
),
managedPolicies: [
iam.ManagedPolicy.fromManagedPolicyArn(
this,
"EdgeLambdaPolicy",
"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
),
],
});
// Attach permission
this.cdk.bucket.grantReadWrite(role);
if (defaults?.function?.permissions) {
attachPermissionsToRole(role, defaults.function.permissions);
}
return role;
}
private createServerFunctionForRegional(bundlePath: string): lambda.Function {
const { defaults, environment } = this.props;
return new lambda.Function(this, `ServerFunction`, {
description: "Server handler for Remix",
handler: "server.handler",
currentVersionOptions: {
removalPolicy: RemovalPolicy.DESTROY,
},
logRetention: logs.RetentionDays.THREE_DAYS,
code: lambda.Code.fromAsset(bundlePath),
runtime: lambda.Runtime.NODEJS_16_X,
memorySize: defaults?.function?.memorySize || 512,
timeout: Duration.seconds(defaults?.function?.timeout || 10),
role: this.serverLambdaRole,
environment,
});
}
private createServerFunctionForEdge(bundlePath: string): lambda.IVersion {
const name = "Server";
// Create function asset
const asset = new s3Assets.Asset(this, `ServerFunctionAsset`, {
path: bundlePath,
});
// Create function based on region
const root = this.node.root as App;
return root.region === "us-east-1"
? this.createServerFunctionInUE1(name, asset, bundlePath)
: this.createServerFunctionInNonUE1(name, asset, bundlePath);
}
private createServerFunctionInUE1(
name: string,
asset: s3Assets.Asset,
assetPath: string
): lambda.IVersion {
const { defaults } = this.props;
// Create function
const fn = new lambda.Function(this, `${name}Function`, {
description: `${name} handler for Remix`,
handler: "server.handler",
currentVersionOptions: {
removalPolicy: RemovalPolicy.DESTROY,
},
logRetention: logs.RetentionDays.THREE_DAYS,
code: lambda.Code.fromAsset(assetPath),
runtime: lambda.Runtime.NODEJS_16_X,
memorySize: defaults?.function?.memorySize || 512,
timeout: Duration.seconds(defaults?.function?.timeout || 10),
role: this.serverLambdaRole,
});
// Deploy after the code is updated
if (!this.isPlaceholder) {
const updaterCR = this.createLambdaCodeReplacer(name, asset);
fn.node.addDependency(updaterCR);
}
return fn.currentVersion;
}
private createServerFunctionInNonUE1(
name: string,
asset: s3Assets.Asset,
_assetPath: string
): lambda.IVersion {
const { defaults } = this.props;
// If app region is NOT us-east-1, create a Function in us-east-1
// using a Custom Resource
// Create a S3 bucket in us-east-1 to store Lambda code. Create
// 1 bucket for all Edge functions.
const bucketCR = crossRegionHelper.getOrCreateBucket(this);
const bucketName = bucketCR.getAttString("BucketName");
// Create a Lambda function in us-east-1
const functionCR = crossRegionHelper.createFunction(
this,
name,
this.serverLambdaRole,
bucketName,
{
Description: `${name} handler for Remix`,
Handler: "server.handler",
Code: {
S3Bucket: asset.s3BucketName,
S3Key: asset.s3ObjectKey,
},
Runtime: lambda.Runtime.NODEJS_16_X.name,
MemorySize: defaults?.function?.memorySize || 512,
Timeout: Duration.seconds(
defaults?.function?.timeout || 10
).toSeconds(),
Role: this.serverLambdaRole.roleArn,
}
);
const functionArn = functionCR.getAttString("FunctionArn");
// Create a Lambda function version in us-east-1
const versionCR = crossRegionHelper.createVersion(this, name, functionArn);
const versionId = versionCR.getAttString("Version");
crossRegionHelper.updateVersionLogicalId(functionCR, versionCR);
// Deploy after the code is updated
if (!this.isPlaceholder) {
const updaterCR = this.createLambdaCodeReplacer(name, asset);
functionCR.node.addDependency(updaterCR);
}
return lambda.Version.fromVersionArn(
this,
`${name}FunctionVersion`,
`${functionArn}:${versionId}`
);
}
private createLambdaCodeReplacer(
name: string,
asset: s3Assets.Asset
): CustomResource {
// Note: Source code for the Lambda functions have "{{ ENV_KEY }}" in them.
// They need to be replaced with real values before the Lambda
// functions get deployed.
const providerId = "LambdaCodeReplacerProvider";
const resId = `${name}LambdaCodeReplacer`;
const stack = Stack.of(this);
let provider = stack.node.tryFindChild(providerId) as lambda.Function;
// Create provider if not already created
if (!provider) {
provider = new lambda.Function(stack, providerId, {
code: lambda.Code.fromAsset(
// TODO: Move this file into a shared folder
// This references a Nextjs directory, but the underlying
// code appears to be generic enough to utilise in this case.
path.join(__dirname, "../assets/NextjsSite/custom-resource")
),
layers: [this.awsCliLayer],
runtime: lambda.Runtime.PYTHON_3_7,
handler: "lambda-code-updater.handler",
timeout: Duration.minutes(15),
memorySize: 1024,
});
}
// Allow provider to perform search/replace on the asset
provider.role?.addToPrincipalPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["s3:*"],
resources: [`arn:aws:s3:::${asset.s3BucketName}/${asset.s3ObjectKey}`],
})
);
// Create custom resource
const resource = new CustomResource(this, resId, {