fix(lambda): support async retries and dead-letter queue (DLQ) for asynchronous invocations (#4251)

* fix(lambda): support async retries and dead-letter queue (DLQ)

- Add retry loop honoring MaximumRetryAttempts and MaximumEventAgeInSeconds in LambdaExecutorService
- Deliver original payload and message attributes (RequestID, ErrorCode, ErrorMessage) to SQS/SNS DLQ in AsyncInvokeDestinationRouter
- Give precedence to OnFailure destination over DeadLetterConfig
- Wrap EventInvokeConfig queries in RequestScopes.callAs for correct account partitioning
- Add comprehensive unit and integration tests covering retries and DLQ delivery

Closes #4194

* test(lambda): cover cross-account DLQ delivery

* fix(lambda): add missing async destination test helper

* test(lambda): allow async retry attempts in chain guard test

* fix(lambda): preserve async result on age expiry
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-25 20:35:23 -04:00
1 parent cd9843f5bd
commit c3c5c16c81
6 files changed
+546 -27

No files matched your search

@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.lambda.zip.CodeStore;
import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -23,6 +24,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
@@ -30,14 +32,19 @@ import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
@@ -383,6 +390,86 @@ class AsyncInvokeDestinationRouterTest {
.path("responseContext").path("executedVersion").asText());
}
@Test
@SuppressWarnings("unchecked")
void failedAsyncInvocation_sendsTheOriginalEventToDeadLetterQueue() {
fn.setDeadLetterTargetArn(QUEUE_ARN);
router.route(fn, request(), failure("Unhandled", "{\"errorMessage\":\"always fails\"}"), 0);
ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Map<String, MessageAttributeValue>> attrs = ArgumentCaptor.forClass(Map.class);
String queueUrl = "http://localhost:4566/000000000000/quotes-queue";
verify(sqsService).sendMessage(eq(queueUrl), body.capture(), anyInt(), eq(null), eq(null), attrs.capture(), eq("us-east-1"));
assertThat(body.getValue(), containsString("\"amount\":100000"));
assertThat(attrs.getValue().get("RequestID").getStringValue(), equalTo("req-1"));
assertThat(attrs.getValue().get("ErrorCode").getDataType(), equalTo("Number"));
assertThat(attrs.getValue().get("ErrorCode").getStringValue(), equalTo("200"));
assertThat(attrs.getValue().get("ErrorMessage").getStringValue(), equalTo("always fails"));
}
@Test
void eventAgeExpiration_usesRetriesExhaustedConditionWhenAwsBehaviorIsUnverified() {
configure(null, BUS_ARN);
router.route(fn, request(), failure("Unhandled", "{\"errorMessage\":\"Event age exceeded\"}"), 3, 0);
JsonNode detail = detailOf(capturedEventEntry());
assertEquals("RetriesExhausted", detail.path("requestContext").path("condition").asText());
}
@Test
void succeedingAsyncInvocation_sendsNothingToDeadLetterQueue() {
fn.setDeadLetterTargetArn(QUEUE_ARN);
router.route(fn, request(), success("{\"ok\":true}"), 0);
verify(sqsService, never()).sendMessage(anyString(), anyString(), anyInt(), any(), any(), any(), anyString());
}
@Test
@SuppressWarnings("unchecked")
void deadLetterTargetMayBeAnSnsTopic() {
fn.setDeadLetterTargetArn(TOPIC_ARN);
router.route(fn, request(), failure("Unhandled", "{\"errorMessage\":\"always fails\"}"), 0);
ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Map<String, MessageAttributeValue>> attrs = ArgumentCaptor.forClass(Map.class);
verify(snsService).publish(eq(TOPIC_ARN), eq(null), eq(null), body.capture(), eq("Lambda"), attrs.capture(), eq("us-east-1"));
assertThat(body.getValue(), containsString("\"amount\":100000"));
assertThat(attrs.getValue().get("RequestID").getStringValue(), equalTo("req-1"));
assertThat(attrs.getValue().get("ErrorCode").getDataType(), equalTo("Number"));
assertThat(attrs.getValue().get("ErrorCode").getStringValue(), equalTo("200"));
assertThat(attrs.getValue().get("ErrorMessage").getStringValue(), equalTo("always fails"));
}
@Test
@SuppressWarnings("unchecked")
void deadLetterQueue_truncatesErrorMessageTo1Kb() {
fn.setDeadLetterTargetArn(QUEUE_ARN);
String longError = "x".repeat(2000);
router.route(fn, request(), failure("Unhandled", "{\"errorMessage\":\"" + longError + "\"}"), 0);
ArgumentCaptor<Map<String, MessageAttributeValue>> attrs = ArgumentCaptor.forClass(Map.class);
String queueUrl = "http://localhost:4566/000000000000/quotes-queue";
verify(sqsService).sendMessage(eq(queueUrl), anyString(), anyInt(), eq(null), eq(null), attrs.capture(), eq("us-east-1"));
assertEquals(1024, attrs.getValue().get("ErrorMessage").getStringValue().getBytes(StandardCharsets.UTF_8).length);
}
@Test
void whenBothDestinationAndDeadLetterConfigAreConfigured_destinationTakesPrecedence() {
fn.setDeadLetterTargetArn(QUEUE_ARN);
configure(null, TOPIC_ARN);
router.route(fn, request(), failure("Unhandled", "{\"errorMessage\":\"always fails\"}"), 0);
verify(snsService).publish(eq(TOPIC_ARN), eq(null), anyString(), eq("Lambda"), eq("us-east-1"));
String queueUrl = "http://localhost:4566/000000000000/quotes-queue";
verify(sqsService, never()).sendMessage(eq(queueUrl), anyString(), anyInt(), any(), any(), any(), anyString());
}
private void configure(String onSuccess, String onFailure) {
FunctionEventInvokeConfig config = new FunctionEventInvokeConfig();
FunctionEventInvokeConfig.DestinationConfig destinations =
@@ -425,6 +512,10 @@ class AsyncInvokeDestinationRouterTest {
return new InvokeResult(200, null, payload.getBytes(), null, "req-1");
}
private static InvokeResult failure(String functionError, String payload) {
return new InvokeResult(200, functionError, payload.getBytes(), null, "req-1");
}
@SuppressWarnings("unchecked")
private static <T> Instance<T> instanceOf(T bean) {
Instance<T> instance = mock(Instance.class);
@@ -0,0 +1,108 @@
package io.github.hectorvent.floci.services.lambda;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.sqs.model.Message;
import io.github.hectorvent.floci.services.sqs.model.Queue;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@QuarkusTest
class LambdaDeadLetterQueueIntegrationTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String OTHER_ACCOUNT = "111122223333";
@Inject
LambdaService lambdaService;
@Inject
SqsService sqsService;
@Inject
AsyncInvokeDestinationRouter destinationRouter;
@Test
void failedInvocation_deliversPayloadAndAttributesToSqsDeadLetterQueue() {
String queueName = "dlq-integ-queue";
String functionName = "dlq-integ-fn";
Queue queue = RequestScopes.callAs(ACCOUNT, () ->
sqsService.createQueue(queueName, Map.of(), REGION));
String queueUrl = queue.getQueueUrl();
String queueArn = RequestScopes.callAs(ACCOUNT, () ->
sqsService.getQueueAttributes(queueUrl, List.of("QueueArn"), REGION).get("QueueArn"));
LambdaFunction fn = RequestScopes.callAs(ACCOUNT, () ->
lambdaService.createFunction(REGION, new HashMap<>(Map.of(
"FunctionName", functionName,
"Runtime", "nodejs22.x",
"Role", "arn:aws:iam::" + ACCOUNT + ":role/test-role",
"Handler", "index.handler",
"DeadLetterConfig", Map.of("TargetArn", queueArn)))));
assertEquals(queueArn, fn.getDeadLetterTargetArn());
byte[] requestPayload = "{\"probe\":1,\"message\":\"hello\"}".getBytes();
InvokeResult failureResult = new InvokeResult(200, "Unhandled",
"{\"errorMessage\":\"always fails\",\"errorType\":\"Error\"}".getBytes(),
null, "test-req-123");
destinationRouter.route(fn, requestPayload, failureResult, 0);
List<Message> messages = RequestScopes.callAs(ACCOUNT, () ->
sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION));
assertEquals(1, messages.size(), "DLQ should receive exactly 1 message");
Message message = messages.get(0);
assertEquals("{\"probe\":1,\"message\":\"hello\"}", message.getBody());
assertNotNull(message.getMessageAttributes());
assertThat(message.getMessageAttributes().get("RequestID").getStringValue(), equalTo("test-req-123"));
assertThat(message.getMessageAttributes().get("RequestID").getDataType(), equalTo("String"));
assertThat(message.getMessageAttributes().get("ErrorCode").getStringValue(), equalTo("200"));
assertThat(message.getMessageAttributes().get("ErrorCode").getDataType(), equalTo("Number"));
assertThat(message.getMessageAttributes().get("ErrorMessage").getStringValue(), equalTo("always fails"));
assertThat(message.getMessageAttributes().get("ErrorMessage").getDataType(), equalTo("String"));
}
@Test
void failedInvocation_deliversToDeadLetterQueueInTheTargetAccount() {
String queueName = "dlq-cross-account-queue";
String functionName = "dlq-cross-account-fn";
Queue queue = RequestScopes.callAs(OTHER_ACCOUNT, () ->
sqsService.createQueue(queueName, Map.of(), REGION));
String queueArn = RequestScopes.callAs(OTHER_ACCOUNT, () ->
sqsService.getQueueAttributes(queue.getQueueUrl(), List.of("QueueArn"), REGION).get("QueueArn"));
LambdaFunction fn = RequestScopes.callAs(ACCOUNT, () ->
lambdaService.createFunction(REGION, new HashMap<>(Map.of(
"FunctionName", functionName,
"Runtime", "nodejs22.x",
"Role", "arn:aws:iam::" + ACCOUNT + ":role/test-role",
"Handler", "index.handler",
"DeadLetterConfig", Map.of("TargetArn", queueArn)))));
InvokeResult failureResult = new InvokeResult(200, "Unhandled",
"{\"errorMessage\":\"always fails\"}".getBytes(), null, "test-cross-account-req");
destinationRouter.route(fn, "{\"probe\":1}".getBytes(), failureResult, 0);
List<Message> messages = RequestScopes.callAs(OTHER_ACCOUNT, () ->
sqsService.receiveMessage(queue.getQueueUrl(), 10, 0, 0, REGION));
assertEquals(1, messages.size(), "the DLQ should receive the failed invocation in its owning account");
assertEquals("{\"probe\":1}", messages.get(0).getBody());
}
}
@@ -3,19 +3,24 @@ package io.github.hectorvent.floci.services.lambda;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.lambda.launcher.ContainerHandle;
import io.github.hectorvent.floci.services.lambda.model.ContainerState;
import io.github.hectorvent.floci.services.lambda.model.FunctionEventInvokeConfig;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.lambda.model.PendingInvocation;
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -24,6 +29,7 @@ import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -33,6 +39,7 @@ import static org.mockito.Mockito.doAnswer;
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;
@@ -75,7 +82,7 @@ class LambdaExecutorServiceTest {
void asyncInvocationShortOfTheChainBound_stillRuns() {
executor.invoke(fn, "{}".getBytes(), InvocationType.Event, LambdaInvocationChain.MAX_DEPTH - 1);
verify(warmPool, timeout(5000)).acquire(fn);
verify(warmPool, timeout(5000).atLeastOnce()).acquire(fn);
}
@Test
@@ -96,7 +103,7 @@ class LambdaExecutorServiceTest {
byte[] payload = "{}".getBytes();
executor.invoke(fn, payload, InvocationType.Event, 0, "prod");
verify(router, timeout(5000)).route(eq(fn), eq(payload), any(InvokeResult.class), eq(0), eq("prod"));
verify(router, timeout(5000)).route(eq(fn), eq(payload), any(InvokeResult.class), eq(1), eq(0), eq("prod"));
}
@Test
@@ -257,14 +264,121 @@ class LambdaExecutorServiceTest {
doAnswer(inv -> {
routed.countDown();
return null;
}).when(router).route(any(), any(), any(), anyInt(), isNull());
}).when(router).route(any(), any(), any(), anyInt(), anyInt(), isNull());
byte[] payload = "{}".getBytes();
InvokeResult result = routingExecutor.invoke(fn, payload, InvocationType.Event);
assertEquals(202, result.getStatusCode());
assertTrue(routed.await(5, TimeUnit.SECONDS), "destination routing never ran");
verify(router).route(fn, payload, expected, 0, null);
verify(router).route(fn, payload, expected, 1, 0, null);
}
@Test
void eventInvocation_retriesFailedInvocationUpToMaximumRetryAttempts() throws Exception {
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
LambdaService lambdaService = mock(LambdaService.class);
FunctionEventInvokeConfig config = new FunctionEventInvokeConfig();
config.setMaximumRetryAttempts(2);
config.setMaximumEventAgeInSeconds(21600);
when(lambdaService.findEventInvokeConfig(fn, null)).thenReturn(Optional.of(config));
LambdaExecutorService retryExecutor =
new LambdaExecutorService(warmPool, new ObjectMapper(), concurrencyLimiter, router, lambdaService);
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
ContainerHandle handle = new ContainerHandle("cid-retry", "test-fn", rtas, ContainerState.WARM);
when(warmPool.acquire(any())).thenReturn(handle);
InvokeResult failureResult = new InvokeResult(200, "Unhandled",
"{\"errorMessage\":\"fails\"}".getBytes(), null, "req-retry");
doAnswer(invocation -> {
PendingInvocation pendingInvocation = invocation.getArgument(0);
pendingInvocation.getResultFuture().complete(failureResult);
return pendingInvocation.getResultFuture();
}).when(rtas).enqueue(any(PendingInvocation.class));
CountDownLatch routed = new CountDownLatch(1);
doAnswer(invocation -> {
routed.countDown();
return null;
}).when(router).route(any(), any(), any(), anyInt(), anyInt(), any());
byte[] payload = "{}".getBytes();
InvokeResult result = retryExecutor.invoke(fn, payload, InvocationType.Event);
assertEquals(202, result.getStatusCode());
assertTrue(routed.await(5, TimeUnit.SECONDS), "destination routing never ran");
verify(rtas, times(3)).enqueue(any(PendingInvocation.class));
verify(router).route(eq(fn), eq(payload), eq(failureResult), eq(3), eq(0), isNull());
}
@Test
void eventInvocation_stopsRetryingWhenMaxEventAgeExceeded() throws Exception {
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
LambdaService lambdaService = mock(LambdaService.class);
FunctionEventInvokeConfig config = new FunctionEventInvokeConfig();
config.setMaximumRetryAttempts(2);
config.setMaximumEventAgeInSeconds(0);
when(lambdaService.findEventInvokeConfig(fn, null)).thenReturn(Optional.of(config));
LambdaExecutorService retryExecutor =
new LambdaExecutorService(warmPool, new ObjectMapper(), concurrencyLimiter, router, lambdaService);
CountDownLatch routed = new CountDownLatch(1);
doAnswer(invocation -> {
routed.countDown();
return null;
}).when(router).route(any(), any(), any(), anyInt(), anyInt(), any());
byte[] payload = "{}".getBytes();
InvokeResult result = retryExecutor.invoke(fn, payload, InvocationType.Event);
assertEquals(202, result.getStatusCode());
assertTrue(routed.await(5, TimeUnit.SECONDS), "destination routing never ran");
verify(warmPool, never()).acquire(any());
ArgumentCaptor<InvokeResult> resultCaptor = ArgumentCaptor.forClass(InvokeResult.class);
verify(router).route(eq(fn), eq(payload), resultCaptor.capture(), eq(0), eq(0), isNull());
assertTrue(new String(resultCaptor.getValue().getPayload()).contains("EventAgeExceeded"),
"an event that expires before execution needs an expiration result");
}
@Test
void eventInvocation_preservesLastAttemptWhenAgeExpiresBetweenAttempts() throws Exception {
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
LambdaService lambdaService = mock(LambdaService.class);
FunctionEventInvokeConfig config = new FunctionEventInvokeConfig();
config.setMaximumRetryAttempts(2);
config.setMaximumEventAgeInSeconds(1);
when(lambdaService.findEventInvokeConfig(fn, null)).thenReturn(Optional.of(config));
MutableClock clock = new MutableClock();
LambdaExecutorService retryExecutor =
new LambdaExecutorService(warmPool, new ObjectMapper(), concurrencyLimiter, router, lambdaService, clock);
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
ContainerHandle handle = new ContainerHandle("cid-age-after-failure", "test-fn", rtas, ContainerState.WARM);
when(warmPool.acquire(any())).thenReturn(handle);
InvokeResult failedAttempt = new InvokeResult(200, "Unhandled",
"{\"errorMessage\":\"fails\"}".getBytes(), null, "req-age");
doAnswer(invocation -> {
clock.advance(Duration.ofSeconds(1));
PendingInvocation pendingInvocation = invocation.getArgument(0);
pendingInvocation.getResultFuture().complete(failedAttempt);
return pendingInvocation.getResultFuture();
}).when(rtas).enqueue(any(PendingInvocation.class));
CountDownLatch routed = new CountDownLatch(1);
doAnswer(invocation -> {
routed.countDown();
return null;
}).when(router).route(any(), any(), any(), anyInt(), anyInt(), any());
byte[] payload = "{}".getBytes();
InvokeResult result = retryExecutor.invoke(fn, payload, InvocationType.Event);
assertEquals(202, result.getStatusCode());
assertTrue(routed.await(5, TimeUnit.SECONDS), "destination routing never ran");
ArgumentCaptor<InvokeResult> resultCaptor = ArgumentCaptor.forClass(InvokeResult.class);
verify(router).route(eq(fn), eq(payload), resultCaptor.capture(), eq(1), eq(0), isNull());
assertSame(failedAttempt, resultCaptor.getValue(),
"age expiration should preserve the last invocation result");
}
@Test