forked from open-constructs/cdk-serverless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunc.ts
275 lines (241 loc) · 7.21 KB
/
func.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
import * as cognito from '@aws-cdk/aws-cognito';
import * as dynamodb from '@aws-cdk/aws-dynamodb';
import * as iam from '@aws-cdk/aws-iam';
import * as lambda from '@aws-cdk/aws-lambda';
import * as s3 from '@aws-cdk/aws-s3';
import * as cdk from '@aws-cdk/core';
import { WatchableNodejsFunction, WatchableNodejsFunctionProps } from 'cdk-watch';
export type LambdaOptions = Omit<WatchableNodejsFunctionProps, 'entry' | 'handler' | 'description'>
export interface LambdaTracingOptions {
/**
* Activate tracing with X-Ray
*
* @default lambda.Tracing.DISABLED
*/
xRayTracing?: lambda.Tracing;
/**
* Activate tracing with Thundra
*
* @default false
*/
thundraTracing?: boolean;
/**
* name of the Secret that contains the Thundra API Key
*
* @default Thundra
*/
thundraApiKeySecret?: string;
/**
* name of the Secret that contains the Thundra API Key
*
* @default ApiKey
*/
thundraApiKeySecretField?: string;
/**
* ARN of the Lambda layer provided by Thundra
*
* @default latest
*/
thundraLayerArn?: string;
}
export interface LambdaFunctionProps {
/**
* Deployment stage (e.g. dev)
*/
stageName?: string;
/**
* entry file name
*/
entry: string;
/**
* name of the exported handler function
*
* @default handler
*/
handler?: string;
/**
* description of the Lambda function
*/
description?: string;
/**
* DynamoDB that is used as datastore
* The Lambda function will have read access to this table automatically
* The name of the table is available as process.env.TABLE
*/
table?: dynamodb.ITable;
/**
* Activate write permissions to the DynamoDB table
*/
tableWrites?: boolean;
/**
* Cognito user pool
* The name of the pool is available as process.env.USER_POOL_ID
*/
userPool?: cognito.IUserPool;
/**
* Bucket that is used for assets and published using the asset CDN
* The name of the bucket is available as process.env.ASSET_BUCKET
*/
assetBucket?: s3.Bucket;
/**
* Fully qualified domain name of the asset CDN
* It is available as process.env.ASSET_DOMAIN_NAME
*/
assetDomainName?: string;
/**
* Should the AWS-SDK be packaged with the Lambda code or excluded
*
* @default false (exclude SDK and use runtime provided one)
*/
includeSDK?: boolean;
/**
* additional environment variables of the Lambda function
*/
additionalEnv?: {
[key: string]: string;
};
/**
* additional options for the underlying Lambda function construct
*/
lambdaOptions?: LambdaOptions;
/**
* Tracing config
*/
lambdaTracing?: LambdaTracingOptions;
}
export class LambdaFunction extends WatchableNodejsFunction {
constructor(scope: cdk.Construct, id: string, private props: LambdaFunctionProps) {
super(scope, id, {
...props.lambdaOptions,
entry: props.entry,
bundling: {
...props.lambdaOptions?.bundling,
externalModules: props.includeSDK ? [] : undefined,
loader: {
...props.lambdaOptions?.bundling?.loader,
'.yaml': 'text',
},
},
environment: {
...props.lambdaOptions?.environment,
...props.stageName && {
STAGE: props.stageName,
},
...props.table && {
TABLE: props.table.tableName,
},
...props.userPool && {
USER_POOL_ID: props.userPool.userPoolId,
},
...props.assetBucket && {
ASSET_BUCKET: props.assetBucket.bucketName,
},
...props.assetDomainName && {
ASSET_DOMAIN_NAME: props.assetDomainName,
},
...props.lambdaTracing?.thundraTracing && {
thundra_agent_lambda_handler: `index.${props.handler ?? 'handler'}`,
thundra_apiKey: cdk.SecretValue.secretsManager(props.lambdaTracing.thundraApiKeySecret ?? 'Thundra', { jsonField: props.lambdaTracing.thundraApiKeySecretField ?? 'ApiKey' }).toString(),
},
...props.additionalEnv,
},
handler: props.handler ?? 'handler',
description: props.description,
tracing: props.lambdaTracing?.xRayTracing,
});
if (props.lambdaTracing?.thundraTracing) {
this.addLayers(lambda.LayerVersion.fromLayerVersionArn(this, 'ThundraLayer', this.props.lambdaTracing?.thundraLayerArn ?? `arn:aws:lambda:${cdk.Stack.of(this).region}:269863060030:layer:thundra-lambda-node-layer-minified:87`));
(this.node.tryFindChild('Resource') as lambda.CfnFunction).handler = 'thundra_handler.wrapper';
}
if (props.table) {
if (props.tableWrites ?? true) {
props.table.grantReadWriteData(this);
} else {
props.table.grantReadData(this);
}
}
}
public setTable(table: dynamodb.ITable, tableWrites?: boolean): LambdaFunction {
this.props.table = table;
this.props.tableWrites = tableWrites;
this.addEnvironment('TABLE', table.tableName);
if (tableWrites ?? true) {
table.grantReadWriteData(this);
} else {
table.grantReadData(this);
}
return this;
}
public setUserPool(userPool: cognito.IUserPool): LambdaFunction {
this.props.userPool = userPool;
this.addEnvironment('USER_POOL_ID', userPool.userPoolId);
return this;
}
public grantTableWrite(): LambdaFunction {
if (!this.props.table) {
throw new Error('No table configured');
}
this.props.table.grantReadWriteData(this);
return this;
}
public grantSendEmails(): LambdaFunction {
this.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({
actions: [
'ses:SendEmail',
'ses:SendTemplatedEmail',
'ses:SendBulkTemplatedEmail',
],
resources: ['*'],
}));
return this;
}
public grantUploadAssets(): LambdaFunction {
if (!this.props.assetBucket) {
throw new Error('No asset bucket configured');
}
this.props.assetBucket.grantPut(this);
return this;
}
public grantDeleteAsset(): LambdaFunction {
if (!this.props.assetBucket) {
throw new Error('No asset bucket configured');
}
this.props.assetBucket.grantDelete(this);
return this;
}
public grantUserpoolRead(): LambdaFunction {
if (!this.props.userPool) {
throw new Error('No user pool configured');
}
this.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({
actions: [
'cognito-idp:ListUsers',
'cognito-idp:AdminGetUser',
'cognito-idp:AdminListGroupsForUser',
],
resources: [this.props.userPool.userPoolArn],
}));
return this;
}
public grantUserpoolReadWrite(): LambdaFunction {
if (!this.props.userPool) {
throw new Error('No user pool configured');
}
this.grantUserpoolRead();
this.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({
actions: [
'cognito-idp:AdminUpdateUserAttributes',
'cognito-idp:AdminAddUserToGroup',
'cognito-idp:AdminRemoveUserFromGroup',
'cognito-idp:AdminCreateUser',
'cognito-idp:AdminDeleteUser',
],
resources: [this.props.userPool.userPoolArn],
}));
return this;
}
public setTimeout(timeout: cdk.Duration): LambdaFunction {
(this.node.defaultChild as lambda.CfnFunction).addPropertyOverride('Timeout', timeout.toSeconds());
return this;
}
}