-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.ts
387 lines (369 loc) · 13.6 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
/*
*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: MIT-0
*/
import { RemovalPolicy, Duration, Aws, Stack } from 'aws-cdk-lib'
import {
AttributeType,
BillingMode,
ProjectionType,
Table
} from 'aws-cdk-lib/aws-dynamodb'
import {
Effect,
Policy,
PolicyStatement,
Role,
ServicePrincipal
} from 'aws-cdk-lib/aws-iam'
import {
ApplicationLogLevel,
Architecture,
LambdaInsightsVersion,
LoggingFormat,
Runtime,
Tracing
} from 'aws-cdk-lib/aws-lambda'
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs'
import { RetentionDays } from 'aws-cdk-lib/aws-logs'
import { Bucket, BucketEncryption } from 'aws-cdk-lib/aws-s3'
import { CfnScheduleGroup } from 'aws-cdk-lib/aws-scheduler'
import { Construct } from 'constructs'
import { PinpointApp } from './pinpoint-app'
import { type IUserPool } from 'aws-cdk-lib/aws-cognito'
import { type UIConfig } from '../shared'
import { NagSuppressions } from 'cdk-nag'
import { fileURLToPath } from 'url'
import path, { dirname } from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
interface NewsletterGeneratorProps {
dataFeedTable: Table
dataFeedTableLSI: string
accountTable: Table
accountTableUserIndex: string
userPool: IUserPool
loggingBucket: Bucket
}
export class NewsletterGenerator extends Construct {
public readonly newsletterTableCampaignGSI: string =
'newsletter-campaign-index'
public readonly newsletterTableItemTypeGSI: string =
'newsletter-item-type-index'
public readonly newsletterTable: Table
public readonly createNewsletterFunction: NodejsFunction
public readonly userSubscriberFunction: NodejsFunction
public readonly userUnsubscriberFunction: NodejsFunction
public readonly newsletterScheduleGroup: CfnScheduleGroup
public readonly getNewsletterFunction: NodejsFunction
public readonly emailBucket: Bucket
public readonly emailBucketArn: string
private readonly newsletterScheduleGroupName: string
constructor (scope: Construct, id: string, props: NewsletterGeneratorProps) {
super(scope, id)
const { dataFeedTable, userPool, loggingBucket } = props
this.newsletterScheduleGroupName =
Stack.of(this).stackName + 'NewsletterSubscriptions'
const uiConfig = this.node.tryGetContext('ui') as UIConfig
const newsletterTable = new Table(this, 'NewsletterTable', {
removalPolicy: RemovalPolicy.RETAIN_ON_UPDATE_OR_DELETE,
tableName: Stack.of(this).stackName + '-NewsletterTable',
pointInTimeRecovery: true,
partitionKey: {
name: 'newsletterId',
type: AttributeType.STRING
},
sortKey: {
name: 'sk',
type: AttributeType.STRING
},
billingMode: BillingMode.PAY_PER_REQUEST
})
newsletterTable.addGlobalSecondaryIndex({
indexName: this.newsletterTableCampaignGSI,
partitionKey: {
name: 'campaignId',
type: AttributeType.STRING
},
sortKey: {
name: 'sk',
type: AttributeType.STRING
},
projectionType: ProjectionType.KEYS_ONLY
})
newsletterTable.addGlobalSecondaryIndex({
indexName: this.newsletterTableItemTypeGSI,
partitionKey: {
name: 'sk',
type: AttributeType.STRING
},
sortKey: {
name: 'accountId',
type: AttributeType.STRING
}
})
const emailBucket = new Bucket(this, 'EmailBucket', {
removalPolicy: RemovalPolicy.DESTROY,
autoDeleteObjects: true,
serverAccessLogsBucket: loggingBucket,
serverAccessLogsPrefix: 'email-bucket-server-access-logs/',
encryption: BucketEncryption.S3_MANAGED,
enforceSSL: true
})
this.emailBucketArn = emailBucket.bucketArn
const pinpointApp = new PinpointApp(this, 'NewsletterPinpoint', {
newsletterTable,
newsletterTableCampaignGSI: this.newsletterTableCampaignGSI
})
const newsletterCampaignCreatorFunction = new NodejsFunction(
this,
'newsletter-campaign-creator',
{
description:
'Function responsible for creating the newsletter campaigns for each unique email',
handler: 'handler',
entry: path.join(__dirname, 'index.newsletter-campaign-creator.ts'),
architecture: Architecture.ARM_64,
runtime: Runtime.NODEJS_20_X,
tracing: Tracing.ACTIVE,
loggingFormat: LoggingFormat.JSON,
logRetention: RetentionDays.ONE_WEEK,
applicationLogLevelV2: ApplicationLogLevel.DEBUG,
insightsVersion: LambdaInsightsVersion.VERSION_1_0_229_0,
timeout: Duration.minutes(5),
environment: {
POWERTOOLS_LOG_LEVEL: 'DEBUG',
NEWSLETTER_TABLE: newsletterTable.tableName,
PINPOINT_APP_ID: pinpointApp.pinpointAppId,
PINPOINT_BASE_SEGMENT_ID: pinpointApp.pinpointBaseSegmentId,
PINPOINT_CAMPAIGN_HOOK_FUNCTION:
pinpointApp.pinpointCampaignHookFunction.functionName,
EMAIL_BUCKET: emailBucket.bucketName
}
}
)
newsletterCampaignCreatorFunction.addToRolePolicy(
pinpointApp.pinpointAddNewsletterCampaignAndSegmentPolicyStatement
)
emailBucket.grantRead(newsletterCampaignCreatorFunction)
newsletterTable.grantReadWriteData(newsletterCampaignCreatorFunction)
const emailGeneratorFunction = new NodejsFunction(this, 'email-generator', {
description:
'Function responsible for generating the newsletter HTML & Plain Text emails',
handler: 'handler',
entry: path.join(__dirname, 'index.email-generator.ts'),
architecture: Architecture.ARM_64,
runtime: Runtime.NODEJS_20_X,
tracing: Tracing.ACTIVE,
loggingFormat: LoggingFormat.JSON,
logRetention: RetentionDays.ONE_WEEK,
applicationLogLevelV2: ApplicationLogLevel.DEBUG,
insightsVersion: LambdaInsightsVersion.VERSION_1_0_229_0,
memorySize: 512, // Bumping memory up on this function since it is doing rendering and processing
timeout: Duration.minutes(5),
environment: {
POWERTOOLS_LOG_LEVEL: 'DEBUG',
DATA_FEED_TABLE: props.dataFeedTable.tableName,
DATA_FEED_TABLE_LSI: props.dataFeedTableLSI,
NEWSLETTER_TABLE: newsletterTable.tableName,
EMAIL_BUCKET: emailBucket.bucketName,
NEWSLETTER_CAMPAIGN_CREATOR_FUNCTION:
newsletterCampaignCreatorFunction.functionName,
APP_HOST_NAME: uiConfig?.hostName ?? ''
}
})
props.dataFeedTable.grantReadData(emailGeneratorFunction)
newsletterTable.grantReadWriteData(emailGeneratorFunction)
emailBucket.grantWrite(emailGeneratorFunction)
newsletterCampaignCreatorFunction.grantInvoke(emailGeneratorFunction)
const newsletterScheduleGroup = new CfnScheduleGroup(
this,
'NewsletterScheduleGroup',
{
name: this.newsletterScheduleGroupName
}
)
const emailGeneratorSchedulerInvokeRole = new Role(
this,
'EmailGeneratorSchedulerInvokeRole',
{
assumedBy: new ServicePrincipal('scheduler.amazonaws.com'),
description:
'Role used by the scheduler to invoke the email generator function'
}
)
emailGeneratorFunction.grantInvoke(emailGeneratorSchedulerInvokeRole)
emailGeneratorFunction.addToRolePolicy(
new PolicyStatement({
actions: ['bedrock:InvokeModel'],
resources: ['*'],
effect: Effect.ALLOW
})
)
const newsletterCreatorFunction = new NodejsFunction(
this,
'newsletter-creator',
{
description:
'Function responsible for creating and scheduling the newsletter',
handler: 'handler',
entry: path.join(__dirname, 'index.newsletter-creator.ts'),
architecture: Architecture.ARM_64,
runtime: Runtime.NODEJS_20_X,
tracing: Tracing.ACTIVE,
loggingFormat: LoggingFormat.JSON,
logRetention: RetentionDays.ONE_WEEK,
applicationLogLevelV2: ApplicationLogLevel.DEBUG,
insightsVersion: LambdaInsightsVersion.VERSION_1_0_229_0,
timeout: Duration.minutes(5),
environment: {
POWERTOOLS_LOG_LEVEL: 'DEBUG',
NEWSLETTER_DATA_TABLE: newsletterTable.tableName,
NEWSLETTER_SCHEDULE_GROUP_NAME: this.newsletterScheduleGroupName,
EMAIL_GENERATOR_FUNCTION_ARN: emailGeneratorFunction.functionArn,
EMAIL_GENERATOR_SCHEDULER_ROLE_ARN:
emailGeneratorSchedulerInvokeRole.roleArn,
PINPOINT_APP_ID: pinpointApp.pinpointAppId,
PINPOINT_BASE_SEGMENT_ID: pinpointApp.pinpointBaseSegmentId,
ACCOUNT_TABLE: props.accountTable.tableName,
ACCOUNT_TABLE_USER_INDEX: props.accountTableUserIndex
}
}
)
props.accountTable.grantReadData(newsletterCreatorFunction)
newsletterTable.grantReadWriteData(newsletterCreatorFunction)
newsletterCreatorFunction.addToRolePolicy(
pinpointApp.pinpointAddNewsletterCampaignAndSegmentPolicyStatement
)
newsletterCreatorFunction.addToRolePolicy(
new PolicyStatement({
actions: ['scheduler:CreateSchedule', 'iam:PassRole'],
resources: [
emailGeneratorSchedulerInvokeRole.roleArn,
`arn:aws:scheduler:${Aws.REGION}:${Aws.ACCOUNT_ID}:schedule/${this.newsletterScheduleGroupName}/*`
]
})
)
const getNewsletterFunction = new NodejsFunction(this, 'get-newsletter', {
description:
'Function responsible for getting looking up a Newsletter and its associated details',
handler: 'handler',
entry: path.join(__dirname, 'index.get-newsletter.ts'),
architecture: Architecture.ARM_64,
runtime: Runtime.NODEJS_20_X,
tracing: Tracing.ACTIVE,
loggingFormat: LoggingFormat.JSON,
logRetention: RetentionDays.ONE_WEEK,
applicationLogLevelV2: ApplicationLogLevel.DEBUG,
insightsVersion: LambdaInsightsVersion.VERSION_1_0_229_0,
timeout: Duration.minutes(5),
environment: {
POWERTOOLS_LOG_LEVEL: 'DEBUG',
NEWSLETTER_DATA_TABLE: newsletterTable.tableName,
NEWS_SUBSCRIPTION_TABLE: dataFeedTable.tableName
}
})
newsletterTable.grantReadData(getNewsletterFunction)
dataFeedTable.grantReadData(getNewsletterFunction)
const userSubscriberFunction = new NodejsFunction(this, 'user-subscriber', {
description:
'Function responsible for subscribing a user to the newsletter',
handler: 'handler',
entry: path.join(__dirname, 'index.user-subscriber.ts'),
architecture: Architecture.ARM_64,
runtime: Runtime.NODEJS_20_X,
tracing: Tracing.ACTIVE,
loggingFormat: LoggingFormat.JSON,
logRetention: RetentionDays.ONE_WEEK,
applicationLogLevelV2: ApplicationLogLevel.DEBUG,
insightsVersion: LambdaInsightsVersion.VERSION_1_0_229_0,
timeout: Duration.minutes(5),
environment: {
POWERTOOLS_LOG_LEVEL: 'DEBUG',
PINPOINT_APP_ID: pinpointApp.pinpointAppId,
NEWSLETTER_TABLE: newsletterTable.tableName,
COGNITO_USER_POOL_ID: userPool.userPoolId
}
})
newsletterTable.grantReadWriteData(userSubscriberFunction)
userSubscriberFunction.addToRolePolicy(
pinpointApp.pinpointSubscribeUserToNewsletterPolicyStatement
)
userSubscriberFunction.role?.attachInlinePolicy(
new Policy(this, 'UserSubscriberCognitoLookup', {
statements: [
new PolicyStatement({
effect: Effect.ALLOW,
actions: ['cognito-idp:ListUsers'],
resources: [userPool.userPoolArn]
})
]
})
)
const userUnsubscriberFunction = new NodejsFunction(
this,
'user-unsubscriber',
{
description:
'Function responsible for unsubscribing a user from the newsletter',
handler: 'handler',
entry: path.join(__dirname, 'index.user-unsubscriber.ts'),
architecture: Architecture.ARM_64,
runtime: Runtime.NODEJS_20_X,
tracing: Tracing.ACTIVE,
loggingFormat: LoggingFormat.JSON,
logRetention: RetentionDays.ONE_WEEK,
applicationLogLevelV2: ApplicationLogLevel.DEBUG,
insightsVersion: LambdaInsightsVersion.VERSION_1_0_229_0,
timeout: Duration.minutes(5),
environment: {
POWERTOOLS_LOG_LEVEL: 'DEBUG',
NEWSLETTER_TABLE: newsletterTable.tableName,
COGNITO_USER_POOL_ID: userPool.userPoolId
}
}
)
userUnsubscriberFunction.role?.attachInlinePolicy(
new Policy(this, 'UserUnsubscriberCognitoLookup', {
statements: [
new PolicyStatement({
effect: Effect.ALLOW,
actions: ['cognito-idp:ListUsers'],
resources: [userPool.userPoolArn]
})
]
})
)
newsletterTable.grantReadWriteData(userUnsubscriberFunction)
this.emailBucket = emailBucket
this.newsletterTable = newsletterTable
this.newsletterScheduleGroup = newsletterScheduleGroup
this.createNewsletterFunction = newsletterCreatorFunction
this.userSubscriberFunction = userSubscriberFunction
this.userUnsubscriberFunction = userUnsubscriberFunction
this.getNewsletterFunction = getNewsletterFunction
/**
* CDK NAG Suppressions
*/
NagSuppressions.addResourceSuppressions(
[
newsletterCampaignCreatorFunction,
userSubscriberFunction,
userUnsubscriberFunction,
getNewsletterFunction,
emailGeneratorFunction,
emailGeneratorSchedulerInvokeRole,
newsletterCreatorFunction
],
[
{
id: 'AwsSolutions-IAM5',
reason:
'Allowing * for CloudWatch, Xray, Pinpoint App Project, Scheduler'
}
],
true
)
}
}