-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathtextract-pipeline-stack.ts
326 lines (294 loc) · 12.2 KB
/
textract-pipeline-stack.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
import * as cdk from 'aws-cdk-lib';
import events = require('aws-cdk-lib/aws-events');
import iam = require('aws-cdk-lib/aws-iam');
import { S3EventSource, SqsEventSource, SnsEventSource, DynamoEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
import sns = require('aws-cdk-lib/aws-sns');
import snsSubscriptions = require("aws-cdk-lib/aws-sns-subscriptions");
import sqs = require('aws-cdk-lib/aws-sqs');
import dynamodb = require('aws-cdk-lib/aws-dynamodb');
import lambda = require('aws-cdk-lib/aws-lambda');
import s3 = require('aws-cdk-lib/aws-s3');
import {LambdaFunction} from "aws-cdk-lib/aws-events-targets";
import { Construct } from 'constructs';
export class TextractPipelineStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// The code that defines your stack goes here
//**********SNS Topics******************************
const jobCompletionTopic = new sns.Topic(this, 'JobCompletion');
//**********IAM Roles******************************
const textractServiceRole = new iam.Role(this, 'TextractServiceRole', {
assumedBy: new iam.ServicePrincipal('textract.amazonaws.com')
});
textractServiceRole.addToPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
resources: [jobCompletionTopic.topicArn],
actions: ["sns:Publish"]
})
);
//**********S3 Batch Operations Role******************************
const s3BatchOperationsRole = new iam.Role(this, 'S3BatchOperationsRole', {
assumedBy: new iam.ServicePrincipal('batchoperations.s3.amazonaws.com')
});
//**********S3 Bucket******************************
//S3 bucket for input documents and output
const contentBucket = new s3.Bucket(this, 'DocumentsBucket', { versioned: false});
const existingContentBucket = new s3.Bucket(this, 'ExistingDocumentsBucket', { versioned: false});
existingContentBucket.grantReadWrite(s3BatchOperationsRole)
const inventoryAndLogsBucket = new s3.Bucket(this, 'InventoryAndLogsBucket', { versioned: false});
inventoryAndLogsBucket.grantReadWrite(s3BatchOperationsRole)
//**********DynamoDB Table*************************
//DynamoDB table with links to output in S3
const outputTable = new dynamodb.Table(this, 'OutputTable', {
partitionKey: { name: 'documentId', type: dynamodb.AttributeType.STRING },
sortKey: { name: 'outputType', type: dynamodb.AttributeType.STRING }
});
//DynamoDB table with links to output in S3
const documentsTable = new dynamodb.Table(this, 'DocumentsTable', {
partitionKey: { name: 'documentId', type: dynamodb.AttributeType.STRING },
stream: dynamodb.StreamViewType.NEW_IMAGE
});
//**********SQS Queues*****************************
//DLQ
const dlq = new sqs.Queue(this, 'DLQ', {
visibilityTimeout: cdk.Duration.seconds(30), retentionPeriod: cdk.Duration.seconds(1209600)
});
//Input Queue for sync jobs
const syncJobsQueue = new sqs.Queue(this, 'SyncJobs', {
visibilityTimeout: cdk.Duration.seconds(30), retentionPeriod: cdk.Duration.seconds(1209600), deadLetterQueue : { queue: dlq, maxReceiveCount: 50}
});
//Input Queue for async jobs
const asyncJobsQueue = new sqs.Queue(this, 'AsyncJobs', {
visibilityTimeout: cdk.Duration.seconds(30), retentionPeriod: cdk.Duration.seconds(1209600), deadLetterQueue : { queue: dlq, maxReceiveCount: 50}
});
//Queue
const jobResultsQueue = new sqs.Queue(this, 'JobResults', {
visibilityTimeout: cdk.Duration.seconds(900), retentionPeriod: cdk.Duration.seconds(1209600), deadLetterQueue : { queue: dlq, maxReceiveCount: 50}
});
//Trigger
//jobCompletionTopic.subscribeQueue(jobResultsQueue);
jobCompletionTopic.addSubscription(
new snsSubscriptions.SqsSubscription(jobResultsQueue)
);
//**********Lambda Functions******************************
// Helper Layer with helper functions
const helperLayer = new lambda.LayerVersion(this, 'HelperLayer', {
code: lambda.Code.fromAsset('lambda/helper'),
compatibleRuntimes: [lambda.Runtime.PYTHON_3_7],
license: 'Apache-2.0',
description: 'Helper layer.',
});
// Textractor helper layer
const textractorLayer = new lambda.LayerVersion(this, 'Textractor', {
code: lambda.Code.fromAsset('lambda/textractor'),
compatibleRuntimes: [lambda.Runtime.PYTHON_3_7],
license: 'Apache-2.0',
description: 'Textractor layer.',
});
//------------------------------------------------------------
// S3 Event processor
const s3Processor = new lambda.Function(this, 'S3Processor', {
runtime: lambda.Runtime.PYTHON_3_7,
code: lambda.Code.fromAsset('lambda/s3processor'),
handler: 'lambda_function.lambda_handler',
timeout: cdk.Duration.seconds(30),
environment: {
SYNC_QUEUE_URL: syncJobsQueue.queueUrl,
ASYNC_QUEUE_URL: asyncJobsQueue.queueUrl,
DOCUMENTS_TABLE: documentsTable.tableName,
OUTPUT_TABLE: outputTable.tableName
}
});
//Layer
s3Processor.addLayers(helperLayer)
//Trigger
s3Processor.addEventSource(new S3EventSource(contentBucket, {
events: [ s3.EventType.OBJECT_CREATED ],
filters: [ { suffix: '.pdf' }]
}));
s3Processor.addEventSource(new S3EventSource(contentBucket, {
events: [ s3.EventType.OBJECT_CREATED ],
filters: [ { suffix: '.png' }]
}));
s3Processor.addEventSource(new S3EventSource(contentBucket, {
events: [ s3.EventType.OBJECT_CREATED ],
filters: [ { suffix: '.jpg' }]
}));
s3Processor.addEventSource(new S3EventSource(contentBucket, {
events: [ s3.EventType.OBJECT_CREATED ],
filters: [ { suffix: '.jpeg' }]
}));
//Permissions
documentsTable.grantReadWriteData(s3Processor)
syncJobsQueue.grantSendMessages(s3Processor)
asyncJobsQueue.grantSendMessages(s3Processor)
//------------------------------------------------------------
// S3 Batch Operations Event processor
const s3BatchProcessor = new lambda.Function(this, 'S3BatchProcessor', {
runtime: lambda.Runtime.PYTHON_3_7,
code: lambda.Code.fromAsset('lambda/s3batchprocessor'),
handler: 'lambda_function.lambda_handler',
timeout: cdk.Duration.seconds(30),
environment: {
DOCUMENTS_TABLE: documentsTable.tableName,
OUTPUT_TABLE: outputTable.tableName
},
reservedConcurrentExecutions: 1,
});
//Layer
s3BatchProcessor.addLayers(helperLayer)
//Permissions
documentsTable.grantReadWriteData(s3BatchProcessor)
s3BatchProcessor.grantInvoke(s3BatchOperationsRole)
s3BatchOperationsRole.addToPolicy(
new iam.PolicyStatement({
actions: ["lambda:*"],
resources: ["*"]
})
);
//------------------------------------------------------------
// Document processor (Router to Sync/Async Pipeline)
const documentProcessor = new lambda.Function(this, 'TaskProcessor', {
runtime: lambda.Runtime.PYTHON_3_7,
code: lambda.Code.fromAsset('lambda/documentprocessor'),
handler: 'lambda_function.lambda_handler',
timeout: cdk.Duration.seconds(900),
environment: {
SYNC_QUEUE_URL: syncJobsQueue.queueUrl,
ASYNC_QUEUE_URL: asyncJobsQueue.queueUrl
}
});
//Layer
documentProcessor.addLayers(helperLayer)
//Trigger
documentProcessor.addEventSource(new DynamoEventSource(documentsTable, {
startingPosition: lambda.StartingPosition.TRIM_HORIZON
}));
//Permissions
documentsTable.grantReadWriteData(documentProcessor)
syncJobsQueue.grantSendMessages(documentProcessor)
asyncJobsQueue.grantSendMessages(documentProcessor)
//------------------------------------------------------------
// Sync Jobs Processor (Process jobs using sync APIs)
const syncProcessor = new lambda.Function(this, 'SyncProcessor', {
runtime: lambda.Runtime.PYTHON_3_7,
code: lambda.Code.fromAsset('lambda/syncprocessor'),
handler: 'lambda_function.lambda_handler',
reservedConcurrentExecutions: 1,
timeout: cdk.Duration.seconds(25),
environment: {
OUTPUT_TABLE: outputTable.tableName,
DOCUMENTS_TABLE: documentsTable.tableName,
AWS_DATA_PATH : "models"
}
});
//Layer
syncProcessor.addLayers(helperLayer)
syncProcessor.addLayers(textractorLayer)
//Trigger
syncProcessor.addEventSource(new SqsEventSource(syncJobsQueue, {
batchSize: 1
}));
//Permissions
contentBucket.grantReadWrite(syncProcessor)
existingContentBucket.grantReadWrite(syncProcessor)
outputTable.grantReadWriteData(syncProcessor)
documentsTable.grantReadWriteData(syncProcessor)
syncProcessor.addToRolePolicy(
new iam.PolicyStatement({
actions: ["textract:*"],
resources: ["*"]
})
);
//------------------------------------------------------------
// Async Job Processor (Start jobs using Async APIs)
const asyncProcessor = new lambda.Function(this, 'ASyncProcessor', {
runtime: lambda.Runtime.PYTHON_3_7,
code: lambda.Code.fromAsset('lambda/asyncprocessor'),
handler: 'lambda_function.lambda_handler',
reservedConcurrentExecutions: 1,
timeout: cdk.Duration.seconds(60),
environment: {
ASYNC_QUEUE_URL: asyncJobsQueue.queueUrl,
SNS_TOPIC_ARN : jobCompletionTopic.topicArn,
SNS_ROLE_ARN : textractServiceRole.roleArn,
AWS_DATA_PATH : "models"
}
});
//asyncProcessor.addEnvironment("SNS_TOPIC_ARN", textractServiceRole.topicArn)
//Layer
asyncProcessor.addLayers(helperLayer)
//Triggers
// Run async job processor every 5 minutes
//Enable code below after test deploy
const rule = new events.Rule(this, 'Rule', {
schedule: events.Schedule.expression('rate(2 minutes)')
});
rule.addTarget(new LambdaFunction(asyncProcessor));
//Run when a job is successfully complete
asyncProcessor.addEventSource(new SnsEventSource(jobCompletionTopic))
//Permissions
contentBucket.grantRead(asyncProcessor)
existingContentBucket.grantReadWrite(asyncProcessor)
asyncJobsQueue.grantConsumeMessages(asyncProcessor)
asyncProcessor.addToRolePolicy(
new iam.PolicyStatement({
actions: ["iam:PassRole"],
resources: [textractServiceRole.roleArn]
})
);
asyncProcessor.addToRolePolicy(
new iam.PolicyStatement({
actions: ["textract:*"],
resources: ["*"]
})
);
//------------------------------------------------------------
// Async Jobs Results Processor
const jobResultProcessor = new lambda.Function(this, 'JobResultProcessor', {
runtime: lambda.Runtime.PYTHON_3_7,
code: lambda.Code.fromAsset('lambda/jobresultprocessor'),
handler: 'lambda_function.lambda_handler',
memorySize: 2000,
reservedConcurrentExecutions: 50,
timeout: cdk.Duration.seconds(900),
environment: {
OUTPUT_TABLE: outputTable.tableName,
DOCUMENTS_TABLE: documentsTable.tableName,
AWS_DATA_PATH : "models"
}
});
//Layer
jobResultProcessor.addLayers(helperLayer)
jobResultProcessor.addLayers(textractorLayer)
//Triggers
jobResultProcessor.addEventSource(new SqsEventSource(jobResultsQueue, {
batchSize: 1
}));
//Permissions
outputTable.grantReadWriteData(jobResultProcessor)
documentsTable.grantReadWriteData(jobResultProcessor)
contentBucket.grantReadWrite(jobResultProcessor)
existingContentBucket.grantReadWrite(jobResultProcessor)
jobResultProcessor.addToRolePolicy(
new iam.PolicyStatement({
actions: ["textract:*"],
resources: ["*"]
})
);
//--------------
// PDF Generator
const pdfGenerator = new lambda.Function(this, 'PdfGenerator', {
runtime: lambda.Runtime.JAVA_8,
code: lambda.Code.fromAsset('lambda/pdfgenerator'),
handler: 'DemoLambdaV2::handleRequest',
memorySize: 3000,
timeout: cdk.Duration.seconds(900),
});
contentBucket.grantReadWrite(pdfGenerator)
existingContentBucket.grantReadWrite(pdfGenerator)
pdfGenerator.grantInvoke(syncProcessor)
pdfGenerator.grantInvoke(asyncProcessor)
}
}