+ * 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.
+ *
+ * Exception can also be suppressed if desired.
+ *
+ * If all the messages are successfully processes, No SQS messages are deleted explicitly but is rather delegated to
+ * Lambda execution context for deletion.
+ *
+ *
+ * @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 List batchProcessor(final SQSEvent event,
final boolean suppressException,
@@ -125,10 +165,32 @@ public static List batchProcessor(final SQSEvent event,
}
/**
- * @param event
- * @param handler
- * @param
- * @return
+ * This utility method is used to processes each {@link SQSMessage} inside received {@link SQSEvent}
+ *
+ *
+ * Utility will take care of calling {@link SqsMessageHandler#process(SQSMessage)} method for each {@link SQSMessage}
+ * in the received {@link SQSEvent}
+ *
+ *
+ *
+ * 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.
+ *
+ * If all the messages are successfully processes, No SQS messages are deleted explicitly but is rather delegated to
+ * Lambda execution context for deletion.
+ *
+ *
+ *
+ * If you dont want to utility to throw {@link SQSBatchProcessingException} in case of failures but rather suppress
+ * it, Refer {@link PowertoolsSqs#batchProcessor(SQSEvent, boolean, SqsMessageHandler)}
+ *
+ *
+ * @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 List batchProcessor(final SQSEvent event,
final SqsMessageHandler handler) {
@@ -136,11 +198,31 @@ public static List batchProcessor(final SQSEvent event,
}
/**
- * @param event
- * @param suppressException
- * @param handler
- * @param
- * @return
+ * This utility method is used to processes each {@link SQSMessage} inside received {@link SQSEvent}
+ *
+ *
+ * Utility will take care of calling {@link SqsMessageHandler#process(SQSMessage)} method for each {@link SQSMessage}
+ * in the received {@link SQSEvent}
+ *
+ *
+ *
+ * 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.
+ *
+ * Exception can also be suppressed if desired.
+ *
+ * If all the messages are successfully processes, No SQS messages are deleted explicitly but is rather delegated to
+ * Lambda execution context for deletion.
+ *
+ *
+ * @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 List batchProcessor(final SQSEvent event,
final boolean suppressException,
@@ -158,12 +240,7 @@ public static List batchProcessor(final SQSEvent event,
}
}
- try {
- batchContext.processSuccessAndReset(suppressException);
- } catch (SQSBatchProcessingException e) {
- e.addSuccessMessageReturnValues(handlerReturn);
- throw e;
- }
+ batchContext.processSuccessAndHandleFailed(handlerReturn, suppressException);
return handlerReturn;
}
diff --git a/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/SQSBatchProcessingException.java b/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/SQSBatchProcessingException.java
index 984e25038..38a9c943d 100644
--- a/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/SQSBatchProcessingException.java
+++ b/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/SQSBatchProcessingException.java
@@ -5,19 +5,34 @@
import com.amazonaws.services.lambda.runtime.events.SQSEvent;
+import static com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage;
import static java.util.stream.Collectors.joining;
/**
+ *
+ * When one or more {@link SQSMessage} fails and if any exception is thrown from {@link SqsMessageHandler#process(SQSMessage)}
+ * during processing of a messages, this exception is with all the details of successful and failed messages.
+ *
+ *
*/
public class SQSBatchProcessingException extends RuntimeException {
private final List exceptions;
- private final List failures;
+ private final List failures;
private final List returnValues;
public SQSBatchProcessingException(final List exceptions,
- final List failures,
+ final List failures,
final List successReturns) {
super(exceptions.stream()
.map(Throwable::toString)
@@ -28,15 +43,27 @@ public SQSBatchProcessingException(final List exceptions,
this.returnValues = new ArrayList<>(successReturns);
}
+ /**
+ * Details for exceptions that occurred while processing messages in {@link SqsMessageHandler#process(SQSMessage)}
+ * @return List of exceptions that occurred while processing messages
+ */
public List getExceptions() {
return exceptions;
}
+ /**
+ * List of returns from {@link SqsMessageHandler#process(SQSMessage)} that were successfully processed.
+ * @return List of returns from successfully processed messages
+ */
public List successMessageReturnValues() {
return returnValues;
}
- public List getFailures() {
+ /**
+ * Details of {@link SQSMessage} that failed in {@link SqsMessageHandler#process(SQSMessage)}
+ * @return List of failed messages
+ */
+ public List getFailures() {
return failures;
}
@@ -46,8 +73,4 @@ public void printStackTrace() {
exception.printStackTrace();
}
}
-
- void addSuccessMessageReturnValues(final List returnValues) {
- this.returnValues.addAll(returnValues);
- }
}
diff --git a/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/SqsBatchProcessor.java b/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/SqsBatchProcessor.java
index 3a8768ff4..342765052 100644
--- a/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/SqsBatchProcessor.java
+++ b/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/SqsBatchProcessor.java
@@ -5,8 +5,52 @@
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
+import com.amazonaws.services.lambda.runtime.events.SQSEvent;
+
+import static com.amazonaws.services.lambda.runtime.events.SQSEvent.*;
+
/**
+ * {@link SqsBatchProcessor} is used to process batch messages in {@link SQSEvent}
+ *
+ *
+ * When using the annotation, implementation of {@link SqsMessageHandler} is required. Annotation will take care of
+ * calling {@link SqsMessageHandler#process(SQSMessage)} method for each {@link SQSMessage} in the received {@link SQSEvent}
+ *
+ *
+ *
+ * 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)}, Lambda execution will fail
+ * with {@link SQSBatchProcessingException}.
+ *
+ * If all the messages are successfully processes, No SQS messages are deleted explicitly but is rather delegated to
+ * Lambda execution context for deletion.
+ *
+ *
+ *
+ * If you want to suppress the exception even if any message in batch fails, set
+ * {@link SqsBatchProcessor#suppressException()} to true. By default its value is false
+ *
+ *
+ * @param Return value type from {@link SqsMessageHandler#process(SQSMessage)}
*/
@FunctionalInterface
public interface SqsMessageHandler {
diff --git a/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/internal/BatchContext.java b/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/internal/BatchContext.java
index 54942f1ca..eca4be3b8 100644
--- a/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/internal/BatchContext.java
+++ b/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/internal/BatchContext.java
@@ -1,6 +1,5 @@
package software.amazon.lambda.powertools.sqs.internal;
-import java.awt.geom.Area;
import java.util.ArrayList;
import java.util.List;
@@ -37,21 +36,21 @@ public void addFailure(SQSMessage event, Exception e) {
exceptions.add(e);
}
- public void processSuccessAndReset(final boolean suppressException) {
- try {
- if (hasFailures()) {
+ public void processSuccessAndHandleFailed(final List successReturns,
+ final boolean suppressException) {
+ if (hasFailures()) {
+ deleteSuccessMessage();
- deleteSuccessMessage();
+ if (suppressException) {
+ List messageIds = failures.stream().
+ map(SQSMessage::getMessageId)
+ .collect(toList());
- if (suppressException) {
- List messageIds = failures.stream().map(SQSMessage::getMessageId).collect(toList());
- LOG.debug(format("[%s] records failed processing, but exceptions are suppressed. Failed messages %s", failures.size(), messageIds));
- } else {
- throw new SQSBatchProcessingException(exceptions, failures, new ArrayList());
- }
+ LOG.debug(format("[%s] records failed processing, but exceptions are suppressed. " +
+ "Failed messages %s", failures.size(), messageIds));
+ } else {
+ throw new SQSBatchProcessingException(exceptions, failures, successReturns);
}
- } finally {
- reset();
}
}
@@ -81,10 +80,4 @@ private String url() {
.build())
.queueUrl();
}
-
- private void reset() {
- success.clear();
- failures.clear();
- exceptions.clear();
- }
}
From 145174b676eecf877d45d826b9369655cfab0bf5 Mon Sep 17 00:00:00 2001
From: Pankaj Agrawal
Date: Sun, 4 Oct 2020 12:12:25 +0200
Subject: [PATCH 07/12] public docs update
---
docs/content/utilities/batch.mdx | 251 ++++++++++++++++++
.../utilities/sqs_large_message_handling.mdx | 6 +-
docs/gatsby-config.js | 3 +-
3 files changed, 256 insertions(+), 4 deletions(-)
create mode 100644 docs/content/utilities/batch.mdx
diff --git a/docs/content/utilities/batch.mdx b/docs/content/utilities/batch.mdx
new file mode 100644
index 000000000..babe709e9
--- /dev/null
+++ b/docs/content/utilities/batch.mdx
@@ -0,0 +1,251 @@
+---
+title: SQS Batch Processing
+description: Utility
+---
+
+import Note from "../../src/components/Note"
+
+The SQS batch processing utility provides a way to handle partial failures when processing batches of messages from SQS.
+
+**Key Features**
+
+* Prevent successfully processed messages from being returned to SQS
+* A simple interface for individually processing messages from a batch
+
+**Background**
+
+When using SQS as a Lambda event source mapping, Lambda functions are triggered with a batch of messages from SQS.
+
+If your function fails to process any message from the batch, the entire batch returns to your SQS queue, and your Lambda function is triggered with the same batch one more time.
+
+With this utility, messages within a batch are handled individually - only messages that were not successfully processed
+are returned to the queue.
+
+
+ While this utility lowers the chance of processing messages more than once, it is not guaranteed. We recommend implementing processing logic in an idempotent manner wherever possible.
+
+ More details on how Lambda works with SQS can be found in the AWS documentation
+
+
+## Install
+
+To install this utility, add the following dependency to your project.
+
+```xml
+
+ software.amazon.lambda
+ powertools-sqs
+ 0.4.0-beta
+
+```
+
+And configure the aspectj-maven-plugin to compile-time weave (CTW) the
+aws-lambda-powertools-java aspects into your project. You may already have this
+plugin in your pom. In that case add the dependency to the `aspectLibraries`
+section.
+
+```xml
+
+
+ ...
+
+ org.codehaus.mojo
+ aspectj-maven-plugin
+ 1.11
+
+ 1.8
+ 1.8
+ 1.8
+
+
+
+ software.amazon.lambda
+ powertools-sqs
+
+
+
+
+
+
+
+ compile
+
+
+
+
+ ...
+
+
+```
+
+**IAM Permissions**
+
+This utility requires additional permissions to work as expected. Lambda functions using this utility require the `sqs:GetQueueUrl` and `sqs:DeleteMessageBatch` permission.
+
+## Processing messages from SQS
+
+You can use either **[SqsBatchProcessor annotation](#SqsBatchProcessor annotation)**, or **[PowertoolsSqs Utility API](#PowertoolsSqs Utility API)** as a fluent API.
+
+Both have nearly the same behaviour when it comes to processing messages from the batch:
+
+* **Entire batch has been successfully processed**, where your Lambda handler returned successfully, we will let SQS delete the batch to optimize your cost
+* **Entire Batch has been partially processed successfully**, where exceptions were raised within your `SqsMessageHandler` interface implementation, we will:
+ - **1)** Delete successfully processed messages from the queue by directly calling `sqs:DeleteMessageBatch`
+ - **2)** Raise `SQSBatchProcessingException` to ensure failed messages return to your SQS queue
+
+The only difference is that **PowertoolsSqs Utility API** will give you access to return from the processed messages if you need. Exception `SQSBatchProcessingException` thrown from the
+utility will have access to both successful and failed messaged along with failure exceptions.
+
+## Functional Interface SqsMessageHandler
+
+Both [annotation](#SqsBatchProcessor annotation) and [PowertoolsSqs Utility API](#PowertoolsSqs Utility API) requires an implementation of functional interface `SqsMessageHandler`.
+
+This implementation is responsible for processing each individual message from the batch, and to raise an exception if unable to process any of the messages sent.
+
+**Any non-exception/successful return from your record handler function** will instruct utility to queue up each individual message for deletion.
+
+### SqsBatchProcessor annotation
+
+When using this annotation, you need provide a class implementation of `SqsMessageHandler` that will process individual messages from the batch - It should raise an exception if it is unable to process the record.
+
+All records in the batch will be passed to this handler for processing, even if exceptions are thrown - Here's the behaviour after completing the batch:
+
+* **Any successfully processed messages**, we will delete them from the queue via `sqs:DeleteMessageBatch`
+* **Any unprocessed messages detected**, we will raise `SQSBatchProcessingException` to ensure failed messages return to your SQS queue
+
+
+ You will not have accessed to the processed messages within the Lambda Handler - all processing logic will and should be performed by the implemented SqsMessageHandler#process() function.
+
+
+
+```java:title=App.java
+public class AppSqsEvent implements RequestHandler {
+ @Override
+ @SqsBatchProcessor(SampleMessageHandler.class) // highlight-line
+ public String handleRequest(SQSEvent input, Context context) {
+ return "{\"statusCode\": 200}";
+ }
+
+ public class SampleMessageHandler implements SqsMessageHandler {
+
+ @Override
+ public String process(SQSMessage message) {
+ // This will be called for each individual message from a batch
+ // It should raise an exception if the message was not processed successfully
+ String returnVal = doSomething(message.getBody());
+ return returnVal;
+ }
+ }
+}
+```
+
+### PowertoolsSqs Utility API
+
+If you require access to the result of processed messages, you can use this utility.
+
+The result from calling PowertoolsSqs#batchProcessor() on the context manager will be a list of all the return values from your SqsMessageHandler#process() function.
+
+```java:title=App.java
+public class AppSqsEvent implements RequestHandler> {
+ @Override
+ public List handleRequest(SQSEvent input, Context context) {
+ List returnValues = PowertoolsSqs.batchProcessor(input, SampleMessageHandler.class); // highlight-line
+
+ return returnValues;
+ }
+
+ public class SampleMessageHandler implements SqsMessageHandler {
+
+ @Override
+ public String process(SQSMessage message) {
+ // This will be called for each individual message from a batch
+ // It should raise an exception if the message was not processed successfully
+ String returnVal = doSomething(message.getBody());
+ return returnVal;
+ }
+ }
+}
+```
+
+You can also use the utility in a more functional way` by providing inline implementation of functional interface SqsMessageHandler#process()
+
+```java:title=App.java
+public class AppSqsEvent implements RequestHandler> {
+
+ @Override
+ public List handleRequest(SQSEvent input, Context context) {
+ // highlight-start
+ List returnValues = PowertoolsSqs.batchProcessor(input, (message) -> {
+ // This will be called for each individual message from a batch
+ // It should raise an exception if the message was not processed successfully
+ String returnVal = doSomething(message.getBody());
+ return returnVal;
+ });
+ // highlight-end
+
+ return returnValues;
+ }
+}
+```
+
+## Passing custom SqsClient
+
+If you need to pass custom SqsClient such as region to the SDK, you can pass your own `SqsClient` to be used by utility either for
+**[SqsBatchProcessor annotation](#SqsBatchProcessor annotation)**, or **[PowertoolsSqs Utility API](#PowertoolsSqs Utility API)**.
+
+```java:title=App.java
+
+public class AppSqsEvent implements RequestHandler> {
+ // highlight-start
+ static {
+ PowertoolsSqs.defaultSqsClient(SqsClient.builder()
+ .build());
+ }
+ // highlight-end
+
+ @Override
+ public List handleRequest(SQSEvent input, Context context) {
+ List returnValues = PowertoolsSqs.batchProcessor(input, SampleMessageHandler.class);
+
+ return returnValues;
+ }
+
+ public class SampleMessageHandler implements SqsMessageHandler {
+
+ @Override
+ public String process(SQSMessage message) {
+ // This will be called for each individual message from a batch
+ // It should raise an exception if the message was not processed successfully
+ String returnVal = doSomething(message.getBody());
+ return returnVal;
+ }
+ }
+}
+
+```
+
+## Suppressing exceptions
+
+If you want to disable the default behavior where `SQSBatchProcessingException` is raised if there are any exception, you can pass the `suppressException` boolean argument.
+
+**Within SqsBatchProcessor annotation**
+
+```java:title=App.java
+...
+ @Override
+ @SqsBatchProcessor(value = SampleMessageHandler.class, suppressException = true) // highlight-line
+ public String handleRequest(SQSEvent input, Context context) {
+ return "{\"statusCode\": 200}";
+ }
+```
+
+**Within PowertoolsSqs Utility API**
+
+```java:title=App.java
+ @Override
+ public List handleRequest(SQSEvent input, Context context) {
+ List returnValues = PowertoolsSqs.batchProcessor(input, true, SampleMessageHandler.class); // highlight-line
+
+ return returnValues;
+ }
+```
diff --git a/docs/content/utilities/sqs_large_message_handling.mdx b/docs/content/utilities/sqs_large_message_handling.mdx
index cb273f38c..e2e4a77ad 100644
--- a/docs/content/utilities/sqs_large_message_handling.mdx
+++ b/docs/content/utilities/sqs_large_message_handling.mdx
@@ -35,7 +35,7 @@ To install this utility, add the following dependency to your project.
And configure the aspectj-maven-plugin to compile-time weave (CTW) the
aws-lambda-powertools-java aspects into your project. You may already have this
-plugin in your pom. In that case add the depenedency to the `aspectLibraries`
+plugin in your pom. In that case add the dependency to the `aspectLibraries`
section.
```xml
@@ -51,12 +51,12 @@ section.
1.81.8
- ...
+
software.amazon.lambdapowertools-sqs
- ...
+
diff --git a/docs/gatsby-config.js b/docs/gatsby-config.js
index d3cd330a1..b79126b44 100644
--- a/docs/gatsby-config.js
+++ b/docs/gatsby-config.js
@@ -29,7 +29,8 @@ module.exports = {
],
'Utilities': [
'utilities/sqs_large_message_handling',
- 'utilities/parameters'
+ 'utilities/batch',
+ 'utilities/parameters',
],
},
navConfig: {
From 7cce85f1290a1859f96444dc63da7b5571756ab2 Mon Sep 17 00:00:00 2001
From: Pankaj Agrawal
Date: Sun, 4 Oct 2020 12:53:37 +0200
Subject: [PATCH 08/12] Fix correct place holder for queuename and account
---
.../lambda/powertools/sqs/internal/BatchContext.java | 8 +++++---
.../powertools/sqs/PowertoolsSqsBatchProcessorTest.java | 8 ++++++++
2 files changed, 13 insertions(+), 3 deletions(-)
diff --git a/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/internal/BatchContext.java b/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/internal/BatchContext.java
index eca4be3b8..d1d8da066 100644
--- a/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/internal/BatchContext.java
+++ b/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/internal/BatchContext.java
@@ -8,6 +8,7 @@
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequestEntry;
+import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchResponse;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import software.amazon.lambda.powertools.sqs.SQSBatchProcessingException;
@@ -68,15 +69,16 @@ private void deleteSuccessMessage() {
.build()).collect(toList()))
.build();
- client.deleteMessageBatch(request);
+ DeleteMessageBatchResponse deleteMessageBatchResponse = client.deleteMessageBatch(request);
+ LOG.debug(format("Response from delete request %s", deleteMessageBatchResponse));
}
}
private String url() {
String[] arnArray = success.get(0).getEventSourceArn().split(":");
return client.getQueueUrl(GetQueueUrlRequest.builder()
- .queueOwnerAWSAccountId(arnArray[1])
- .queueName(arnArray[2])
+ .queueOwnerAWSAccountId(arnArray[4])
+ .queueName(arnArray[5])
.build())
.queueUrl();
}
diff --git a/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/PowertoolsSqsBatchProcessorTest.java b/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/PowertoolsSqsBatchProcessorTest.java
index 002af9636..8020d5bba 100644
--- a/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/PowertoolsSqsBatchProcessorTest.java
+++ b/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/PowertoolsSqsBatchProcessorTest.java
@@ -9,6 +9,7 @@
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
@@ -107,6 +108,13 @@ void shouldBatchProcessAndDeleteSuccessMessageOnPartialFailures() {
verify(interactionClient).listQueues();
verify(sqsClient).deleteMessageBatch(any(DeleteMessageBatchRequest.class));
+
+ ArgumentCaptor captor = ArgumentCaptor.forClass(GetQueueUrlRequest.class);
+ verify(sqsClient).getQueueUrl(captor.capture());
+
+ assertThat(captor.getValue())
+ .hasFieldOrPropertyWithValue("queueName", "my-queue")
+ .hasFieldOrPropertyWithValue("queueOwnerAWSAccountId", "123456789012");
}
@Test
From 33eb76d81acc2f708ac8f0e68dabd2860ab9ad94 Mon Sep 17 00:00:00 2001
From: Pankaj Agrawal
Date: Sun, 4 Oct 2020 13:32:02 +0200
Subject: [PATCH 09/12] Example usage with relevant permissions
---
example/HelloWorldFunction/pom.xml | 9 ++++
.../src/main/java/helloworld/AppSqsEvent.java | 35 +++++++++++++
.../main/java/helloworld/AppSqsEventUtil.java | 39 ++++++++++++++
example/events/eventSqs.json | 36 +++++++++++++
example/template.yaml | 51 +++++++++++++++++++
5 files changed, 170 insertions(+)
create mode 100644 example/HelloWorldFunction/src/main/java/helloworld/AppSqsEvent.java
create mode 100644 example/HelloWorldFunction/src/main/java/helloworld/AppSqsEventUtil.java
create mode 100644 example/events/eventSqs.json
diff --git a/example/HelloWorldFunction/pom.xml b/example/HelloWorldFunction/pom.xml
index 9ad3559f9..c23351de5 100644
--- a/example/HelloWorldFunction/pom.xml
+++ b/example/HelloWorldFunction/pom.xml
@@ -33,6 +33,11 @@
powertools-parameters0.4.0-beta
+
+ software.amazon.lambda
+ powertools-sqs
+ 0.4.0-beta
+ com.amazonawsaws-lambda-java-core
@@ -90,6 +95,10 @@
software.amazon.lambdapowertools-metrics
+
+ software.amazon.lambda
+ powertools-sqs
+
diff --git a/example/HelloWorldFunction/src/main/java/helloworld/AppSqsEvent.java b/example/HelloWorldFunction/src/main/java/helloworld/AppSqsEvent.java
new file mode 100644
index 000000000..ff9d050af
--- /dev/null
+++ b/example/HelloWorldFunction/src/main/java/helloworld/AppSqsEvent.java
@@ -0,0 +1,35 @@
+package helloworld;
+
+import com.amazonaws.services.lambda.runtime.Context;
+import com.amazonaws.services.lambda.runtime.RequestHandler;
+import com.amazonaws.services.lambda.runtime.events.SQSEvent;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import software.amazon.lambda.powertools.logging.PowertoolsLogging;
+import software.amazon.lambda.powertools.sqs.SqsBatchProcessor;
+import software.amazon.lambda.powertools.sqs.SqsMessageHandler;
+
+import static com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage;
+
+public class AppSqsEvent implements RequestHandler {
+ private static final Logger LOG = LogManager.getLogger(AppSqsEvent.class);
+
+ @Override
+ @SqsBatchProcessor(SampleMessageHandler.class)
+ @PowertoolsLogging(logEvent = true)
+ public String handleRequest(SQSEvent input, Context context) {
+ return "{\"statusCode\": 200}";
+ }
+
+ public class SampleMessageHandler implements SqsMessageHandler {
+
+ @Override
+ public String process(SQSMessage message) {
+ if("19dd0b57-b21e-4ac1-bd88-01bbb068cb99".equals(message.getMessageId())) {
+ throw new RuntimeException(message.getMessageId());
+ }
+ LOG.info("Processing message with details {}", message);
+ return message.getMessageId();
+ }
+ }
+}
diff --git a/example/HelloWorldFunction/src/main/java/helloworld/AppSqsEventUtil.java b/example/HelloWorldFunction/src/main/java/helloworld/AppSqsEventUtil.java
new file mode 100644
index 000000000..a1300defc
--- /dev/null
+++ b/example/HelloWorldFunction/src/main/java/helloworld/AppSqsEventUtil.java
@@ -0,0 +1,39 @@
+package helloworld;
+
+import java.util.List;
+
+import com.amazonaws.services.lambda.runtime.Context;
+import com.amazonaws.services.lambda.runtime.RequestHandler;
+import com.amazonaws.services.lambda.runtime.events.SQSEvent;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import software.amazon.lambda.powertools.sqs.PowertoolsSqs;
+import software.amazon.lambda.powertools.sqs.SQSBatchProcessingException;
+
+import static java.util.Collections.emptyList;
+
+public class AppSqsEventUtil implements RequestHandler> {
+ private static final Logger LOG = LogManager.getLogger(AppSqsEventUtil.class);
+
+ @Override
+ public List handleRequest(SQSEvent input, Context context) {
+ try {
+
+ return PowertoolsSqs.batchProcessor(input, (message) -> {
+ if ("19dd0b57-b21e-4ac1-bd88-01bbb068cb99".equals(message.getMessageId())) {
+ throw new RuntimeException(message.getMessageId());
+ }
+
+ LOG.info("Processing message with details {}", message);
+ return message.getMessageId();
+ });
+
+ } catch (SQSBatchProcessingException e) {
+ LOG.info("Exception details {}", e.getMessage(), e);
+ LOG.info("Success message Returns{}", e.successMessageReturnValues());
+ LOG.info("Failed messages {}", e.getFailures());
+ LOG.info("Failed messages Reasons {}", e.getExceptions());
+ return emptyList();
+ }
+ }
+}
diff --git a/example/events/eventSqs.json b/example/events/eventSqs.json
new file mode 100644
index 000000000..37a29c4dd
--- /dev/null
+++ b/example/events/eventSqs.json
@@ -0,0 +1,36 @@
+{
+ "Records": [
+ {
+ "messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb99",
+ "receiptHandle": "MessageReceiptHandle",
+ "body": "Hello from SQS!",
+ "attributes": {
+ "ApproximateReceiveCount": "1",
+ "SentTimestamp": "1523232000000",
+ "SenderId": "123456789012",
+ "ApproximateFirstReceiveTimestamp": "1523232000001"
+ },
+ "messageAttributes": {},
+ "md5OfBody": "7b270e59b47ff90a553787216d55d999",
+ "eventSource": "aws:sqs",
+ "eventSourceARN": "arn:aws:sqs:eu-west-1:123456789:powertools-example-TestSqsQueue-1JW5W8N9",
+ "awsRegion": "eu-west-1"
+ },
+ {
+ "messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78",
+ "receiptHandle": "MessageReceiptHandle",
+ "body": "Hello from SQS!",
+ "attributes": {
+ "ApproximateReceiveCount": "1",
+ "SentTimestamp": "1523232000000",
+ "SenderId": "123456789012",
+ "ApproximateFirstReceiveTimestamp": "1523232000001"
+ },
+ "messageAttributes": {},
+ "md5OfBody": "7b270e59b47ff90a553787216d55d91d",
+ "eventSource": "aws:sqs",
+ "eventSourceARN": "arn:aws:sqs:eu-west-1:123456789:powertools-example-TestSqsQueue-1JW5W8N9",
+ "awsRegion": "eu-west-1"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/example/template.yaml b/example/template.yaml
index a7dd1b8be..9f279c2bf 100644
--- a/example/template.yaml
+++ b/example/template.yaml
@@ -125,6 +125,57 @@ Resources:
Value: aGVsbG8gd29ybGQ=
Description: Base64 SSM Parameter for lambda-powertools-java powertools-parameters module
+ TestSqsQueue:
+ Type: AWS::SQS::Queue
+
+ HelloWorldSqsEventFunction:
+ Type: AWS::Serverless::Function
+ Properties:
+ CodeUri: HelloWorldFunction
+ Handler: helloworld.AppSqsEvent::handleRequest
+ Runtime: java8
+ MemorySize: 512
+ Tracing: Active
+ Policies:
+ - Statement:
+ - Sid: AdditionalPermisssionForPowertoolsSQSUtils
+ Effect: Allow
+ Action:
+ - sqs:GetQueueUrl
+ - sqs:DeleteMessageBatch
+ Resource: !GetAtt TestSqsQueue.Arn
+ Events:
+ TestSQSEvent:
+ Type: SQS
+ Properties:
+ Queue: !GetAtt TestSqsQueue.Arn
+ BatchSize: 10
+
+ TestAnotherSqsQueue:
+ Type: AWS::SQS::Queue
+
+ HelloWorldSqsEventUtilFunction:
+ Type: AWS::Serverless::Function
+ Properties:
+ CodeUri: HelloWorldFunction
+ Handler: helloworld.AppSqsEventUtil::handleRequest
+ Runtime: java8
+ MemorySize: 512
+ Tracing: Active
+ Policies:
+ - Statement:
+ - Sid: AdditionalPermisssionForPowertoolsSQSUtils
+ Effect: Allow
+ Action:
+ - sqs:GetQueueUrl
+ - sqs:DeleteMessageBatch
+ Resource: !GetAtt TestAnotherSqsQueue.Arn
+ Events:
+ TestSQSEvent:
+ Type: SQS
+ Properties:
+ Queue: !GetAtt TestAnotherSqsQueue.Arn
+ BatchSize: 10
Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
From e4d2b1b4b5c21baac1dc92c5676900f5e1ed231a Mon Sep 17 00:00:00 2001
From: Pankaj Agrawal
Date: Mon, 5 Oct 2020 09:49:53 +0200
Subject: [PATCH 10/12] Minor doc updates
---
docs/content/utilities/batch.mdx | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/docs/content/utilities/batch.mdx b/docs/content/utilities/batch.mdx
index babe709e9..61022161b 100644
--- a/docs/content/utilities/batch.mdx
+++ b/docs/content/utilities/batch.mdx
@@ -14,11 +14,11 @@ The SQS batch processing utility provides a way to handle partial failures when
**Background**
-When using SQS as a Lambda event source mapping, Lambda functions are triggered with a batch of messages from SQS.
+When using SQS as a Lambda event source mapping, Lambda functions can be triggered with a batch of messages from SQS.
-If your function fails to process any message from the batch, the entire batch returns to your SQS queue, and your Lambda function is triggered with the same batch one more time.
+If your function fails to process any message from the batch, the entire batch returns to your SQS queue, and your Lambda function will be triggered with the same batch again.
-With this utility, messages within a batch are handled individually - only messages that were not successfully processed
+With this utility, messages within a batch will be handled individually - only messages that were not successfully processed
are returned to the queue.
From 1b0eec334513e4f4c4086595bd7035c061a04376 Mon Sep 17 00:00:00 2001
From: Pankaj Agrawal
Date: Mon, 5 Oct 2020 10:19:36 +0200
Subject: [PATCH 11/12] Ranme method to set custom sqs client
---
docs/content/utilities/batch.mdx | 2 +-
.../amazon/lambda/powertools/sqs/PowertoolsSqs.java | 8 ++------
.../powertools/sqs/PowertoolsSqsBatchProcessorTest.java | 4 ++--
.../sqs/internal/SqsMessageBatchProcessorAspectTest.java | 4 ++--
4 files changed, 7 insertions(+), 11 deletions(-)
diff --git a/docs/content/utilities/batch.mdx b/docs/content/utilities/batch.mdx
index 61022161b..74401a726 100644
--- a/docs/content/utilities/batch.mdx
+++ b/docs/content/utilities/batch.mdx
@@ -198,7 +198,7 @@ If you need to pass custom SqsClient such as region to the SDK, you can pass you
public class AppSqsEvent implements RequestHandler> {
// highlight-start
static {
- PowertoolsSqs.defaultSqsClient(SqsClient.builder()
+ PowertoolsSqs.overrideSqsClient(SqsClient.builder()
.build());
}
// highlight-end
diff --git a/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/PowertoolsSqs.java b/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/PowertoolsSqs.java
index 6bfea05a9..01ded6410 100644
--- a/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/PowertoolsSqs.java
+++ b/powertools-sqs/src/main/java/software/amazon/lambda/powertools/sqs/PowertoolsSqs.java
@@ -92,7 +92,7 @@ public static R enrichedMessageFromS3(final SQSEvent sqsEvent,
*
* @param client {@link SqsClient} to be used by utility
*/
- public static void defaultSqsClient(SqsClient client) {
+ public static void overrideSqsClient(SqsClient client) {
PowertoolsSqs.client = client;
}
@@ -229,7 +229,7 @@ public static List batchProcessor(final SQSEvent event,
final SqsMessageHandler handler) {
final List handlerReturn = new ArrayList<>();
- BatchContext batchContext = new BatchContext(defaultSqsClient());
+ BatchContext batchContext = new BatchContext(client);
for (SQSMessage message : event.getRecords()) {
try {
@@ -245,10 +245,6 @@ public static List batchProcessor(final SQSEvent event,
return handlerReturn;
}
- private static SqsClient defaultSqsClient() {
- return client;
- }
-
private static SqsMessageHandler instantiatedHandler(final Class extends SqsMessageHandler> handler) {
try {
diff --git a/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/PowertoolsSqsBatchProcessorTest.java b/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/PowertoolsSqsBatchProcessorTest.java
index 8020d5bba..c894081d4 100644
--- a/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/PowertoolsSqsBatchProcessorTest.java
+++ b/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/PowertoolsSqsBatchProcessorTest.java
@@ -26,7 +26,7 @@
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static software.amazon.lambda.powertools.sqs.PowertoolsSqs.batchProcessor;
-import static software.amazon.lambda.powertools.sqs.PowertoolsSqs.defaultSqsClient;
+import static software.amazon.lambda.powertools.sqs.PowertoolsSqs.overrideSqsClient;
class PowertoolsSqsBatchProcessorTest {
@@ -44,7 +44,7 @@ void setUp() throws IOException {
.queueUrl("test")
.build());
- defaultSqsClient(sqsClient);
+ overrideSqsClient(sqsClient);
}
@Test
diff --git a/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/internal/SqsMessageBatchProcessorAspectTest.java b/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/internal/SqsMessageBatchProcessorAspectTest.java
index 68999cc9a..59460e665 100644
--- a/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/internal/SqsMessageBatchProcessorAspectTest.java
+++ b/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/internal/SqsMessageBatchProcessorAspectTest.java
@@ -28,7 +28,7 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
-import static software.amazon.lambda.powertools.sqs.PowertoolsSqs.defaultSqsClient;
+import static software.amazon.lambda.powertools.sqs.PowertoolsSqs.overrideSqsClient;
public class SqsMessageBatchProcessorAspectTest {
public static final SqsClient sqsClient = mock(SqsClient.class);
@@ -41,7 +41,7 @@ public class SqsMessageBatchProcessorAspectTest {
@BeforeEach
void setUp() throws IOException {
- defaultSqsClient(sqsClient);
+ overrideSqsClient(sqsClient);
reset(sqsClient);
setupContext();
event = MAPPER.readValue(this.getClass().getResource("/sampleSqsBatchEvent.json"), SQSEvent.class);
From 583544055ed8d46d52ecc7bfc413b27674175104 Mon Sep 17 00:00:00 2001
From: Pankaj Agrawal
Date: Mon, 5 Oct 2020 12:23:03 +0200
Subject: [PATCH 12/12] Make test less confusing
---
.../PartialBatchFailureSuppressedHandler.java | 4 ++--
.../handlers/PartialBatchPartialFailureHandler.java | 4 ++--
.../sqs/handlers/PartialBatchSuccessHandler.java | 4 ++--
.../SqsMessageBatchProcessorAspectTest.java | 13 ++++++++-----
4 files changed, 14 insertions(+), 11 deletions(-)
diff --git a/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/handlers/PartialBatchFailureSuppressedHandler.java b/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/handlers/PartialBatchFailureSuppressedHandler.java
index ea1cd8944..7bec0e091 100644
--- a/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/handlers/PartialBatchFailureSuppressedHandler.java
+++ b/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/handlers/PartialBatchFailureSuppressedHandler.java
@@ -7,7 +7,7 @@
import software.amazon.lambda.powertools.sqs.SqsMessageHandler;
import static com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage;
-import static software.amazon.lambda.powertools.sqs.internal.SqsMessageBatchProcessorAspectTest.sqsClient;
+import static software.amazon.lambda.powertools.sqs.internal.SqsMessageBatchProcessorAspectTest.mockedRandom;
public class PartialBatchFailureSuppressedHandler implements RequestHandler {
@Override
@@ -25,7 +25,7 @@ public String process(SQSMessage message) {
throw new RuntimeException("2e1424d4-f796-459a-8184-9c92662be6da");
}
- sqsClient.listQueues();
+ mockedRandom.nextInt();
return "Success";
}
}
diff --git a/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/handlers/PartialBatchPartialFailureHandler.java b/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/handlers/PartialBatchPartialFailureHandler.java
index 43a569ca6..6301f84ef 100644
--- a/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/handlers/PartialBatchPartialFailureHandler.java
+++ b/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/handlers/PartialBatchPartialFailureHandler.java
@@ -7,7 +7,7 @@
import software.amazon.lambda.powertools.sqs.SqsMessageHandler;
import static com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage;
-import static software.amazon.lambda.powertools.sqs.internal.SqsMessageBatchProcessorAspectTest.sqsClient;
+import static software.amazon.lambda.powertools.sqs.internal.SqsMessageBatchProcessorAspectTest.mockedRandom;
public class PartialBatchPartialFailureHandler implements RequestHandler {
@Override
@@ -25,7 +25,7 @@ public String process(SQSMessage message) {
throw new RuntimeException("2e1424d4-f796-459a-8184-9c92662be6da");
}
- sqsClient.listQueues();
+ mockedRandom.nextInt();
return "Success";
}
}
diff --git a/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/handlers/PartialBatchSuccessHandler.java b/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/handlers/PartialBatchSuccessHandler.java
index d44b084da..009db08b9 100644
--- a/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/handlers/PartialBatchSuccessHandler.java
+++ b/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/handlers/PartialBatchSuccessHandler.java
@@ -7,7 +7,7 @@
import software.amazon.lambda.powertools.sqs.SqsMessageHandler;
import static com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage;
-import static software.amazon.lambda.powertools.sqs.internal.SqsMessageBatchProcessorAspectTest.sqsClient;
+import static software.amazon.lambda.powertools.sqs.internal.SqsMessageBatchProcessorAspectTest.mockedRandom;
public class PartialBatchSuccessHandler implements RequestHandler {
@Override
@@ -21,7 +21,7 @@ private class InnerMessageHandler implements SqsMessageHandler {
@Override
public String process(SQSMessage message) {
- sqsClient.listQueues();
+ mockedRandom.nextInt();
return "Success";
}
}
diff --git a/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/internal/SqsMessageBatchProcessorAspectTest.java b/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/internal/SqsMessageBatchProcessorAspectTest.java
index 59460e665..7d7d3d023 100644
--- a/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/internal/SqsMessageBatchProcessorAspectTest.java
+++ b/powertools-sqs/src/test/java/software/amazon/lambda/powertools/sqs/internal/SqsMessageBatchProcessorAspectTest.java
@@ -1,6 +1,7 @@
package software.amazon.lambda.powertools.sqs.internal;
import java.io.IOException;
+import java.util.Random;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
@@ -31,17 +32,19 @@
import static software.amazon.lambda.powertools.sqs.PowertoolsSqs.overrideSqsClient;
public class SqsMessageBatchProcessorAspectTest {
- public static final SqsClient sqsClient = mock(SqsClient.class);
+ public static final Random mockedRandom = mock(Random.class);
+ private static final SqsClient sqsClient = mock(SqsClient.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private SQSEvent event;
private RequestHandler requestHandler;
- private Context context = mock(Context.class);
+ private final Context context = mock(Context.class);
@BeforeEach
void setUp() throws IOException {
overrideSqsClient(sqsClient);
+ reset(mockedRandom);
reset(sqsClient);
setupContext();
event = MAPPER.readValue(this.getClass().getResource("/sampleSqsBatchEvent.json"), SQSEvent.class);
@@ -57,7 +60,7 @@ void setUp() throws IOException {
void shouldBatchProcessAllMessageSuccessfullyAndNotDeleteFromSQS() {
requestHandler.handleRequest(event, context);
- verify(sqsClient, times(2)).listQueues();
+ verify(mockedRandom, times(2)).nextInt();
verify(sqsClient, times(0)).deleteMessageBatch(any(DeleteMessageBatchRequest.class));
}
@@ -83,7 +86,7 @@ void shouldBatchProcessMessageWithSuccessDeletedOnFailureInBatchFromSQS() {
.contains("Success");
});
- verify(sqsClient).listQueues();
+ verify(mockedRandom).nextInt();
verify(sqsClient).deleteMessageBatch(any(DeleteMessageBatchRequest.class));
}
@@ -93,7 +96,7 @@ void shouldBatchProcessMessageWithSuccessDeletedOnFailureWithSuppressionInBatchF
requestHandler.handleRequest(event, context);
- verify(sqsClient).listQueues();
+ verify(mockedRandom).nextInt();
verify(sqsClient).deleteMessageBatch(any(DeleteMessageBatchRequest.class));
}