/
lambda-function.ts
371 lines (337 loc) · 10.4 KB
/
lambda-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
import * as path from "path";
import { pascal } from "case";
import { AwsCdkDeps } from "./awscdk-deps";
import {
convertToPosixPath,
TYPESCRIPT_EDGE_LAMBDA_EXT,
TYPESCRIPT_LAMBDA_EXT,
} from "./internal";
import { Component } from "../component";
import { Bundler, BundlingOptions, Eslint } from "../javascript";
import { Project } from "../project";
import { SourceCode } from "../source-code";
import { TypeScriptProject } from "../typescript";
/**
* Common options for `LambdaFunction`. Applies to all functions in
* auto-discovery.
*/
export interface LambdaFunctionCommonOptions {
/**
* The node.js version to target.
*
* @default Runtime.NODEJS_16_X
*/
readonly runtime?: LambdaRuntime;
/**
* Bundling options for this AWS Lambda function.
*
* If not specified the default bundling options specified for the project
* `Bundler` instance will be used.
*
* @default - defaults
*/
readonly bundlingOptions?: BundlingOptions;
/**
* Whether to automatically reuse TCP connections when working with the AWS
* SDK for JavaScript.
*
* This sets the `AWS_NODEJS_CONNECTION_REUSE_ENABLED` environment variable
* to `1`.
*
* Not applicable when `edgeLambda` is set to `true` because environment
* variables are not supported in Lambda@Edge.
*
* @see https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/node-reusing-connections.html
*
* @default true
*/
readonly awsSdkConnectionReuse?: boolean;
/**
* Whether to create a `cloudfront.experimental.EdgeFunction` instead
* of a `lambda.Function`.
*
* @default false
*/
readonly edgeLambda?: boolean;
}
/**
* Options for `Function`.
*/
export interface LambdaFunctionOptions extends LambdaFunctionCommonOptions {
/**
* A path from the project root directory to a TypeScript file which contains
* the AWS Lambda handler entrypoint (exports a `handler` function).
*
* This is relative to the root directory of the project.
*
* @example "src/subdir/foo.lambda.ts"
*/
readonly entrypoint: string;
/**
* The name of the generated TypeScript source file. This file should also be
* under the source tree.
*
* @default - The name of the entrypoint file, with the `-function.ts` suffix
* instead of `.lambda.ts`.
*/
readonly constructFile?: string;
/**
* The name of the generated `lambda.Function` subclass.
*
* @default - A pascal cased version of the name of the entrypoint file, with
* the extension `Function` (e.g. `ResizeImageFunction`).
*/
readonly constructName?: string;
/**
* AWS CDK dependency manager.
*/
readonly cdkDeps: AwsCdkDeps;
}
/**
* Generates a pre-bundled AWS Lambda function construct from handler code.
*
* To use this, create an AWS Lambda handler file under your source tree with
* the `.lambda.ts` extension and add a `LambdaFunction` component to your
* typescript project pointing to this entrypoint.
*
* This will add a task to your "compile" step which will use `esbuild` to
* bundle the handler code into the build directory. It will also generate a
* file `src/foo-function.ts` with a custom AWS construct called `FooFunction`
* which extends `@aws-cdk/aws-lambda.Function` which is bound to the bundled
* handle through an asset.
*
* @example
*
* new LambdaFunction(myProject, {
* srcdir: myProject.srcdir,
* entrypoint: 'src/foo.lambda.ts',
* });
*/
export class LambdaFunction extends Component {
/**
* Defines a pre-bundled AWS Lambda function construct from handler code.
*
* @param project The project to use
* @param options Options
*/
constructor(project: Project, options: LambdaFunctionOptions) {
super(project);
const cdkDeps = options.cdkDeps;
const bundler = Bundler.of(project);
if (!bundler) {
throw new Error(
"No bundler found. Please add a Bundler component to your project."
);
}
const runtime = options.runtime ?? LambdaRuntime.NODEJS_16_X;
// allow Lambda handler code to import dev-deps since they are only needed
// during bundling
const eslint = Eslint.of(project);
eslint?.allowDevDeps(options.entrypoint);
const entrypoint = options.entrypoint;
if (
!entrypoint.endsWith(TYPESCRIPT_LAMBDA_EXT) &&
!entrypoint.endsWith(TYPESCRIPT_EDGE_LAMBDA_EXT)
) {
throw new Error(
`${entrypoint} must have a ${TYPESCRIPT_LAMBDA_EXT} or ${TYPESCRIPT_EDGE_LAMBDA_EXT} extension`
);
}
const basePath = path.posix.join(
path.dirname(entrypoint),
path.basename(
entrypoint,
options.edgeLambda ? TYPESCRIPT_EDGE_LAMBDA_EXT : TYPESCRIPT_LAMBDA_EXT
)
);
const constructFile = options.constructFile ?? `${basePath}-function.ts`;
if (path.extname(constructFile) !== ".ts") {
throw new Error(
`Construct file name "${constructFile}" must have a .ts extension`
);
}
// type names
const constructName =
options.constructName ?? pascal(path.basename(basePath)) + "Function";
const propsType = `${constructName}Props`;
const bundle = bundler.addBundle(entrypoint, {
target: runtime.esbuildTarget,
platform: runtime.esbuildPlatform,
externals: runtime.defaultExternals,
...options.bundlingOptions,
tsconfigPath: (project as TypeScriptProject)?.tsconfigDev?.fileName,
});
// calculate the relative path between the directory containing the
// generated construct source file to the directory containing the bundle
// index.js by resolving them as absolute paths first.
// e.g:
// - outfileAbs => `/project-outdir/assets/foo/bar/baz/foo-function/index.js`
// - constructAbs => `/project-outdir/src/foo/bar/baz/foo-function.ts`
const outfileAbs = path.join(project.outdir, bundle.outfile);
const constructAbs = path.join(project.outdir, constructFile);
const relativeOutfile = path.relative(
path.dirname(constructAbs),
path.dirname(outfileAbs)
);
const src = new SourceCode(project, constructFile);
if (src.marker) {
src.line(`// ${src.marker}`);
}
src.line("import * as path from 'path';");
if (cdkDeps.cdkMajorVersion === 1) {
if (options.edgeLambda) {
src.line("import * as cloudfront from '@aws-cdk/aws-cloudfront';");
cdkDeps.addV1Dependencies("@aws-cdk/aws-cloudfront");
}
src.line("import * as lambda from '@aws-cdk/aws-lambda';");
src.line("import { Construct } from '@aws-cdk/core';");
cdkDeps.addV1Dependencies("@aws-cdk/aws-lambda");
cdkDeps.addV1Dependencies("@aws-cdk/core");
} else {
if (options.edgeLambda) {
src.line("import * as cloudfront from 'aws-cdk-lib/aws-cloudfront';");
}
src.line("import * as lambda from 'aws-cdk-lib/aws-lambda';");
src.line("import { Construct } from 'constructs';");
}
src.line();
src.line("/**");
src.line(` * Props for ${constructName}`);
src.line(" */");
if (options.edgeLambda) {
src.open(
`export interface ${propsType} extends cloudfront.experimental.EdgeFunctionProps {`
);
} else {
src.open(
`export interface ${propsType} extends lambda.FunctionOptions {`
);
}
src.close("}");
src.line();
src.line("/**");
src.line(
` * An AWS Lambda function which executes ${convertToPosixPath(
basePath
)}.`
);
src.line(" */");
if (options.edgeLambda) {
src.open(
`export class ${constructName} extends cloudfront.experimental.EdgeFunction {`
);
} else {
src.open(`export class ${constructName} extends lambda.Function {`);
}
src.open(
`constructor(scope: Construct, id: string, props?: ${propsType}) {`
);
src.open("super(scope, id, {");
src.line(`description: '${convertToPosixPath(entrypoint)}',`);
src.line("...props,");
src.line(
`runtime: new lambda.Runtime('${runtime.functionRuntime}', lambda.RuntimeFamily.NODEJS),`
);
src.line("handler: 'index.handler',");
src.line(
`code: lambda.Code.fromAsset(path.join(__dirname, '${convertToPosixPath(
relativeOutfile
)}')),`
);
src.close("});");
if ((options.awsSdkConnectionReuse ?? true) && !options.edgeLambda) {
src.line(
"this.addEnvironment('AWS_NODEJS_CONNECTION_REUSE_ENABLED', '1', { removeInEdge: true });"
);
}
src.close("}");
src.close("}");
this.project.logger.verbose(
`${basePath}: construct "${constructName}" generated under "${constructFile}"`
);
this.project.logger.verbose(
`${basePath}: bundle task "${bundle.bundleTask.name}"`
);
if (bundle.watchTask) {
this.project.logger.verbose(
`${basePath}: bundle watch task "${bundle.watchTask.name}"`
);
}
}
}
/**
* Options for the AWS Lambda function runtime
*/
export interface LambdaRuntimeOptions {
/**
* Packages that are considered externals by default when bundling
*
* @default ['@aws-sdk/*']
*/
readonly defaultExternals?: string[];
}
/**
* The runtime for the AWS Lambda function.
*/
export class LambdaRuntime {
/**
* Node.js 10.x
* @deprecated NodeJS10 has been deprecated
*/
public static readonly NODEJS_10_X = new LambdaRuntime(
"nodejs10.x",
"node10",
{ defaultExternals: ["aws-sdk"] }
);
/**
* Node.js 12.x
* @deprecated NodeJS12 has been deprecated
*/
public static readonly NODEJS_12_X = new LambdaRuntime(
"nodejs12.x",
"node12",
{ defaultExternals: ["aws-sdk"] }
);
/**
* Node.js 14.x
* @deprecated NodeJS14 has been deprecated
*/
public static readonly NODEJS_14_X = new LambdaRuntime(
"nodejs14.x",
"node14",
{ defaultExternals: ["aws-sdk"] }
);
/**
* Node.js 16.x
*/
public static readonly NODEJS_16_X = new LambdaRuntime(
"nodejs16.x",
"node16",
{ defaultExternals: ["aws-sdk"] }
);
/**
* Node.js 18.x
*/
public static readonly NODEJS_18_X = new LambdaRuntime(
"nodejs18.x",
"node18"
);
public readonly esbuildPlatform = "node";
public readonly defaultExternals: string[];
public constructor(
/**
* The Node.js runtime to use
*/
public readonly functionRuntime: string,
/**
* The esbuild setting to use.
*/
public readonly esbuildTarget: string,
/**
* Options for this runtime.
*/
options?: LambdaRuntimeOptions
) {
this.defaultExternals = options?.defaultExternals ?? ["@aws-sdk/*"];
}
}