-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathFunction.ts
1562 lines (1472 loc) · 42.4 KB
/
Function.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
/* eslint-disable @typescript-eslint/ban-types */
// Note: disabling ban-type rule so we don't get an error referencing the class Function
import path from "path";
import type { Loader, BuildOptions } from "esbuild";
import { Construct } from "constructs";
import fs from "fs/promises";
import zlib from "zlib";
import { App } from "./App.js";
import { Stack } from "./Stack.js";
import { Job } from "./Job.js";
import { Secret } from "./Config.js";
import { SSTConstruct, isSSTConstruct } from "./Construct.js";
import { Size, toCdkSize } from "./util/size.js";
import { Duration, toCdkDuration } from "./util/duration.js";
import {
BindingResource,
BindingProps,
getBindingEnvironments,
getBindingPermissions,
getBindingReferencedSecrets,
} from "./util/binding.js";
import { Permissions, attachPermissionsToRole } from "./util/permission.js";
import * as functionUrlCors from "./util/functionUrlCors.js";
import url from "url";
import { useDeferredTasks } from "./deferred_task.js";
import { useProject } from "../project.js";
import { VisibleError } from "../error.js";
import { useRuntimeHandlers } from "../runtime/handlers.js";
import { createAppContext } from "./context.js";
import { useWarning } from "./util/warning.js";
import {
Architecture,
AssetCode,
CfnFunction,
Code,
Function as CDKFunction,
FunctionOptions,
FunctionUrl,
FunctionUrlAuthType,
Handler as CDKHandler,
ILayerVersion,
LayerVersion,
Runtime as CDKRuntime,
Tracing,
InvokeMode,
} from "aws-cdk-lib/aws-lambda";
import { RetentionDays } from "aws-cdk-lib/aws-logs";
import {
Token,
Size as CDKSize,
Duration as CDKDuration,
IgnoreMode,
DockerCacheOption,
CustomResource,
} from "aws-cdk-lib/core";
import { Effect, Policy, PolicyStatement, Role } from "aws-cdk-lib/aws-iam";
import { StringParameter } from "aws-cdk-lib/aws-ssm";
import { Platform } from "aws-cdk-lib/aws-ecr-assets";
import { useBootstrap } from "../bootstrap.js";
import { Colors } from "../cli/colors.js";
import { Asset } from "aws-cdk-lib/aws-s3-assets";
import { Config } from "../config.js";
const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const supportedRuntimes = {
container: CDKRuntime.FROM_IMAGE,
rust: CDKRuntime.PROVIDED_AL2023,
"nodejs16.x": CDKRuntime.NODEJS_16_X,
"nodejs18.x": CDKRuntime.NODEJS_18_X,
"nodejs20.x": CDKRuntime.NODEJS_20_X,
"nodejs22.x": CDKRuntime.NODEJS_22_X,
"python3.7": CDKRuntime.PYTHON_3_7,
"python3.8": CDKRuntime.PYTHON_3_8,
"python3.9": CDKRuntime.PYTHON_3_9,
"python3.10": CDKRuntime.PYTHON_3_10,
"python3.11": CDKRuntime.PYTHON_3_11,
"python3.12": CDKRuntime.PYTHON_3_12,
"dotnetcore3.1": CDKRuntime.DOTNET_CORE_3_1,
dotnet6: CDKRuntime.DOTNET_6,
dotnet8: CDKRuntime.DOTNET_8,
java8: CDKRuntime.JAVA_8,
java11: CDKRuntime.JAVA_11,
java17: CDKRuntime.JAVA_17,
java21: CDKRuntime.JAVA_21,
"go1.x": CDKRuntime.PROVIDED_AL2023,
go: CDKRuntime.PROVIDED_AL2023,
};
export type Runtime = keyof typeof supportedRuntimes;
export type FunctionInlineDefinition = string | Function;
export type FunctionDefinition = string | Function | FunctionProps;
export interface FunctionUrlCorsProps extends functionUrlCors.CorsProps {}
export interface FunctionDockerBuildCacheProps extends DockerCacheOption {}
export interface FunctionDockerBuildProps {
/**
* Cache from options to pass to the `docker build` command.
* @default No cache from args are passed
* @example
* ```js
* cacheFrom: [{type: "gha"}],
* ```
*/
cacheFrom?: FunctionDockerBuildCacheProps[];
/**
* Cache to options to pass to the `docker build` command.
* @default No cache to args are passed
* @example
* ```js
* cacheTo: {type: "gha"},
* ```
*/
cacheTo?: FunctionDockerBuildCacheProps;
}
export interface FunctionHooks {
/**
* Hook to run before build
*/
beforeBuild?: (props: FunctionProps, out: string) => Promise<void>;
/**
* Hook to run after build
*/
afterBuild?: (props: FunctionProps, out: string) => Promise<void>;
}
export interface FunctionProps
extends Omit<
FunctionOptions,
| "functionName"
| "memorySize"
| "timeout"
| "runtime"
| "tracing"
| "layers"
| "architecture"
| "logRetention"
| "ephemeralStorageSize"
> {
/**
* Used to configure additional files to copy into the function bundle
*
* @example
* ```js
* new Function(stack, "Function", {
* copyFiles: [{ from: "src/index.js" }]
* })
*```
*/
copyFiles?: FunctionCopyFilesProps[];
/**
* Used to configure go function properties
*/
go?: GoProps;
/**
* Used to configure nodejs function properties
*/
nodejs?: NodeJSProps;
/**
* Used to configure java function properties
*/
java?: JavaProps;
/**
* Used to configure python function properties
*/
python?: PythonProps;
/**
* Used to configure container function properties
*/
container?: ContainerProps;
/**
* Hooks to run before and after function builds
*/
hooks?: FunctionHooks;
/**
* The CPU architecture of the lambda function.
*
* @default "x86_64"
*
* @example
* ```js
* new Function(stack, "Function", {
* architecture: "arm_64",
* })
* ```
*/
architecture?: Lowercase<
keyof Pick<typeof Architecture, "ARM_64" | "X86_64">
>;
/**
* By default, the name of the function is auto-generated by AWS. You can configure the name by providing a string.
*
* @default Auto-generated function name
*
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* functionName: "my-function",
* })
*```
*/
functionName?: string | ((props: FunctionNameProps) => string);
/**
* Path to the entry point and handler function. Of the format:
* `/path/to/file.function`.
*
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* })
*```
*/
handler?: string;
/**
* The runtime environment for the function.
* @default "nodejs22.x"
* @example
* ```js
* new Function(stack, "Function", {
* handler: "function.handler",
* runtime: "nodejs20.x",
* })
*```
*/
runtime?: Runtime;
/**
* The amount of disk storage in MB allocated.
*
* @default "512 MB"
*
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* diskSize: "2 GB",
* })
*```
*/
diskSize?: number | Size;
/**
* The amount of memory in MB allocated.
*
* @default "1 GB"
*
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* memorySize: "2 GB",
* })
*```
*/
memorySize?: number | Size;
/**
* The execution timeout in seconds.
*
* @default "10 seconds"
*
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* timeout: "30 seconds",
* })
*```
*/
timeout?: number | Duration;
/**
* Enable AWS X-Ray Tracing.
*
* @default "active"
*
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* tracing: "pass_through",
* })
*```
*/
tracing?: Lowercase<keyof typeof Tracing>;
/**
* Can be used to disable Live Lambda Development when using `sst start`. Useful for things like Custom Resources that need to execute during deployment.
*
* @default true
*
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* enableLiveDev: false
* })
*```
*/
enableLiveDev?: boolean;
/**
* Configure environment variables for the function
*
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* environment: {
* TABLE_NAME: table.tableName,
* }
* })
* ```
*/
environment?: Record<string, string>;
/**
* Bind resources for the function
*
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* bind: [STRIPE_KEY, bucket],
* })
* ```
*/
bind?: BindingResource[];
/**
* Attaches the given list of permissions to the function. Configuring this property is equivalent to calling `attachPermissions()` after the function is created.
*
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* permissions: ["ses"]
* })
* ```
*/
permissions?: Permissions;
/**
* Enable function URLs, a dedicated endpoint for your Lambda function.
* @default Disabled
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* url: true
* })
* ```
*
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* url: {
* authorizer: "iam",
* cors: {
* allowedOrigins: ['https://example.com'],
* },
* },
* })
* ```
*/
url?: boolean | FunctionUrlProps;
/**
* A list of Layers to add to the function's execution environment.
*
* Note that, if a Layer is created in a stack (say `stackA`) and is referenced in another stack (say `stackB`), SST automatically creates an SSM parameter in `stackA` with the Layer's ARN. And in `stackB`, SST reads the ARN from the SSM parameter, and then imports the Layer.
*
* This is to get around the limitation that a Lambda Layer ARN cannot be referenced across stacks via a stack export. The Layer ARN contains a version number that is incremented everytime the Layer is modified. When you refer to a Layer's ARN across stacks, a CloudFormation export is created. However, CloudFormation does not allow an exported value to be updated. Once exported, if you try to deploy the updated layer, the CloudFormation update will fail. You can read more about this issue here - https://github.com/sst/sst/issues/549.
*
* @default no layers
*
* @example
* ```js
* new Function(stack, "Function", {
* layers: ["arn:aws:lambda:us-east-1:764866452798:layer:chrome-aws-lambda:22", myLayer]
* })
* ```
*/
layers?: (string | ILayerVersion)[];
/**
* Disable sending function logs to CloudWatch Logs.
*
* Note that, logs will still appear locally when running `sst dev`.
* @default false
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* disableCloudWatchLogs: true
* })
* ```
*
*/
disableCloudWatchLogs?: boolean;
/**
* Prefetches bound secret values and injects them into the function's environment variables.
* @default false
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* prefetchSecrets: true
* })
* ```
*
*/
prefetchSecrets?: boolean;
/**
* The duration function logs are kept in CloudWatch Logs.
*
* When updating this property, unsetting it doesn't retain the logs indefinitely. Explicitly set the value to "infinite".
* @default Logs retained indefinitely
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* logRetention: "one_week"
* })
* ```
*/
logRetention?: Lowercase<keyof typeof RetentionDays>;
/**
* @internal
*/
_doNotAllowOthersToBind?: boolean;
}
export interface FunctionNameProps {
/**
* The stack the function is being created in
*/
stack: Stack;
/**
* The function properties
*/
functionProps: FunctionProps;
}
export interface FunctionUrlProps {
/**
* The authorizer for the function URL
* @default "none"
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* url: {
* authorizer: "iam",
* },
* })
* ```
*/
authorizer?: "none" | "iam";
/**
* CORS support for the function URL
* @default true
* @example
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* url: {
* cors: true,
* },
* })
* ```
*
* ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* url: {
* cors: {
* allowedMethods: ["GET", "POST"]
* allowedOrigins: ['https://example.com'],
* },
* },
* })
* ```
*/
cors?: boolean | FunctionUrlCorsProps;
/**
* Stream the response payload.
* @default false
* * ```js
* new Function(stack, "Function", {
* handler: "src/function.handler",
* url: {
* streaming: true,
* },
* })
* ```
*/
streaming?: boolean;
}
export interface NodeJSProps {
/**
* Configure additional esbuild loaders for other file extensions
*
* @example
* ```js
* nodejs: {
* loader: {
* ".png": "file"
* }
* }
* ```
*/
loader?: Record<string, Loader>;
/**
* Packages that will be excluded from the bundle and installed into node_modules instead. Useful for dependencies that cannot be bundled, like those with binary dependencies.
*
* @example
* ```js
* nodejs: {
* install: ["pg"]
* }
* ```
*/
install?: string[];
/**
* Use this to insert an arbitrary string at the beginning of generated JavaScript and CSS files.
*
* @example
* ```js
* nodejs: {
* banner: "console.log('Function starting')"
* }
* ```
*/
banner?: string;
/**
* This allows you to customize esbuild config.
*/
esbuild?: BuildOptions;
/**
* Enable or disable minification
*
* @default false
*
* @example
* ```js
* nodejs: {
* minify: true
* }
* ```
*/
minify?: boolean;
/**
* Configure format
*
* @default "esm"
*
* @example
* ```js
* nodejs: {
* format: "cjs"
* }
* ```
*/
format?: "cjs" | "esm";
/**
* Configure if sourcemaps are generated when the function is bundled for production. Since they increase payload size and potentially cold starts they are not generated by default. They are always generated during local development mode.
*
* @default false
*
* @example
* ```js
* nodejs: {
* sourcemap: true
* }
* ```
*/
sourcemap?: boolean;
/**
* If enabled, modules that are dynamically imported will be bundled as their own files with common dependencies placed in shared chunks. This can help drastically reduce cold starts as your function grows in size.
*
* @default false
*
* @example
* ```js
* nodejs: {
* splitting: true
* }
* ```
*/
splitting?: boolean;
}
/**
* Used to configure Python bundling options
*/
export interface PythonProps {
/**
* A list of commands to override the [default installing behavior](Function#bundle) for Python dependencies.
*
* Each string in the array is a command that'll be run. For example:
*
* @default "[]"
*
* @example
* ```js
* new Function(stack, "Function", {
* python: {
* installCommands: [
* 'export VARNAME="my value"',
* 'pip install --index-url https://domain.com/pypi/myprivatemodule/simple/ --extra-index-url https://pypi.org/simple -r requirements.txt .',
* ]
* }
* })
* ```
*/
installCommands?: string[];
/**
* This options skips the Python bundle step. If you set this flag to `true`, you must ensure
* that either:
*
* 1. Your Python build does not require dependencies.
* 2. Or, you've already installed production dependencies before running `sst deploy`.
*
* One solution to accomplish this is to pre-compile your production dependencies to some
* temporary directory, using pip's `--platform` argument to ensure Python pre-built wheels are
* used and that your builds match your target Lambda runtime, and use SST's `copyFiles`
* option to make sure these dependencies make it into your final deployment build.
*
* This can also help speed up Python Lambdas which do not have external dependencies. By
* default, SST will still run a docker file that is essentially a no-op if you have no
* dependencies. This option will bypass that step, even if you have a `Pipfile`, a `poetry.toml`,
* a `pyproject.toml`, or a `requirements.txt` (which would normally trigger an all-dependencies
* Docker build).
*
* Enabling this option implies that you have accounted for all of the above and are handling
* your own build processes, and you are doing this for the sake of build optimization.
*/
noDocker?: boolean;
/**
* Build options to pass to the docker build command.
*/
dockerBuild?: FunctionDockerBuildProps;
}
/**
* Used to configure Go bundling options
*/
export interface GoProps {
/**
* The ldflags to use when building the Go module.
*
* @default ["-s", "-w"]
* @example
* ```js
* go: {
* ldFlags: ["-X main.version=1.0.0"],
* }
* ```
*/
ldFlags?: string[];
/**
* The build tags to use when building the Go module.
*
* @default []
* @example
* ```js
* go: {
* buildTags: ["enterprise", "pro"],
* }
* ```
*/
buildTags?: string[];
/**
* Whether to enable CGO for the Go build.
*
* @default false
* @example
* ```js
* go: {
* cgoEnabled: true,
* }
* ```
*/
cgoEnabled?: boolean;
}
/**
* Used to configure Java package build options
*/
export interface JavaProps {
/**
* Gradle build command to generate the bundled .zip file.
*
* @default "build"
*
* @example
* ```js
* new Function(stack, "Function", {
* java: {
* buildTask: "bundle"
* }
* })
* ```
*/
buildTask?: string;
/**
* The output folder that the bundled .zip file will be created within.
*
* @default "distributions"
*
* @example
* ```js
* new Function(stack, "Function", {
* java: {
* buildOutputDir: "output"
* }
* })
* ```
*/
buildOutputDir?: string;
/**
* Use custom Amazon Linux runtime instead of Java runtime.
*
* @default Not using provided runtime
*
* @example
* ```js
* new Function(stack, "Function", {
* java: {
* experimentalUseProvidedRuntime: "provided.al2"
* }
* })
* ```
*/
experimentalUseProvidedRuntime?: "provided" | "provided.al2";
}
export interface ContainerProps {
/**
* Specify or override the CMD on the Docker image.
* @example
* ```js
* container: {
* cmd: ["index.handler"]
* }
* ```
*/
cmd?: string[];
/**
* Name of the Dockerfile.
* @example
* ```js
* container: {
* file: "path/to/Dockerfile.prod"
* }
* ```
*/
file?: string;
/**
* Build args to pass to the docker build command.
* @default No build args
* @example
* ```js
* container: {
* buildArgs: {
* FOO: "bar"
* }
* }
* ```
*/
buildArgs?: Record<string, string>;
/**
* SSH agent socket or keys to pass to the docker build command.
* Docker BuildKit must be enabled to use the ssh flag
* @default No --ssh flag is passed to the build command
* @example
* ```js
* container: {
* buildSsh: "default"
* }
* ```
*/
buildSsh?: string;
/**
* Cache from options to pass to the docker build command.
* [DockerCacheOption](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr_assets.DockerCacheOption.html)[].
* @default No cache from options are passed to the build command
* @example
* ```js
* container: {
* cacheFrom: [{ type: 'registry', params: { ref: 'ghcr.io/myorg/myimage:cache' }}],
* }
* ```
*/
cacheFrom?: FunctionDockerBuildCacheProps[];
/**
* Cache to options to pass to the docker build command.
* [DockerCacheOption](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr_assets.DockerCacheOption.html)[].
* @default No cache to options are passed to the build command
* @example
* ```js
* container: {
* cacheTo: { type: 'registry', params: { ref: 'ghcr.io/myorg/myimage:cache', mode: 'max', compression: 'zstd' }},
* }
* ```
*/
cacheTo?: FunctionDockerBuildCacheProps;
}
/**
* Used to configure additional files to copy into the function bundle
*
* @example
* ```js
* new Function(stack, "Function", {
* copyFiles: [{ from: "src/index.js" }]
* })
*```
*/
export interface FunctionCopyFilesProps {
/**
* Source path relative to sst.config.ts
*/
from: string;
/**
* Destination path relative to function root in bundle
*/
to?: string;
}
/**
* The `Function` construct is a higher level CDK construct that makes it easy to create a Lambda Function with support for Live Lambda Development.
*
* @example
*
* ```js
* import { Function } from "sst/constructs";
*
* new Function(stack, "MySnsLambda", {
* handler: "src/sns/index.main",
* });
* ```
*/
export class Function extends CDKFunction implements SSTConstruct {
public readonly id: string;
public readonly _isLiveDevEnabled: boolean;
/** @internal */
public readonly _doNotAllowOthersToBind?: boolean;
/** @internal */
public _overrideMetadataHandler?: string;
private missingSourcemap?: boolean;
private functionUrl?: FunctionUrl;
private props: FunctionProps;
private allBindings: BindingResource[] = [];
constructor(scope: Construct, id: string, props: FunctionProps) {
const app = scope.node.root as App;
const stack = Stack.of(scope) as Stack;
// Merge with app defaultFunctionProps
// note: reverse order so later prop override earlier ones
stack.defaultFunctionProps
.slice()
.reverse()
.forEach((per) => {
props = Function.mergeProps(per, props);
});
props.runtime = props.runtime || "nodejs22.x";
if (props.runtime === "go1.x") useWarning().add("go.deprecated");
// Set defaults
const functionName =
props.functionName &&
(typeof props.functionName === "string"
? props.functionName
: props.functionName({ stack, functionProps: props }));
const timeout = Function.normalizeTimeout(props.timeout);
const architecture = (() => {
if (props.architecture === "arm_64") return Architecture.ARM_64;
if (props.architecture === "x86_64") return Architecture.X86_64;
return Architecture.X86_64;
})();
const memorySize = Function.normalizeMemorySize(props.memorySize);
const diskSize = Function.normalizeDiskSize(props.diskSize);
const tracing =
Tracing[
(props.tracing || "active").toUpperCase() as keyof typeof Tracing
];
const logRetention =
props.logRetention &&
RetentionDays[
props.logRetention.toUpperCase() as keyof typeof RetentionDays
];
const isLiveDevEnabled =
app.mode === "dev" && (props.enableLiveDev === false ? false : true);
Function.validateHandlerSet(id, props);
Function.validateVpcSettings(id, props);
// Handle inactive stacks
if (!stack.isActive) {
// Note: need to override runtime as CDK does not support inline code
// for some runtimes.
super(scope, id, {
...props,
architecture,
code: Code.fromInline("export function placeholder() {}"),
handler: "index.placeholder",
functionName,
runtime: CDKRuntime.NODEJS_22_X,
memorySize,
ephemeralStorageSize: diskSize,
timeout,
tracing,
environment: props.environment,
layers: Function.buildLayers(scope, id, props),
logRetention,
logRetentionRetryOptions: logRetention && { maxRetries: 100 },
});
}
// Handle local development (ie. sst start)
// - set runtime to nodejs for non-Node runtimes (b/c the stub is in Node)
// - set retry to 0. When the debugger is disconnected, the Cron construct
// will still try to periodically invoke the Lambda, and the requests would
// fail and retry. So when launching `sst start`, a couple of retry requests
// from recent failed request will be received. And this behavior is confusing.
else if (isLiveDevEnabled) {
// If debugIncreaseTimeout is enabled:
// set timeout to 900s. This will give people more time to debug the function
// without timing out the request. Note API Gateway requests have a maximum
// timeout of 29s. In this case, the API will timeout, but the Lambda function
// will continue to run.
let debugOverrideProps;
if (app.debugIncreaseTimeout) {
debugOverrideProps = {
timeout: toCdkDuration("900 second"),
};
}
// Ensure descriptions fits the 256 chars limit
const description = props.description
? `${props.description.substring(0, 240)} (live)`
: `live`;
super(scope, id, {
...props,
...(props.runtime === "container"
? {
description,
code: Code.fromAssetImage(
path.resolve(__dirname, "../support/bridge"),
{
...(architecture?.dockerPlatform
? { platform: Platform.custom(architecture.dockerPlatform) }
: {}),
}
),
handler: CDKHandler.FROM_IMAGE,
runtime: CDKRuntime.FROM_IMAGE,
layers: undefined,
}
: {
description,
runtime: CDKRuntime.NODEJS_22_X,
code: Code.fromAsset(
path.resolve(__dirname, "../support/bridge")
),
handler: "live-lambda.handler",
layers: [],
}),
architecture,
functionName,
memorySize,
ephemeralStorageSize: diskSize,
timeout,
tracing,
environment: props.environment,
logRetention,
logRetentionRetryOptions: logRetention && { maxRetries: 100 },
retryAttempts: 0,
...(debugOverrideProps || {}),
});
this.addEnvironment("SST_FUNCTION_ID", this.node.addr);
useDeferredTasks().add(async () => {
if (app.isRunningSSTTest()) return;
const bootstrap = await useBootstrap();
const bootstrapBucketArn = `arn:${Stack.of(this).partition}:s3:::${