-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathSqsUtils.java
575 lines (531 loc) · 30.7 KB
/
SqsUtils.java
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
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates.
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package software.amazon.lambda.powertools.sqs;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.amazonaws.services.lambda.runtime.events.SQSEvent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.lambda.powertools.sqs.exception.SkippedMessageDueToFailedBatchException;
import software.amazon.lambda.powertools.sqs.internal.BatchContext;
import software.amazon.payloadoffloading.PayloadS3Pointer;
import software.amazon.lambda.powertools.sqs.internal.SqsLargeMessageAspect;
import static com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage;
import static software.amazon.lambda.powertools.sqs.internal.SqsLargeMessageAspect.processMessages;
/**
* A class of helper functions to add additional functionality to {@link SQSEvent} processing.
*/
public final class SqsUtils {
private static final Logger LOG = LoggerFactory.getLogger(SqsUtils.class);
private static final ObjectMapper objectMapper = new ObjectMapper();
private static SqsClient client;
private static S3Client s3Client;
// The attribute on an SQS-FIFO message used to record the message group ID
private static final String MESSAGE_GROUP_ID = "MessageGroupId";
private SqsUtils() {
}
/**
* This is a utility method when you want to avoid using {@code SqsLargeMessage} annotation.
* Gives you access to enriched messages from S3 in the SQS event produced via extended client lib.
* If all the large S3 payload are successfully retrieved, it will delete them from S3 post success.
*
* @param sqsEvent Event received from SQS Extended client library
* @param messageFunction Function to execute you business logic which provides access to enriched messages from S3 when needed.
* @return Return value from the function.
*/
public static <R> R enrichedMessageFromS3(final SQSEvent sqsEvent,
final Function<List<SQSMessage>, R> messageFunction) {
return enrichedMessageFromS3(sqsEvent, true, messageFunction);
}
/**
* This is a utility method when you want to avoid using {@code SqsLargeMessage} annotation.
* Gives you access to enriched messages from S3 in the SQS event produced via extended client lib.
* if all the large S3 payload are successfully retrieved, Control if it will delete payload from S3 post success.
*
* @param sqsEvent Event received from SQS Extended client library
* @param messageFunction Function to execute you business logic which provides access to enriched messages from S3 when needed.
* @return Return value from the function.
*/
public static <R> R enrichedMessageFromS3(final SQSEvent sqsEvent,
final boolean deleteS3Payload,
final Function<List<SQSMessage>, R> messageFunction) {
List<SQSMessage> sqsMessages = sqsEvent.getRecords().stream()
.map(SqsUtils::clonedMessage)
.collect(Collectors.toList());
List<PayloadS3Pointer> s3Pointers = processMessages(sqsMessages);
R returnValue = messageFunction.apply(sqsMessages);
if (deleteS3Payload) {
s3Pointers.forEach(SqsLargeMessageAspect::deleteMessage);
}
return returnValue;
}
/**
* Provides ability to set default {@link SqsClient} to be used by utility.
* If no default configuration is provided, client is instantiated via {@link SqsClient#create()}
*
* @param client {@link SqsClient} to be used by utility
*/
public static void overrideSqsClient(SqsClient client) {
SqsUtils.client = client;
}
/**
* By default, the S3Client is instantiated via {@link S3Client#create()}.
* This method provides the ability to override the S3Client with your own custom version.
*
* @param s3Client {@link S3Client} to be used by utility
*/
public static void overrideS3Client(S3Client s3Client) {
SqsUtils.s3Client = s3Client;
}
/**
* This utility method is used to process each {@link SQSMessage} inside the received {@link SQSEvent}
*
* <p>
* The Utility will call {@link SqsMessageHandler#process(SQSMessage)} method for each {@link SQSMessage}
* in the received {@link SQSEvent}
* </p>
*
* </p>
* If any exception is thrown from {@link SqsMessageHandler#process(SQSMessage)} during processing of a message,
* the utility will take care of deleting all the successful messages from SQS. When one or more single message fails
* processing due to exception thrown from {@link SqsMessageHandler#process(SQSMessage)}
* {@link SQSBatchProcessingException} is thrown with all the details of successful and failed messages.
* <p>
* If all the messages are successfully processes, No SQS messages are deleted explicitly but is rather delegated to
* Lambda execution context for deletion.
* </p>
*
* <p>
* If you dont want the utility to throw {@link SQSBatchProcessingException} in case of failures but rather suppress
* it, Refer {@link SqsUtils#batchProcessor(SQSEvent, boolean, Class)}
* </p>
*
* @param event {@link SQSEvent} received by lambda function.
* @param handler Class implementing {@link SqsMessageHandler} which will be called for each message in event.
* @return List of values returned by {@link SqsMessageHandler#process(SQSMessage)} while processing each message.
* @throws SQSBatchProcessingException if some messages fail during processing.
*/
public static <R> List<R> batchProcessor(final SQSEvent event,
final Class<? extends SqsMessageHandler<R>> handler) {
return batchProcessor(event, false, handler);
}
/**
* This utility method is used to process each {@link SQSMessage} inside the received {@link SQSEvent}
*
* <p>
* The Utility will call {@link SqsMessageHandler#process(SQSMessage)} method for each {@link SQSMessage}
* in the received {@link SQSEvent}
* </p>
* <p>
* If any exception is thrown from {@link SqsMessageHandler#process(SQSMessage)} during processing of a message,
* the utility will take care of deleting all the successful messages from SQS. When one or more single message fails
* processing due to exception thrown from {@link SqsMessageHandler#process(SQSMessage)}
* {@link SQSBatchProcessingException} is thrown with all the details of successful and failed messages.
*
* </p>
*
* <p>
* If all the messages are successfully processes, No SQS messages are deleted explicitly but is rather delegated to
* Lambda execution context for deletion.
* </p>
*
* <p>
* If you dont want the utility to throw {@link SQSBatchProcessingException} in case of failures but rather suppress
* it, Refer {@link SqsUtils#batchProcessor(SQSEvent, boolean, Class)}
* </p>
*
* <p>
* If you want certain exceptions to be treated as permanent failures, i.e. exceptions where the result of retrying will
* always be a failure and want these can be immediately moved to the dead letter queue associated to the source SQS queue,
* you can use nonRetryableExceptions parameter to configure such exceptions.
*
* Make sure function execution role has sqs:GetQueueAttributes permission on source SQS queue and sqs:SendMessage,
* sqs:SendMessageBatch permission for configured DLQ.
*
* If there is no DLQ configured on source SQS queue and {@link SqsBatch#nonRetryableExceptions()} attribute is set, if
* nonRetryableExceptions occurs from {@link SqsMessageHandler}, such exceptions will still be treated as temporary
* exceptions and the message will be moved back to source SQS queue for reprocessing. The same behaviour will occur if
* for some reason the utility is unable to move the message to the DLQ. An example of this could be because the function
* is missing the correct permissions.
* </p>
* @see <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Amazon SQS dead-letter queues</a>
* @param event {@link SQSEvent} received by lambda function.
* @param handler Class implementing {@link SqsMessageHandler} which will be called for each message in event.
* @param nonRetryableExceptions exception classes that are to be treated as permanent exceptions and to be moved
* to DLQ.
* @return List of values returned by {@link SqsMessageHandler#process(SQSMessage)} while processing each message.
* @throws SQSBatchProcessingException if some messages fail during processing.
*/
@SafeVarargs
public static <R> List<R> batchProcessor(final SQSEvent event,
final Class<? extends SqsMessageHandler<R>> handler,
final Class<? extends Exception>... nonRetryableExceptions) {
return batchProcessor(event, false, handler, nonRetryableExceptions);
}
/**
* This utility method is used to process each {@link SQSMessage} inside the received {@link SQSEvent}
*
* <p>
* The Utility will call {@link SqsMessageHandler#process(SQSMessage)} method for each {@link SQSMessage}
* in the received {@link SQSEvent}
* </p>
* </p>
* If any exception is thrown from {@link SqsMessageHandler#process(SQSMessage)} during processing of a message,
* the utility will take care of deleting all the successful messages from SQS. When one or more single message fails
* processing due to exception thrown from {@link SqsMessageHandler#process(SQSMessage)}
* {@link SQSBatchProcessingException} is thrown with all the details of successful and failed messages.
* <p>
* Exception can also be suppressed if desired.
* <p>
* If all the messages are successfully processes, No SQS messages are deleted explicitly but is rather delegated to
* Lambda execution context for deletion.
* </p>
*
* @param event {@link SQSEvent} received by lambda function.
* @param suppressException if this is set to true, No {@link SQSBatchProcessingException} is thrown even on failed
* messages.
* @param handler Class implementing {@link SqsMessageHandler} which will be called for each message in event.
* @return List of values returned by {@link SqsMessageHandler#process(SQSMessage)} while processing each message.
* @throws SQSBatchProcessingException if some messages fail during processing and no suppression enabled.
*/
public static <R> List<R> batchProcessor(final SQSEvent event,
final boolean suppressException,
final Class<? extends SqsMessageHandler<R>> handler) {
SqsMessageHandler<R> handlerInstance = instantiatedHandler(handler);
return batchProcessor(event, suppressException, handlerInstance);
}
/**
* This utility method is used to process each {@link SQSMessage} inside the received {@link SQSEvent}
*
* <p>
* The Utility will call {@link SqsMessageHandler#process(SQSMessage)} method for each {@link SQSMessage}
* in the received {@link SQSEvent}
* </p>
* <p>
* If any exception is thrown from {@link SqsMessageHandler#process(SQSMessage)} during processing of a message,
* the utility will take care of deleting all the successful messages from SQS. When one or more single message fails
* processing due to exception thrown from {@link SqsMessageHandler#process(SQSMessage)}
* {@link SQSBatchProcessingException} is thrown with all the details of successful and failed messages.
*
* </p>
*
* <p>
* If all the messages are successfully processes, No SQS messages are deleted explicitly but is rather delegated to
* Lambda execution context for deletion.
* </p>
*
* <p>
* If you dont want the utility to throw {@link SQSBatchProcessingException} in case of failures but rather suppress
* it, Refer {@link SqsUtils#batchProcessor(SQSEvent, boolean, Class)}
* </p>
*
* <p>
* If you want certain exceptions to be treated as permanent failures, i.e. exceptions where the result of retrying will
* always be a failure and want these can be immediately moved to the dead letter queue associated to the source SQS queue,
* you can use nonRetryableExceptions parameter to configure such exceptions.
*
* Make sure function execution role has sqs:GetQueueAttributes permission on source SQS queue and sqs:SendMessage,
* sqs:SendMessageBatch permission for configured DLQ.
*
* If there is no DLQ configured on source SQS queue and {@link SqsBatch#nonRetryableExceptions()} attribute is set, if
* nonRetryableExceptions occurs from {@link SqsMessageHandler}, such exceptions will still be treated as temporary
* exceptions and the message will be moved back to source SQS queue for reprocessing. The same behaviour will occur if
* for some reason the utility is unable to move the message to the DLQ. An example of this could be because the function
* is missing the correct permissions.
* </p>
* @see <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Amazon SQS dead-letter queues</a>
*
* @param event {@link SQSEvent} received by lambda function.
* @param suppressException if this is set to true, No {@link SQSBatchProcessingException} is thrown even on failed
* messages.
* @param handler Class implementing {@link SqsMessageHandler} which will be called for each message in event.
* @param nonRetryableExceptions exception classes that are to be treated as permanent exceptions and to be moved
* to DLQ.
* @return List of values returned by {@link SqsMessageHandler#process(SQSMessage)} while processing each message.
* @throws SQSBatchProcessingException if some messages fail during processing.
*/
@SafeVarargs
public static <R> List<R> batchProcessor(final SQSEvent event,
final boolean suppressException,
final Class<? extends SqsMessageHandler<R>> handler,
final Class<? extends Exception>... nonRetryableExceptions) {
SqsMessageHandler<R> handlerInstance = instantiatedHandler(handler);
return batchProcessor(event, suppressException, handlerInstance, false, nonRetryableExceptions);
}
/**
* This utility method is used to process each {@link SQSMessage} inside the received {@link SQSEvent}
*
* <p>
* The Utility will call {@link SqsMessageHandler#process(SQSMessage)} method for each {@link SQSMessage}
* in the received {@link SQSEvent}
* </p>
*
* <p>
* If any exception is thrown from {@link SqsMessageHandler#process(SQSMessage)} during processing of a message,
* the utility will take care of deleting all the successful messages from SQS. When one or more single message fails
* processing due to exception thrown from {@link SqsMessageHandler#process(SQSMessage)}
* {@link SQSBatchProcessingException} is thrown with all the details of successful and failed messages.
*
* </p>
*
* <p>
* If all the messages are successfully processes, No SQS messages are deleted explicitly but is rather delegated to
* Lambda execution context for deletion.
* </p>
*
* <p>
* If you dont want the utility to throw {@link SQSBatchProcessingException} in case of failures but rather suppress
* it, Refer {@link SqsUtils#batchProcessor(SQSEvent, boolean, Class)}
* </p>
*
* <p>
* If you want certain exceptions to be treated as permanent failures, i.e. exceptions where the result of retrying will
* always be a failure and want these can be immediately moved to the dead letter queue associated to the source SQS queue,
* you can use nonRetryableExceptions parameter to configure such exceptions.
*
* Make sure function execution role has sqs:GetQueueAttributes permission on source SQS queue and sqs:SendMessage,
* sqs:SendMessageBatch permission for configured DLQ.
*
* If you want such messages to be deleted instead, set deleteNonRetryableMessageFromQueue to true.
*
* If there is no DLQ configured on source SQS queue and {@link SqsBatch#nonRetryableExceptions()} attribute is set, if
* nonRetryableExceptions occurs from {@link SqsMessageHandler}, such exceptions will still be treated as temporary
* exceptions and the message will be moved back to source SQS queue for reprocessing. The same behaviour will occur if
* for some reason the utility is unable to move the message to the DLQ. An example of this could be because the function
* is missing the correct permissions.
* </p>
* @see <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Amazon SQS dead-letter queues</a>
* @param event {@link SQSEvent} received by lambda function.
* @param suppressException if this is set to true, No {@link SQSBatchProcessingException} is thrown even on failed
* messages.
* @param handler Class implementing {@link SqsMessageHandler} which will be called for each message in event.
* @param deleteNonRetryableMessageFromQueue If messages with nonRetryableExceptions are to be deleted from SQS queue.
* @param nonRetryableExceptions exception classes that are to be treated as permanent exceptions and to be moved
* to DLQ.
* @return List of values returned by {@link SqsMessageHandler#process(SQSMessage)} while processing each message.
* @throws SQSBatchProcessingException if some messages fail during processing.
*/
@SafeVarargs
public static <R> List<R> batchProcessor(final SQSEvent event,
final boolean suppressException,
final Class<? extends SqsMessageHandler<R>> handler,
final boolean deleteNonRetryableMessageFromQueue,
final Class<? extends Exception>... nonRetryableExceptions) {
SqsMessageHandler<R> handlerInstance = instantiatedHandler(handler);
return batchProcessor(event, suppressException, handlerInstance, deleteNonRetryableMessageFromQueue, nonRetryableExceptions);
}
/**
* This utility method is used to process each {@link SQSMessage} inside the received {@link SQSEvent}
*
* <p>
* The Utility will call {@link SqsMessageHandler#process(SQSMessage)} method for each {@link SQSMessage}
* in the received {@link SQSEvent}
* </p>
*
* </p>
* If any exception is thrown from {@link SqsMessageHandler#process(SQSMessage)} during processing of a messages,
* Utility will take care of deleting all the successful messages from SQS. When one or more single message fails
* processing due to exception thrown from {@link SqsMessageHandler#process(SQSMessage)}
* {@link SQSBatchProcessingException} is thrown with all the details of successful and failed messages.
* <p>
* If all the messages are successfully processes, No SQS messages are deleted explicitly but is rather delegated to
* Lambda execution context for deletion.
* </p>
*
* <p>
* If you dont want the utility to throw {@link SQSBatchProcessingException} in case of failures but rather suppress
* it, Refer {@link SqsUtils#batchProcessor(SQSEvent, boolean, SqsMessageHandler)}
* </p>
*
* @param event {@link SQSEvent} received by lambda function.
* @param handler Instance of class implementing {@link SqsMessageHandler} which will be called for each message in event.
* @return List of values returned by {@link SqsMessageHandler#process(SQSMessage)} while processing each message-
* @throws SQSBatchProcessingException if some messages fail during processing.
*/
public static <R> List<R> batchProcessor(final SQSEvent event,
final SqsMessageHandler<R> handler) {
return batchProcessor(event, false, handler);
}
/**
* This utility method is used to process each {@link SQSMessage} inside the received {@link SQSEvent}
*
* <p>
* The Utility will call {@link SqsMessageHandler#process(SQSMessage)} method for each {@link SQSMessage}
* in the received {@link SQSEvent}
* </p>
*
* <p>
* If any exception is thrown from {@link SqsMessageHandler#process(SQSMessage)} during processing of a message,
* the utility will take care of deleting all the successful messages from SQS. When one or more single message fails
* processing due to exception thrown from {@link SqsMessageHandler#process(SQSMessage)}
* {@link SQSBatchProcessingException} is thrown with all the details of successful and failed messages.
*
* </p>
*
* <p>
* If all the messages are successfully processes, No SQS messages are deleted explicitly but is rather delegated to
* Lambda execution context for deletion.
* </p>
*
* <p>
* If you dont want the utility to throw {@link SQSBatchProcessingException} in case of failures but rather suppress
* it, Refer {@link SqsUtils#batchProcessor(SQSEvent, boolean, Class)}
* </p>
*
* <p>
* If you want certain exceptions to be treated as permanent failures, i.e. exceptions where the result of retrying will
* always be a failure and want these can be immediately moved to the dead letter queue associated to the source SQS queue,
* you can use nonRetryableExceptions parameter to configure such exceptions.
*
* Make sure function execution role has sqs:GetQueueAttributes permission on source SQS queue and sqs:SendMessage,
* sqs:SendMessageBatch permission for configured DLQ.
*
* If there is no DLQ configured on source SQS queue and {@link SqsBatch#nonRetryableExceptions()} attribute is set, if
* nonRetryableExceptions occurs from {@link SqsMessageHandler}, such exceptions will still be treated as temporary
* exceptions and the message will be moved back to source SQS queue for reprocessing.The same behaviour will occur if
* for some reason the utility is unable to moved the message to the DLQ. An example of this could be because the function
* is missing the correct permissions.
* </p>
* @see <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Amazon SQS dead-letter queues</a>
* @param event {@link SQSEvent} received by lambda function.
* @param handler Instance of class implementing {@link SqsMessageHandler} which will be called for each message in event.
* @param nonRetryableExceptions exception classes that are to be treated as permanent exceptions and to be moved
* to DLQ.
* @return List of values returned by {@link SqsMessageHandler#process(SQSMessage)} while processing each message.
* @throws SQSBatchProcessingException if some messages fail during processing.
*/
@SafeVarargs
public static <R> List<R> batchProcessor(final SQSEvent event,
final SqsMessageHandler<R> handler,
final Class<? extends Exception>... nonRetryableExceptions) {
return batchProcessor(event, false, handler, false, nonRetryableExceptions);
}
/**
* This utility method is used to process each {@link SQSMessage} inside the received {@link SQSEvent}
*
* <p>
* The Utility will call {@link SqsMessageHandler#process(SQSMessage)} method for each {@link SQSMessage}
* in the received {@link SQSEvent}
* </p>
*
* </p>
* If any exception is thrown from {@link SqsMessageHandler#process(SQSMessage)} during processing of a messages,
* the utility will take care of deleting all the successful messages from SQS. When one or more single message fails
* processing due to exception thrown from {@link SqsMessageHandler#process(SQSMessage)}
* {@link SQSBatchProcessingException} is thrown with all the details of successful and failed messages.
* <p>
* Exception can also be suppressed if desired.
* <p>
* If all the messages are successfully processes, No SQS messages are deleted explicitly but is rather delegated to
* Lambda execution context for deletion.
* </p>
*
* @param event {@link SQSEvent} received by lambda function.
* @param suppressException if this is set to true, No {@link SQSBatchProcessingException} is thrown even on failed
* messages.
* @param handler Instance of class implementing {@link SqsMessageHandler} which will be called for each message in event.
* @return List of values returned by {@link SqsMessageHandler#process(SQSMessage)} while processing each message.
* @throws SQSBatchProcessingException if some messages fail during processing and no suppression enabled.
*/
public static <R> List<R> batchProcessor(final SQSEvent event,
final boolean suppressException,
final SqsMessageHandler<R> handler) {
return batchProcessor(event, suppressException, handler, false);
}
@SafeVarargs
public static <R> List<R> batchProcessor(final SQSEvent event,
final boolean suppressException,
final SqsMessageHandler<R> handler,
final boolean deleteNonRetryableMessageFromQueue,
final Class<? extends Exception>... nonRetryableExceptions) {
final List<R> handlerReturn = new ArrayList<>();
if(client == null) {
client = SqsClient.create();
}
BatchContext batchContext = new BatchContext(client);
Queue<SQSMessage> messagesToProcess = new LinkedList<>(event.getRecords());
while (!messagesToProcess.isEmpty()) {
SQSMessage message = messagesToProcess.remove();
// If the batch hasn't failed, try process the message
try {
handlerReturn.add(handler.process(message));
batchContext.addSuccess(message);
} catch(Exception e){
// Record the failure
batchContext.addFailure(message, e);
// If we are trying to process a message that has a messageGroupId, we are on a FIFO queue. A failure
// now stops us from processing the rest of the batch; we break out of the loop leaving unprocessed
// messages in the queue
// https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html#services-sqs-batchfailurereporting
String messageGroupId = message.getAttributes() != null ?
message.getAttributes().get(MESSAGE_GROUP_ID) : null;
if (messageGroupId != null) {
LOG.info("A message in a message batch with messageGroupId {} and messageId {} failed; failing the rest of the batch too"
, messageGroupId, message.getMessageId());
break;
}
LOG.error("Encountered issue processing message: {}", message.getMessageId(), e);
}
}
// If we have a FIFO batch failure, unprocessed messages will remain on the queue
// past the failed message. We have to add these to the errors
messagesToProcess.forEach(message -> {
LOG.info("Skipping message {} as another message with a message group failed in this batch",
message.getMessageId());
batchContext.addFailure(message, new SkippedMessageDueToFailedBatchException());
});
batchContext.processSuccessAndHandleFailed(handlerReturn, suppressException, deleteNonRetryableMessageFromQueue, nonRetryableExceptions);
return handlerReturn;
}
private static <R> SqsMessageHandler<R> instantiatedHandler(final Class<? extends SqsMessageHandler<R>> handler) {
try {
if (null == handler.getDeclaringClass()) {
return handler.getDeclaredConstructor().newInstance();
}
final Constructor<? extends SqsMessageHandler<R>> constructor = handler.getDeclaredConstructor(handler.getDeclaringClass());
constructor.setAccessible(true);
return constructor.newInstance(handler.getDeclaringClass().getDeclaredConstructor().newInstance());
} catch (Exception e) {
LOG.error("Failed creating handler instance", e);
throw new RuntimeException("Unexpected error occurred. Please raise issue at " +
"https://github.com/aws-powertools/powertools-lambda-java/issues", e);
}
}
private static SQSMessage clonedMessage(final SQSMessage sqsMessage) {
try {
return objectMapper
.readValue(objectMapper.writeValueAsString(sqsMessage), SQSMessage.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public static ObjectMapper objectMapper() {
return objectMapper;
}
public static S3Client s3Client() {
if(null == s3Client) {
SqsUtils.s3Client = S3Client.create();
}
return s3Client;
}
}