Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(lambda): honor MaximumRetryAttempts and DestinationConfig.OnFailure for DynamoDB Streams ESM (#3263) (#3428)

Vũ Thế Huy1af3b56683e6
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java
index 2d048d76c9..168dd30966 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java
@@ -1,6 +1,11 @@
package io.github.hectorvent.floci.services.lambda;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
@@ -10,16 +15,16 @@ import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.pipes.PipesFilterMatcher;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.services.sns.SnsService;
+import io.github.hectorvent.floci.services.sqs.SqsService;
import io.vertx.core.Vertx;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
+import java.time.Instant;
+import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -45,9 +50,13 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
private final EsmStore esmStore;
private final ObjectMapper objectMapper;
private final PipesFilterMatcher filterMatcher;
+ private final SqsService sqsService;
+ private final SnsService snsService;
+ private final String baseUrl;
private final long pollIntervalMs;
private final ConcurrentHashMap<String, Long> timerIds = new ConcurrentHashMap<>();
- private final ConcurrentHashMap<String, Boolean> activePolls = new ConcurrentHashMap<>();
+ final ConcurrentHashMap<String, Boolean> activePolls = new ConcurrentHashMap<>();
+ private final ConcurrentHashMap<String, Integer> retryCounts = new ConcurrentHashMap<>();
private final ExecutorService pollExecutor = Executors.newCachedThreadPool(r -> {
Thread t = new Thread(r, "dynamodb-streams-esm-poller");
t.setDaemon(true);
@@ -61,7 +70,9 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
EsmStore esmStore,
ObjectMapper objectMapper,
EmulatorConfig config,
- PipesFilterMatcher filterMatcher) {
+ PipesFilterMatcher filterMatcher,
+ SqsService sqsService,
+ SnsService snsService) {
this.vertx = vertx;
this.streamService = streamService;
this.executorService = executorService;
@@ -69,7 +80,10 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
this.esmStore = esmStore;
this.objectMapper = objectMapper;
this.pollIntervalMs = config.services().lambda().pollIntervalMs();
+ this.baseUrl = config.effectiveBaseUrl();
this.filterMatcher = filterMatcher;
+ this.sqsService = sqsService;
+ this.snsService = snsService;
}
public void startPersistedPollers() {
@@ -118,6 +132,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
timerIds.values().forEach(vertx::cancelTimer);
timerIds.clear();
activePolls.clear();
+ retryCounts.clear();
}
public void startPolling(EventSourceMapping esm) {
@@ -142,8 +157,10 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
vertx.cancelTimer(timerId);
LOG.debugv("Stopped DynamoDB Streams polling for ESM {0}", uuid);
}
+ retryCounts.keySet().removeIf(k -> k.startsWith(uuid + ":"));
}
+
void pollAndInvoke(EventSourceMapping esm) {
if (activePolls.putIfAbsent(esm.getUuid(), Boolean.TRUE) != null) {
return;
@@ -161,6 +178,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
String shardId = DynamoDbStreamService.SHARD_ID;
String lastSeq = esm.getShardSequenceNumbers().get(shardId);
+ boolean checkpointTrimmed = false;
DynamoDbStreamService.GetRecordsResult result;
try {
String iterator = lastSeq == null
@@ -171,6 +189,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
if (!TRIMMED_DATA_ACCESS_EXCEPTION.equals(e.getErrorCode())) {
throw e;
}
+ checkpointTrimmed = true;
// The checkpoint fell outside the retained window, so the cursor it names can
// never succeed again. Retrying it wedges the ESM permanently: every later
// write reaches the stream and none is ever delivered. Resume from the oldest
@@ -226,15 +245,64 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
throw e;
}
- if (invokeResult.getFunctionError() == null) {
- String checkpoint = successfulInvocationCheckpoint(
- esm, invokeResult, lastSeq, records, matched);
- if (checkpoint != null && !checkpoint.equals(lastSeq)) {
- advanceCheckpoint(esm, shardId, checkpoint);
+ String checkpointSeq = (lastSeq == null || checkpointTrimmed) ? "TRIM_HORIZON" : lastSeq;
+ String batchKey = esm.getUuid() + ":" + shardId + ":" + checkpointSeq;
+ CheckpointOutcome outcome = invokeResult.getFunctionError() == null
+ ? successfulInvocationCheckpoint(esm, invokeResult, lastSeq, records, matched)
+ : new CheckpointOutcome(null, 0);
+
+ if (outcome.lowestFailedIndex() == records.size()) {
+ retryCounts.remove(batchKey);
+ advanceCheckpoint(esm, shardId, outcome.checkpoint());
+ } else if (outcome.lowestFailedIndex() > 0) {
+ retryCounts.remove(batchKey);
+
+ String nextCheckpoint = outcome.checkpoint();
+ String nextBatchKey = esm.getUuid() + ":" + shardId + ":" + nextCheckpoint;
+ Integer maxRetries = esm.getMaximumRetryAttempts();
+ int currentRetries = retryCounts.merge(nextBatchKey, 1, Integer::sum);
+
+ if (maxRetries != null && maxRetries >= 0 && currentRetries > maxRetries) {
+ LOG.warnv("DynamoDB Streams ESM {0}: maximum retry attempts ({1}) exhausted for batch ending at {2}",
+ esm.getUuid(), maxRetries, newestFetchedSeq);
+ Set<String> deliveredSeqs = new HashSet<>();
+ for (DynamoDbStreamRecord rec : matched) {
+ deliveredSeqs.add(rec.getSequenceNumber());
+ }
+ List<DynamoDbStreamRecord> failedRecords = new ArrayList<>();
+ for (int i = outcome.lowestFailedIndex(); i < records.size(); i++) {
+ DynamoDbStreamRecord rec = records.get(i);
+ if (deliveredSeqs.contains(rec.getSequenceNumber())) {
+ failedRecords.add(rec);
+ }
+ }
+ if (failedRecords.isEmpty()) {
+ failedRecords = records.subList(outcome.lowestFailedIndex(), records.size());
+ }
+ sendToOnFailureDestination(esm, shardId, failedRecords, invokeResult, currentRetries);
+ retryCounts.remove(nextBatchKey);
+ advanceCheckpoint(esm, shardId, newestFetchedSeq);
+ } else {
+ LOG.warnv("DynamoDB Streams ESM {0}: Lambda returned error [batchItemFailures], retry {1}, records will be retried",
+ esm.getUuid(), currentRetries);
+ advanceCheckpoint(esm, shardId, nextCheckpoint);
}
} else {
- LOG.warnv("DynamoDB Streams ESM {0}: Lambda returned error [{1}], records will be retried",
- esm.getUuid(), invokeResult.getFunctionError());
+ Integer maxRetries = esm.getMaximumRetryAttempts();
+ int currentRetries = retryCounts.merge(batchKey, 1, Integer::sum);
+ if (maxRetries != null && maxRetries >= 0 && currentRetries > maxRetries) {
+ LOG.warnv("DynamoDB Streams ESM {0}: maximum retry attempts ({1}) exhausted for batch ending at {2}",
+ esm.getUuid(), maxRetries, newestFetchedSeq);
+ sendToOnFailureDestination(esm, shardId, matched, invokeResult, currentRetries);
+ retryCounts.remove(batchKey);
+ advanceCheckpoint(esm, shardId, newestFetchedSeq);
+ } else {
+ String error = invokeResult.getFunctionError() != null
+ ? invokeResult.getFunctionError()
+ : "batchItemFailures";
+ LOG.warnv("DynamoDB Streams ESM {0}: Lambda returned error [{1}], retry {2}, records will be retried",
+ esm.getUuid(), error, currentRetries);
+ }
}
} catch (Exception e) {
LOG.warnv("DynamoDB Streams ESM {0} poll error: {1}", esm.getUuid(), e.getMessage());
@@ -244,29 +312,32 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
});
}
+ private record CheckpointOutcome(String checkpoint, int lowestFailedIndex) {}
+
/**
* Returns the last record that can be consumed after a successful invocation. Floci stores the
* last consumed sequence and resumes with {@code AFTER_SEQUENCE_NUMBER}, so a partial failure
* checkpoints the record immediately before AWS's lowest reported failed sequence.
*/
- private String successfulInvocationCheckpoint(EventSourceMapping esm, InvokeResult invokeResult,
- String previousCheckpoint,
- List<DynamoDbStreamRecord> fetched,
- List<DynamoDbStreamRecord> delivered) {
+ private CheckpointOutcome successfulInvocationCheckpoint(EventSourceMapping esm, InvokeResult invokeResult,
+ String previousCheckpoint,
+ List<DynamoDbStreamRecord> fetched,
+ List<DynamoDbStreamRecord> delivered) {
String newestFetchedSeq = fetched.get(fetched.size() - 1).getSequenceNumber();
byte[] payload = invokeResult.getPayload();
if (!esm.isReportBatchItemFailures() || payload == null || payload.length == 0) {
- return newestFetchedSeq;
+ return new CheckpointOutcome(newestFetchedSeq, fetched.size());
}
try {
JsonNode response = objectMapper.readTree(payload);
JsonNode failures = response.get("batchItemFailures");
if (failures == null || failures.isNull()) {
- return newestFetchedSeq;
+ return new CheckpointOutcome(newestFetchedSeq, fetched.size());
}
if (!failures.isArray()) {
- return retryWholeBatch(esm, previousCheckpoint, "batchItemFailures is not an array");
+ return new CheckpointOutcome(
+ retryWholeBatch(esm, previousCheckpoint, "batchItemFailures is not an array"), 0);
}
Map<String, Integer> fetchedIndexes = new HashMap<>();
@@ -282,27 +353,30 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
for (JsonNode item : failures) {
JsonNode identifier = item.get("itemIdentifier");
if (identifier == null || identifier.isNull() || identifier.asText().isEmpty()) {
- return retryWholeBatch(esm, previousCheckpoint,
- "entry has a missing, null or empty itemIdentifier");
+ return new CheckpointOutcome(
+ retryWholeBatch(esm, previousCheckpoint,
+ "entry has a missing, null or empty itemIdentifier"), 0);
}
String sequenceNumber = identifier.asText();
Integer index = fetchedIndexes.get(sequenceNumber);
if (index == null || !deliveredSequences.contains(sequenceNumber)) {
- return retryWholeBatch(esm, previousCheckpoint,
- "itemIdentifier " + sequenceNumber + " is not in the delivered batch");
+ return new CheckpointOutcome(
+ retryWholeBatch(esm, previousCheckpoint,
+ "itemIdentifier " + sequenceNumber + " is not in the delivered batch"), 0);
}
lowestFailedIndex = Math.min(lowestFailedIndex, index);
}
if (lowestFailedIndex == fetched.size()) {
- return newestFetchedSeq;
+ return new CheckpointOutcome(newestFetchedSeq, fetched.size());
}
- return lowestFailedIndex == 0
+ String checkpoint = lowestFailedIndex == 0
? previousCheckpoint
: fetched.get(lowestFailedIndex - 1).getSequenceNumber();
+ return new CheckpointOutcome(checkpoint, lowestFailedIndex);
} catch (Exception e) {
- return retryWholeBatch(esm, previousCheckpoint,
- "response is not valid JSON: " + e.getMessage());
+ return new CheckpointOutcome(
+ retryWholeBatch(esm, previousCheckpoint, "response is not valid JSON: " + e.getMessage()), 0);
}
}
@@ -313,6 +387,86 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
return previousCheckpoint;
}
+ private void sendToOnFailureDestination(EventSourceMapping esm, String shardId,
+ List<DynamoDbStreamRecord> records,
+ InvokeResult invokeResult,
+ int invokeCount) {
+ if (esm.getDestinationConfig() == null || esm.getDestinationConfig().getOnFailure() == null) {
+ return;
+ }
+ String destinationArn = esm.getDestinationConfig().getOnFailure().getDestination();
+ if (destinationArn == null || destinationArn.isBlank()) {
+ return;
+ }
+
+ try {
+ String payload = buildOnFailurePayload(esm, shardId, records, invokeResult, invokeCount);
+ String region = AwsArnUtils.regionOrDefault(destinationArn, esm.getRegion());
+
+ if (destinationArn.contains(":sqs:")) {
+ String queueUrl = AwsArnUtils.arnToQueueUrl(destinationArn, baseUrl);
+ sqsService.sendMessage(queueUrl, payload, 0, region);
+ LOG.infov("DynamoDB Streams ESM {0}: sent failed batch to SQS DLQ {1}", esm.getUuid(), destinationArn);
+ } else if (destinationArn.contains(":sns:")) {
+ snsService.publish(destinationArn, null, payload, "ESM OnFailure", region);
+ LOG.infov("DynamoDB Streams ESM {0}: sent failed batch to SNS DLQ {1}", esm.getUuid(), destinationArn);
+ } else {
+ LOG.warnv("DynamoDB Streams ESM {0}: unsupported OnFailure destination ARN {1}",
+ esm.getUuid(), destinationArn);
+ }
+ } catch (Exception e) {
+ LOG.errorv("DynamoDB Streams ESM {0}: failed to send to OnFailure destination {1}: {2}",
+ esm.getUuid(), destinationArn, e.getMessage());
+ }
+ }
+
+ private String buildOnFailurePayload(EventSourceMapping esm, String shardId,
+ List<DynamoDbStreamRecord> records,
+ InvokeResult invokeResult,
+ int invokeCount) {
+ try {
+ ObjectNode root = objectMapper.createObjectNode();
+ root.put("version", "1.0");
+ root.put("timestamp", DateTimeFormatter.ISO_INSTANT.format(Instant.now()));
+
+ ObjectNode requestContext = root.putObject("requestContext");
+ requestContext.put("requestId", invokeResult.getRequestId() != null ? invokeResult.getRequestId() : "");
+ requestContext.put("functionArn", esm.getFunctionArn() != null ? esm.getFunctionArn() : "");
+ requestContext.put("condition", "RetryAttemptsExhausted");
+ requestContext.put("approximateInvokeCount", invokeCount);
+
+ ObjectNode responseContext = root.putObject("responseContext");
+ responseContext.put("statusCode", invokeResult.getStatusCode() != 0 ? invokeResult.getStatusCode() : 200);
+ responseContext.put("executedVersion", invokeResult.getExecutedVersion() != null ? invokeResult.getExecutedVersion() : "$LATEST");
+ if (invokeResult.getFunctionError() != null) {
+ responseContext.put("functionError", invokeResult.getFunctionError());
+ }
+
+ ObjectNode batchInfo = root.putObject("DDBStreamBatchInfo");
+ batchInfo.put("shardId", shardId);
+ String startSeq = records.isEmpty() ? "" : records.get(0).getSequenceNumber();
+ String endSeq = records.isEmpty() ? "" : records.get(records.size() - 1).getSequenceNumber();
+ batchInfo.put("startSequenceNumber", startSeq);
+ batchInfo.put("endSequenceNumber", endSeq);
+
+ if (!records.isEmpty()) {
+ long firstArrival = records.get(0).getApproximateCreationDateTime();
+ long lastArrival = records.get(records.size() - 1).getApproximateCreationDateTime();
+ batchInfo.put("approximateArrivalOfFirstRecord",
+ DateTimeFormatter.ISO_INSTANT.format(Instant.ofEpochSecond(firstArrival)));
+ batchInfo.put("approximateArrivalOfLastRecord",
+ DateTimeFormatter.ISO_INSTANT.format(Instant.ofEpochSecond(lastArrival)));
+ }
+ batchInfo.put("batchSize", records.size());
+ batchInfo.put("streamArn", esm.getEventSourceArn());
+
+ return objectMapper.writeValueAsString(root);
+ } catch (Exception e) {
+ LOG.warnv("Failed to serialize OnFailure payload: {0}", e.getMessage());
+ return "{}";
+ }
+ }
+
private String buildDynamoDbEvent(List<DynamoDbStreamRecord> records, EventSourceMapping esm) {
try {
ObjectNode root = objectMapper.createObjectNode();
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
index ca7ff325c9..b2cf08c25f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
@@ -369,6 +369,10 @@ public class LambdaController {
node.put("BisectBatchOnFunctionError", esm.getBisectBatchOnFunctionError());
}
+ if (esm.getMaximumRetryAttempts() != null) {
+ node.put("MaximumRetryAttempts", esm.getMaximumRetryAttempts());
+ }
+
if (esm.getDestinationConfig() != null && esm.getDestinationConfig().getOnFailure() != null) {
ObjectNode destinationConfig = node.putObject("DestinationConfig");
ObjectNode onFailure = destinationConfig.putObject("OnFailure");
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
index 530d73e8d7..5ca0725cdc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
@@ -1319,6 +1319,8 @@ public class LambdaService implements ResourceProvider {
? b
: null;
+ Integer maximumRetryAttempts = parseMaximumRetryAttempts(request);
+
EventSourceMapping.DestinationConfig destinationConfig = parseDestinationConfig(request);
EventSourceMapping.FilterCriteria filterCriteria = parseFilterCriteria(request, objectMapper);
@@ -1344,6 +1346,7 @@ public class LambdaService implements ResourceProvider {
esm.setScalingConfig(scalingConfig);
esm.setFunctionResponseTypes(functionResponseTypes);
esm.setBisectBatchOnFunctionError(bisectBatchOnFunctionError);
+ esm.setMaximumRetryAttempts(maximumRetryAttempts);
esm.setDestinationConfig(destinationConfig);
esm.setFilterCriteria(filterCriteria);
esm.setStartingPosition(startingPosition.position());
@@ -1727,6 +1730,28 @@ public class LambdaService implements ResourceProvider {
return (int) value;
}
+ private Integer parseMaximumRetryAttempts(Map<String, Object> request) {
+ Object raw = request.get("MaximumRetryAttempts");
+ if (raw == null) {
+ return null;
+ }
+ if (!(raw instanceof Number)) {
+ throw new AwsException("InvalidParameterValueException",
+ "MaximumRetryAttempts must be a numeric value", 400);
+ }
+ double d = ((Number) raw).doubleValue();
+ if (Double.isNaN(d) || Double.isInfinite(d) || d != Math.floor(d)) {
+ throw new AwsException("InvalidParameterValueException",
+ "MaximumRetryAttempts must be an integer", 400);
+ }
+ long value = ((Number) raw).longValue();
+ if (value < -1 || value > 10000) {
+ throw new AwsException("InvalidParameterValueException",
+ "MaximumRetryAttempts must be between -1 and 10000 (got " + value + ")", 400);
+ }
+ return (int) value;
+ }
+
private void startPollingHelper(EventSourceMapping esm) {
if (esm.getEventSourceArn() == null) {
return;
@@ -1798,6 +1823,10 @@ public class LambdaService implements ResourceProvider {
esm.setBisectBatchOnFunctionError(raw instanceof Boolean b ? b : null);
}
+ if (request.containsKey("MaximumRetryAttempts")) {
+ esm.setMaximumRetryAttempts(parseMaximumRetryAttempts(request));
+ }
+
if (request.containsKey("DestinationConfig")) {
esm.setDestinationConfig(parseDestinationConfig(request));
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java
index 00e9052031..32e999cf92 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java
@@ -31,6 +31,7 @@ public class EventSourceMapping {
private Map<String, String> shardSequenceNumbers = new HashMap<>();
private ScalingConfig scalingConfig;
private Boolean bisectBatchOnFunctionError;
+ private Integer maximumRetryAttempts;
private DestinationConfig destinationConfig;
private FilterCriteria filterCriteria;
private Map<String, Object> selfManagedEventSource;
@@ -118,6 +119,14 @@ public class EventSourceMapping {
this.bisectBatchOnFunctionError = bisectBatchOnFunctionError;
}
+ public Integer getMaximumRetryAttempts() {
+ return maximumRetryAttempts;
+ }
+
+ public void setMaximumRetryAttempts(Integer maximumRetryAttempts) {
+ this.maximumRetryAttempts = maximumRetryAttempts;
+ }
+
public DestinationConfig getDestinationConfig() {
return destinationConfig;
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePollerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePollerTest.java
index 5871070fa3..f21f021a5b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePollerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePollerTest.java
@@ -19,11 +19,13 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
+import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -34,6 +36,7 @@ import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -58,6 +61,8 @@ class DynamoDbStreamsEventSourcePollerTest {
private EsmStore esmStore;
private EmulatorConfig config;
private PipesFilterMatcher filterMatcher;
+ private io.github.hectorvent.floci.services.sqs.SqsService sqsService;
+ private io.github.hectorvent.floci.services.sns.SnsService snsService;
@BeforeEach
void setUp() {
@@ -67,18 +72,21 @@ class DynamoDbStreamsEventSourcePollerTest {
when(config.services()).thenReturn(services);
when(services.lambda()).thenReturn(lambdaConfig);
when(lambdaConfig.pollIntervalMs()).thenReturn(1000L);
+ when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
streamService = mock(DynamoDbStreamService.class);
executorService = mock(LambdaExecutorService.class);
functionStore = mock(LambdaFunctionStore.class);
esmStore = new EsmStore(new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, ACCOUNT_ID));
filterMatcher = new PipesFilterMatcher(OBJECT_MAPPER);
+ sqsService = mock(io.github.hectorvent.floci.services.sqs.SqsService.class);
+ snsService = mock(io.github.hectorvent.floci.services.sns.SnsService.class);
// A mocked Vertx makes setPeriodic a no-op, so startPolling registers no live timer and
// the tests drive pollAndInvoke deterministically.
poller = new DynamoDbStreamsEventSourcePoller(
mock(Vertx.class), streamService, executorService, functionStore,
- esmStore, OBJECT_MAPPER, config, filterMatcher);
+ esmStore, OBJECT_MAPPER, config, filterMatcher, sqsService, snsService);
}
private EventSourceMapping persistedStreamsEsmWithStaleCheckpoint() {
@@ -152,7 +160,7 @@ class DynamoDbStreamsEventSourcePollerTest {
private DynamoDbStreamsEventSourcePoller pollerWith(EsmStore store) {
return new DynamoDbStreamsEventSourcePoller(
mock(Vertx.class), streamService, executorService, functionStore,
- store, OBJECT_MAPPER, config, filterMatcher);
+ store, OBJECT_MAPPER, config, filterMatcher, sqsService, snsService);
}
/**
@@ -555,6 +563,401 @@ class DynamoDbStreamsEventSourcePollerTest {
assertEquals(STALE_CHECKPOINT, esm.getShardSequenceNumbers().get(DynamoDbStreamService.SHARD_ID));
}
+ @Test
+ void maxRetryAttemptsExhaustedDeliversToSqsOnFailureDestinationAndAdvancesCheckpoint() throws Exception {
+ stubTrimHorizon(List.of(ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}")));
+ InvokeResult err = new InvokeResult();
+ err.setFunctionError("Unhandled");
+ err.setStatusCode(200);
+ err.setRequestId("req-123");
+ err.setExecutedVersion("$LATEST");
+ when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(err);
+
+ EsmStore store = mock(EsmStore.class);
+ EventSourceMapping esm = filterEsm();
+ esm.setMaximumRetryAttempts(1); // 1 retry attempt allowed, 2nd error exhausts retries
+
+ String sqsArn = "arn:aws:sqs:us-east-1:000000000000:my-dlq";
+ EventSourceMapping.DestinationConfig destConfig = new EventSourceMapping.DestinationConfig();
+ EventSourceMapping.OnFailure onFailure = new EventSourceMapping.OnFailure();
+ onFailure.setDestination(sqsArn);
+ destConfig.setOnFailure(onFailure);
+ esm.setDestinationConfig(destConfig);
+
+ DynamoDbStreamsEventSourcePoller p = pollerWith(store);
+
+ // First poll: attempt 1 (initial failure, retries left)
+ p.pollAndInvoke(esm);
+ // Verify invoke was called for attempt 1
+ verify(executorService, timeout(2000)).invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse));
+ // Wait for poll 1 to finish by ensuring activePolls is released
+ long deadline = System.currentTimeMillis() + 3000;
+ while (System.currentTimeMillis() < deadline) {
+ if (p.activePolls.isEmpty()) {
+ break;
+ }
+ Thread.sleep(25);
+ }
+ // After 1st failure: checkpoint not advanced, no DLQ delivery
+ verify(store, never()).saveForAccount(anyString(), any());
+ verify(sqsService, never()).sendMessage(anyString(), anyString(), anyInt(), anyString());
+
+ // Second poll: attempt 2 (retry 1, which exceeds maxRetryAttempts=1 -> exhausted!)
+ p.pollAndInvoke(esm);
+
+ // Checkpoint advanced to "s1"
+ verify(store, timeout(2000)).saveForAccount(eq(ACCOUNT_ID), any());
+ assertEquals("s1", esm.getShardSequenceNumbers().get(DynamoDbStreamService.SHARD_ID));
+
+ // SQS delivery invoked
+ ArgumentCaptor<String> bodyCaptor = ArgumentCaptor.forClass(String.class);
+ String expectedQueueUrl = "http://localhost:4566/000000000000/my-dlq";
+ verify(sqsService, timeout(2000)).sendMessage(eq(expectedQueueUrl), bodyCaptor.capture(), eq(0), eq("us-east-1"));
+
+ JsonNode dlqPayload = OBJECT_MAPPER.readTree(bodyCaptor.getValue());
+ assertEquals("1.0", dlqPayload.path("version").asText());
+ assertEquals("RetryAttemptsExhausted", dlqPayload.path("requestContext").path("condition").asText());
+ assertEquals(2, dlqPayload.path("requestContext").path("approximateInvokeCount").asInt());
+ assertEquals("req-123", dlqPayload.path("requestContext").path("requestId").asText());
+ assertEquals("Unhandled", dlqPayload.path("responseContext").path("functionError").asText());
+ assertEquals(DynamoDbStreamService.SHARD_ID, dlqPayload.path("DDBStreamBatchInfo").path("shardId").asText());
+ assertEquals("s1", dlqPayload.path("DDBStreamBatchInfo").path("startSequenceNumber").asText());
+ assertEquals("s1", dlqPayload.path("DDBStreamBatchInfo").path("endSequenceNumber").asText());
+ assertEquals(1, dlqPayload.path("DDBStreamBatchInfo").path("batchSize").asInt());
+ assertEquals(STREAM_ARN, dlqPayload.path("DDBStreamBatchInfo").path("streamArn").asText());
+ assertTrue(dlqPayload.path("DDBStreamBatchInfo").has("approximateArrivalOfFirstRecord"));
+ assertTrue(dlqPayload.path("DDBStreamBatchInfo").has("approximateArrivalOfLastRecord"));
+ assertFalse(dlqPayload.has("hasBeenTruncated"));
+ }
+
+ @Test
+ void onFailurePayloadUsesEpochSecondsNotMillisForArrivalTimestamps() throws Exception {
+ // Chosen so the seconds/millis interpretations land 46+ years apart: a millis bug cannot
+ // accidentally parse back to this epoch-seconds value.
+ long knownEpochSeconds = 1_700_000_000L;
+ DynamoDbStreamRecord rec = ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}");
+ rec.setApproximateCreationDateTime(knownEpochSeconds);
+ stubTrimHorizon(List.of(rec));
+
+ InvokeResult err = new InvokeResult();
+ err.setFunctionError("Unhandled");
+ when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(err);
+
+ EsmStore store = mock(EsmStore.class);
+ EventSourceMapping esm = filterEsm();
+ esm.setMaximumRetryAttempts(0); // exhausts on the first failure
+
+ String sqsArn = "arn:aws:sqs:us-east-1:000000000000:my-dlq";
+ EventSourceMapping.DestinationConfig destConfig = new EventSourceMapping.DestinationConfig();
+ EventSourceMapping.OnFailure onFailure = new EventSourceMapping.OnFailure();
+ onFailure.setDestination(sqsArn);
+ destConfig.setOnFailure(onFailure);
+ esm.setDestinationConfig(destConfig);
+
+ DynamoDbStreamsEventSourcePoller p = pollerWith(store);
+ p.pollAndInvoke(esm);
+
+ ArgumentCaptor<String> bodyCaptor = ArgumentCaptor.forClass(String.class);
+ verify(sqsService, timeout(2000)).sendMessage(anyString(), bodyCaptor.capture(), anyInt(), anyString());
+
+ JsonNode dlqPayload = OBJECT_MAPPER.readTree(bodyCaptor.getValue());
+ Instant first = Instant.parse(
+ dlqPayload.path("DDBStreamBatchInfo").path("approximateArrivalOfFirstRecord").asText());
+ Instant last = Instant.parse(
+ dlqPayload.path("DDBStreamBatchInfo").path("approximateArrivalOfLastRecord").asText());
+ assertEquals(knownEpochSeconds, first.getEpochSecond());
+ assertEquals(knownEpochSeconds, last.getEpochSecond());
+ }
+
+ @Test
+ void maxRetryAttemptsExhaustedDeliversToSnsOnFailureDestination() {
+ stubTrimHorizon(List.of(ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}")));
+ InvokeResult err = new InvokeResult();
+ err.setFunctionError("Handled");
+ when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(err);
+
+ EsmStore store = mock(EsmStore.class);
+ EventSourceMapping esm = filterEsm();
+ esm.setMaximumRetryAttempts(0); // 0 retries allowed, 1st error exhausts immediately
+
+ String snsArn = "arn:aws:sns:us-east-1:000000000000:my-dlq-topic";
+ EventSourceMapping.DestinationConfig destConfig = new EventSourceMapping.DestinationConfig();
+ EventSourceMapping.OnFailure onFailure = new EventSourceMapping.OnFailure();
+ onFailure.setDestination(snsArn);
+ destConfig.setOnFailure(onFailure);
+ esm.setDestinationConfig(destConfig);
+
+ DynamoDbStreamsEventSourcePoller p = pollerWith(store);
+
+ p.pollAndInvoke(esm);
+
+ verify(store, timeout(2000)).saveForAccount(eq(ACCOUNT_ID), any());
+ assertEquals("s1", esm.getShardSequenceNumbers().get(DynamoDbStreamService.SHARD_ID));
+
+ verify(snsService, timeout(2000)).publish(eq(snsArn), any(), anyString(), eq("ESM OnFailure"), eq("us-east-1"));
+ }
+
+ @Test
+ void maxRetryAttemptsExhaustedTracksRetriesAcrossExpandingBatchWindow() throws Exception {
+ when(streamService.getShardIterator(eq(STREAM_ARN), eq(DynamoDbStreamService.SHARD_ID),
+ eq("TRIM_HORIZON"), any())).thenReturn("it-1", "it-2");
+ when(streamService.getRecords(eq("it-1"), anyInt())).thenReturn(
+ new DynamoDbStreamService.GetRecordsResult(
+ List.of(ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}")), "it-1"));
+ when(streamService.getRecords(eq("it-2"), anyInt())).thenReturn(
+ new DynamoDbStreamService.GetRecordsResult(
+ List.of(ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}"),
+ ddbRecord("s2", "INSERT", "{\"status\":{\"S\":\"active\"}}")), "it-2"));
+
+ InvokeResult err = new InvokeResult();
+ err.setFunctionError("Unhandled");
+ when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(err);
+ LambdaFunction fn = new LambdaFunction();
+ fn.setFunctionName("fn");
+ when(functionStore.getForAccount(ACCOUNT_ID, "us-east-1", "fn")).thenReturn(Optional.of(fn));
+
+ EsmStore store = mock(EsmStore.class);
+ EventSourceMapping esm = filterEsm();
+ esm.setMaximumRetryAttempts(1); // 1 retry allowed, 2nd error exhausts
+
+ String sqsArn = "arn:aws:sqs:us-east-1:000000000000:my-dlq";
+ EventSourceMapping.DestinationConfig destConfig = new EventSourceMapping.DestinationConfig();
+ EventSourceMapping.OnFailure onFailure = new EventSourceMapping.OnFailure();
+ onFailure.setDestination(sqsArn);
+ destConfig.setOnFailure(onFailure);
+ esm.setDestinationConfig(destConfig);
+
+ DynamoDbStreamsEventSourcePoller p = pollerWith(store);
+
+ p.pollAndInvoke(esm);
+ verify(executorService, timeout(2000)).invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse));
+
+ long deadline = System.currentTimeMillis() + 3000;
+ while (System.currentTimeMillis() < deadline) {
+ if (p.activePolls.isEmpty()) {
+ break;
+ }
+ Thread.sleep(25);
+ }
+
+ p.pollAndInvoke(esm);
+
+ verify(store, timeout(2000)).saveForAccount(eq(ACCOUNT_ID), any());
+ assertEquals("s2", esm.getShardSequenceNumbers().get(DynamoDbStreamService.SHARD_ID));
+
+ ArgumentCaptor<String> bodyCaptor = ArgumentCaptor.forClass(String.class);
+ String expectedQueueUrl = "http://localhost:4566/000000000000/my-dlq";
+ verify(sqsService, timeout(2000)).sendMessage(eq(expectedQueueUrl), bodyCaptor.capture(), eq(0), eq("us-east-1"));
+
+ JsonNode dlqPayload = OBJECT_MAPPER.readTree(bodyCaptor.getValue());
+ assertEquals("1.0", dlqPayload.path("version").asText());
+ assertEquals(2, dlqPayload.path("requestContext").path("approximateInvokeCount").asInt());
+ assertEquals("s1", dlqPayload.path("DDBStreamBatchInfo").path("startSequenceNumber").asText());
+ assertEquals("s2", dlqPayload.path("DDBStreamBatchInfo").path("endSequenceNumber").asText());
+ assertEquals(2, dlqPayload.path("DDBStreamBatchInfo").path("batchSize").asInt());
+ assertFalse(dlqPayload.has("hasBeenTruncated"));
+ }
+
+ @Test
+ void reportBatchItemFailuresExhaustsRetriesAndDeliversToOnFailureDestination() throws Exception {
+ stubTrimHorizon(List.of(ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}")));
+ InvokeResult result = new InvokeResult();
+ result.setStatusCode(200);
+ result.setRequestId("req-batch-fail");
+ result.setPayload("{\"batchItemFailures\":[{\"itemIdentifier\":\"s1\"}]}".getBytes());
+ when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(result);
+
+ EsmStore store = mock(EsmStore.class);
+ EventSourceMapping esm = filterEsm();
+ esm.setFunctionResponseTypes(List.of("ReportBatchItemFailures"));
+ esm.setMaximumRetryAttempts(1); // 1 retry attempt allowed, 2nd error exhausts retries
+
+ String sqsArn = "arn:aws:sqs:us-east-1:000000000000:my-dlq";
+ EventSourceMapping.DestinationConfig destConfig = new EventSourceMapping.DestinationConfig();
+ EventSourceMapping.OnFailure onFailure = new EventSourceMapping.OnFailure();
+ onFailure.setDestination(sqsArn);
+ destConfig.setOnFailure(onFailure);
+ esm.setDestinationConfig(destConfig);
+
+ DynamoDbStreamsEventSourcePoller p = pollerWith(store);
+
+ // First poll: attempt 1 (initial partial failure, retries left)
+ p.pollAndInvoke(esm);
+ verify(executorService, timeout(2000)).invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse));
+
+ long deadline = System.currentTimeMillis() + 3000;
+ while (System.currentTimeMillis() < deadline) {
+ if (p.activePolls.isEmpty()) {
+ break;
+ }
+ Thread.sleep(25);
+ }
+
+ // After 1st failure: checkpoint not advanced, no DLQ delivery
+ verify(store, never()).saveForAccount(anyString(), any());
+ verify(sqsService, never()).sendMessage(anyString(), anyString(), anyInt(), anyString());
+
+ // Second poll: attempt 2 (retry 1, which exceeds maxRetryAttempts=1 -> exhausted!)
+ p.pollAndInvoke(esm);
+
+ // Checkpoint advanced to "s1"
+ verify(store, timeout(2000)).saveForAccount(eq(ACCOUNT_ID), any());
+ assertEquals("s1", esm.getShardSequenceNumbers().get(DynamoDbStreamService.SHARD_ID));
+
+ // SQS delivery invoked
+ ArgumentCaptor<String> bodyCaptor = ArgumentCaptor.forClass(String.class);
+ String expectedQueueUrl = "http://localhost:4566/000000000000/my-dlq";
+ verify(sqsService, timeout(2000)).sendMessage(eq(expectedQueueUrl), bodyCaptor.capture(), eq(0), eq("us-east-1"));
+
+ JsonNode dlqPayload = OBJECT_MAPPER.readTree(bodyCaptor.getValue());
+ assertEquals("1.0", dlqPayload.path("version").asText());
+ assertEquals("RetryAttemptsExhausted", dlqPayload.path("requestContext").path("condition").asText());
+ assertEquals(2, dlqPayload.path("requestContext").path("approximateInvokeCount").asInt());
+ assertEquals("req-batch-fail", dlqPayload.path("requestContext").path("requestId").asText());
+ assertEquals(200, dlqPayload.path("responseContext").path("statusCode").asInt());
+ assertFalse(dlqPayload.path("responseContext").has("functionError"));
+ assertEquals(DynamoDbStreamService.SHARD_ID, dlqPayload.path("DDBStreamBatchInfo").path("shardId").asText());
+ assertEquals("s1", dlqPayload.path("DDBStreamBatchInfo").path("startSequenceNumber").asText());
+ assertEquals("s1", dlqPayload.path("DDBStreamBatchInfo").path("endSequenceNumber").asText());
+ assertEquals(1, dlqPayload.path("DDBStreamBatchInfo").path("batchSize").asInt());
+ assertEquals(STREAM_ARN, dlqPayload.path("DDBStreamBatchInfo").path("streamArn").asText());
+ assertFalse(dlqPayload.has("hasBeenTruncated"));
+ }
+
+ @Test
+ void reportBatchItemFailuresPartialSuccessWithZeroRetriesExhaustsImmediately() throws Exception {
+ when(streamService.getShardIterator(eq(STREAM_ARN), eq(DynamoDbStreamService.SHARD_ID),
+ eq("TRIM_HORIZON"), any())).thenReturn("it-1");
+ when(streamService.getRecords(eq("it-1"), anyInt())).thenReturn(
+ new DynamoDbStreamService.GetRecordsResult(
+ List.of(ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}"),
+ ddbRecord("s2", "INSERT", "{\"status\":{\"S\":\"active\"}}")), "it-1"));
+
+ InvokeResult partialFailure = new InvokeResult();
+ partialFailure.setStatusCode(200);
+ partialFailure.setPayload("{\"batchItemFailures\":[{\"itemIdentifier\":\"s2\"}]}".getBytes());
+ when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(partialFailure);
+
+ LambdaFunction fn = new LambdaFunction();
+ fn.setFunctionName("fn");
+ when(functionStore.getForAccount(ACCOUNT_ID, "us-east-1", "fn")).thenReturn(Optional.of(fn));
+
+ EsmStore store = mock(EsmStore.class);
+ EventSourceMapping esm = filterEsm();
+ esm.setFunctionResponseTypes(List.of("ReportBatchItemFailures"));
+ esm.setMaximumRetryAttempts(0); // 0 retries allowed: initial failure exhausts immediately
+
+ String sqsArn = "arn:aws:sqs:us-east-1:000000000000:my-dlq";
+ EventSourceMapping.DestinationConfig destConfig = new EventSourceMapping.DestinationConfig();
+ EventSourceMapping.OnFailure onFailure = new EventSourceMapping.OnFailure();
+ onFailure.setDestination(sqsArn);
+ destConfig.setOnFailure(onFailure);
+ esm.setDestinationConfig(destConfig);
+
+ DynamoDbStreamsEventSourcePoller p = pollerWith(store);
+
+ // First poll: s1 succeeds, s2 fails -> maxRetries=0 exhausts immediately
+ p.pollAndInvoke(esm);
+
+ // Checkpoint advanced to "s2"
+ verify(store, timeout(2000)).saveForAccount(eq(ACCOUNT_ID), any());
+ assertEquals("s2", esm.getShardSequenceNumbers().get(DynamoDbStreamService.SHARD_ID));
+
+ ArgumentCaptor<String> bodyCaptor = ArgumentCaptor.forClass(String.class);
+ String expectedQueueUrl = "http://localhost:4566/000000000000/my-dlq";
+ verify(sqsService, timeout(2000)).sendMessage(eq(expectedQueueUrl), bodyCaptor.capture(), eq(0), eq("us-east-1"));
+
+ JsonNode dlqPayload = OBJECT_MAPPER.readTree(bodyCaptor.getValue());
+ assertEquals("1.0", dlqPayload.path("version").asText());
+ assertEquals("RetryAttemptsExhausted", dlqPayload.path("requestContext").path("condition").asText());
+ assertEquals(1, dlqPayload.path("requestContext").path("approximateInvokeCount").asInt());
+ assertEquals("s2", dlqPayload.path("DDBStreamBatchInfo").path("startSequenceNumber").asText());
+ assertEquals("s2", dlqPayload.path("DDBStreamBatchInfo").path("endSequenceNumber").asText());
+ assertEquals(1, dlqPayload.path("DDBStreamBatchInfo").path("batchSize").asInt());
+
+ // Prove there is NO second Lambda invocation for that failed item
+ verify(executorService, times(1)).invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse));
+ }
+
+ @Test
+ void reportBatchItemFailuresPartialSuccessAllowsOneRetryBeforeExhaustion() throws Exception {
+ when(streamService.getShardIterator(eq(STREAM_ARN), eq(DynamoDbStreamService.SHARD_ID),
+ eq("TRIM_HORIZON"), any())).thenReturn("it-1");
+ when(streamService.getShardIterator(eq(STREAM_ARN), eq(DynamoDbStreamService.SHARD_ID),
+ eq("AFTER_SEQUENCE_NUMBER"), eq("s1"))).thenReturn("it-2");
+ when(streamService.getRecords(eq("it-1"), anyInt())).thenReturn(
+ new DynamoDbStreamService.GetRecordsResult(
+ List.of(ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}"),
+ ddbRecord("s2", "INSERT", "{\"status\":{\"S\":\"active\"}}")), "it-1"));
+ when(streamService.getRecords(eq("it-2"), anyInt())).thenReturn(
+ new DynamoDbStreamService.GetRecordsResult(
+ List.of(ddbRecord("s2", "INSERT", "{\"status\":{\"S\":\"active\"}}")), "it-2"));
+
+ InvokeResult partialFailure = new InvokeResult();
+ partialFailure.setStatusCode(200);
+ partialFailure.setPayload("{\"batchItemFailures\":[{\"itemIdentifier\":\"s2\"}]}".getBytes());
+ when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(partialFailure);
+
+ LambdaFunction fn = new LambdaFunction();
+ fn.setFunctionName("fn");
+ when(functionStore.getForAccount(ACCOUNT_ID, "us-east-1", "fn")).thenReturn(Optional.of(fn));
+
+ EsmStore store = mock(EsmStore.class);
+ EventSourceMapping esm = filterEsm();
+ esm.setFunctionResponseTypes(List.of("ReportBatchItemFailures"));
+ esm.setMaximumRetryAttempts(1); // 1 retry allowed; 2nd failure exhausts
+
+ String sqsArn = "arn:aws:sqs:us-east-1:000000000000:my-dlq";
+ EventSourceMapping.DestinationConfig destConfig = new EventSourceMapping.DestinationConfig();
+ EventSourceMapping.OnFailure onFailure = new EventSourceMapping.OnFailure();
+ onFailure.setDestination(sqsArn);
+ destConfig.setOnFailure(onFailure);
+ esm.setDestinationConfig(destConfig);
+
+ DynamoDbStreamsEventSourcePoller p = pollerWith(store);
+
+ // First poll: s1 succeeds, s2 fails -> checkpoint advances to s1, retry count carried over, no DLQ delivery
+ p.pollAndInvoke(esm);
+ verify(store, timeout(2000)).saveForAccount(eq(ACCOUNT_ID), any());
+ assertEquals("s1", esm.getShardSequenceNumbers().get(DynamoDbStreamService.SHARD_ID));
+ verify(sqsService, never()).sendMessage(anyString(), anyString(), anyInt(), anyString());
+
+ long deadline = System.currentTimeMillis() + 3000;
+ while (System.currentTimeMillis() < deadline) {
+ if (p.activePolls.isEmpty()) {
+ break;
+ }
+ Thread.sleep(25);
+ }
+
+ // Second poll: fetches [s2], s2 fails again -> maxRetries=1 exhausts (attempt 2, retry 1)
+ p.pollAndInvoke(esm);
+
+ verify(store, timeout(2000).times(2)).saveForAccount(eq(ACCOUNT_ID), any());
+ assertEquals("s2", esm.getShardSequenceNumbers().get(DynamoDbStreamService.SHARD_ID));
+
+ ArgumentCaptor<String> bodyCaptor = ArgumentCaptor.forClass(String.class);
+ String expectedQueueUrl = "http://localhost:4566/000000000000/my-dlq";
+ verify(sqsService, timeout(2000)).sendMessage(eq(expectedQueueUrl), bodyCaptor.capture(), eq(0), eq("us-east-1"));
+
+ JsonNode dlqPayload = OBJECT_MAPPER.readTree(bodyCaptor.getValue());
+ assertEquals("1.0", dlqPayload.path("version").asText());
+ assertEquals("RetryAttemptsExhausted", dlqPayload.path("requestContext").path("condition").asText());
+ assertEquals(2, dlqPayload.path("requestContext").path("approximateInvokeCount").asInt());
+ assertEquals("s2", dlqPayload.path("DDBStreamBatchInfo").path("startSequenceNumber").asText());
+ assertEquals("s2", dlqPayload.path("DDBStreamBatchInfo").path("endSequenceNumber").asText());
+ assertEquals(1, dlqPayload.path("DDBStreamBatchInfo").path("batchSize").asInt());
+
+ verify(executorService, times(2)).invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse));
+ }
+
private JsonNode readRecords(byte[] payload) {
try {
return OBJECT_MAPPER.readTree(payload).path("Records");
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java
index 51192d0064..a12d82e6a2 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java
@@ -223,6 +223,7 @@ class EsmIntegrationTest {
.body("""
{
"BisectBatchOnFunctionError": true,
+ "MaximumRetryAttempts": 3,
"DestinationConfig": {
"OnFailure": {
"Destination": "%s"
@@ -235,6 +236,7 @@ class EsmIntegrationTest {
.then()
.statusCode(202)
.body("BisectBatchOnFunctionError", equalTo(true))
+ .body("MaximumRetryAttempts", equalTo(3))
.body("DestinationConfig.OnFailure.Destination", equalTo(destinationArn));
given()
@@ -243,6 +245,7 @@ class EsmIntegrationTest {
.then()
.statusCode(200)
.body("BisectBatchOnFunctionError", equalTo(true))
+ .body("MaximumRetryAttempts", equalTo(3))
.body("DestinationConfig.OnFailure.Destination", equalTo(destinationArn));
given()
@@ -266,6 +269,7 @@ class EsmIntegrationTest {
.then()
.statusCode(202)
.body("$", not(hasKey("BisectBatchOnFunctionError")))
+ .body("$", not(hasKey("MaximumRetryAttempts")))
.body("$", not(hasKey("DestinationConfig")))
.extract()
.path("UUID");