diff --git a/docs/services/lambda.md b/docs/services/lambda.md index deef5ab7d4..d8afca65a4 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -57,17 +57,34 @@ Floci Lambda runs your function code locally inside real Docker containers - clo | `ListFunctionEventInvokeConfigs` | List the asynchronous invocation settings of every version and alias of a function | The event invoke configuration is stored and returned as AWS does, and `AWS::Lambda::EventInvokeConfig` -provisions it from a stack. Asynchronous invocations do not yet apply its retry or event age -settings. +provisions it from a stack. Asynchronous invocations apply its retry, event age, destination settings, +and dead-letter queue configurations (`DeadLetterConfig`). + +### Asynchronous Invocation Retries and Dead-Letter Queues + +An asynchronous invocation (`InvocationType: Event`) answers `202` immediately and runs on the background +pool. If the invocation fails, it is retried up to `MaximumRetryAttempts` (default: 2, total 3 attempts) +unless the event age exceeds `MaximumEventAgeInSeconds` (default: 21600 seconds, 6 hours). In Floci, +retries run back to back without the delays of live AWS (which waits roughly one minute and then two) to keep +local test runs fast. + +When retries are exhausted or event age is exceeded: + +- If an `OnFailure` destination is configured, the failure record is delivered to the destination. +- Otherwise, if a `DeadLetterConfig` (`TargetArn`) is configured on the function, the original request payload + is delivered to the specified SQS queue or SNS topic with `RequestID`, `ErrorCode` (Number), and `ErrorMessage` + (String, truncated to the first 1 KB) message attributes. +- If both are configured, Floci routes to the `OnFailure` destination rather than the dead-letter queue + by design choice (AWS describes dead-letter queues as an alternative to an on-failure destination without + specifying precedence). ### Asynchronous Invocation Destinations -An asynchronous invocation (`InvocationType: Event`) delivers its result to the `OnSuccess` or -`OnFailure` destination the configuration names. Four of AWS's five destination kinds are -supported, routed by the service in the destination ARN: an EventBridge event bus, an SQS queue, -an SNS topic, and another Lambda function. A function with no destination configured is unaffected, and delivery -never changes what the caller sees: the invoke still answers `202` immediately, and a destination -that rejects the record is logged rather than reported back. +An asynchronous invocation delivers its result to the `OnSuccess` or `OnFailure` destination the configuration +names. Four of AWS's five destination kinds are supported, routed by the service in the destination ARN: an EventBridge +event bus, an SQS queue, an SNS topic, and another Lambda function. A function with no destination configured +is unaffected, and delivery never changes what the caller sees: the invoke still answers `202` immediately, and +a destination that rejects the record is logged rather than reported back. Every destination receives the same invocation record AWS sends: @@ -92,8 +109,8 @@ detail type `Lambda Function Invocation Result - Success`, so a rule can match a function's own response at `detail.responsePayload.`. A failed invocation carries the detail type `Lambda Function Invocation Result - Failure`, a `condition` of `RetriesExhausted`, a `responseContext.functionError` of `Unhandled`, and the error as its `responsePayload`. That -`functionError` member is present only on a failure record. Since retries are not applied, a -failure reaches its destination once and `approximateInvokeCount` is always 1. +`functionError` member is present only on a failure record. The `approximateInvokeCount` field reflects +the actual number of attempts executed before completion or exhaustion. An alias-specific destination configuration is used when the alias is invoked. If the alias has none, Floci checks the configuration on the version that the alias resolves to. diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouter.java b/src/main/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouter.java index a49efc9e0f..57a949e3ad 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouter.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouter.java @@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.lambda.model.InvokeResult; import io.github.hectorvent.floci.services.lambda.model.LambdaFunction; 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.context.ApplicationScoped; import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; @@ -29,7 +30,8 @@ import java.util.Map; /** * Delivers the result of an asynchronous Lambda invocation to the {@code OnSuccess} or - * {@code OnFailure} destination of the function's event invoke configuration. + * {@code OnFailure} destination of the function's event invoke configuration, or its configured + * dead-letter queue when no failure destination is set. * *

Every destination carries the same asynchronous invocation record AWS sends, the envelope * around the event and the response that real CDK applications write EventBridge rules against @@ -43,8 +45,8 @@ import java.util.Map; * services into the executor eagerly would close a CDI cycle. The lookup happens per delivery, * which is also when a destination is first known to exist. * - *

Retries and event age are not applied, so a failed invocation reaches {@code OnFailure} - * once and its record's {@code approximateInvokeCount} is always 1. + *

Retries and event age are applied before delivery to {@code OnFailure}, so its record's + * {@code approximateInvokeCount} reflects the attempts executed. */ @ApplicationScoped public class AsyncInvokeDestinationRouter { @@ -66,9 +68,11 @@ public class AsyncInvokeDestinationRouter { private static final String SUCCESS_DETAIL_TYPE = "Lambda Function Invocation Result - Success"; private static final String FAILURE_DETAIL_TYPE = "Lambda Function Invocation Result - Failure"; private static final String SUCCESS_CONDITION = "Success"; + // AWS documents RetriesExhausted in its example, but does not establish a distinct condition + // for maximum-age expiration, so Floci keeps the documented condition for both failures. private static final String FAILURE_CONDITION = "RetriesExhausted"; private static final String DEFAULT_VERSION = "$LATEST"; - /** Floci does not retry a failed asynchronous invocation, so every record is the first attempt. */ + /** Default fallback invoke count when not explicitly provided by the caller. */ private static final int APPROXIMATE_INVOKE_COUNT = 1; private final Instance lambdaService; @@ -108,11 +112,21 @@ public class AsyncInvokeDestinationRouter { * {@link LambdaInvocationChain} instead of running forever */ public void route(LambdaFunction fn, byte[] requestPayload, InvokeResult result, int chainDepth) { - route(fn, requestPayload, result, chainDepth, null); + route(fn, requestPayload, result, APPROXIMATE_INVOKE_COUNT, chainDepth, null); } public void route(LambdaFunction fn, byte[] requestPayload, InvokeResult result, int chainDepth, String invokedQualifier) { + route(fn, requestPayload, result, APPROXIMATE_INVOKE_COUNT, chainDepth, invokedQualifier); + } + + public void route(LambdaFunction fn, byte[] requestPayload, InvokeResult result, + int approximateInvokeCount, int chainDepth) { + route(fn, requestPayload, result, approximateInvokeCount, chainDepth, null); + } + + public void route(LambdaFunction fn, byte[] requestPayload, InvokeResult result, + int approximateInvokeCount, int chainDepth, String invokedQualifier) { // A runtime that never started, timed out, or crashed is reported as a function error by // the executor, so this one test covers a handler error and a failed runtime alike. boolean failed = result.getFunctionError() != null; @@ -126,18 +140,91 @@ public class AsyncInvokeDestinationRouter { } if (destination == null || destination.getDestination() == null || destination.getDestination().isBlank()) { + if (failed && fn.getDeadLetterTargetArn() != null && !fn.getDeadLetterTargetArn().isBlank()) { + deliverToDeadLetterQueue(fn, requestPayload, result); + } return; } String arn = destination.getDestination(); try { - deliver(arn, fn, buildRecord(fn, requestPayload, result, failed), failed, chainDepth); + deliver(arn, fn, buildRecord(fn, requestPayload, result, failed, approximateInvokeCount), + failed, chainDepth); } catch (Exception e) { LOG.warnv("Failed to deliver the Lambda {0} destination record for {1} to {2}: {3}", side(failed), fn.getFunctionArn(), arn, e.getMessage()); } } + private void deliverToDeadLetterQueue(LambdaFunction fn, byte[] requestPayload, InvokeResult result) { + String arn = fn.getDeadLetterTargetArn(); + if (!AwsArnUtils.isArn(arn)) { + LOG.warnv("Invalid DeadLetterConfig TargetArn: {0}", arn); + return; + } + + String destinationAccount = AwsArnUtils.accountOrDefault(arn, fn.getAccountId()); + String region = AwsArnUtils.regionOrDefault(arn, + AwsArnUtils.regionOrDefault(fn.getFunctionArn(), null)); + String body = requestPayload != null ? new String(requestPayload, StandardCharsets.UTF_8) : ""; + String requestId = result.getRequestId() != null ? result.getRequestId() : ""; + String errorCode = String.valueOf(result.getStatusCode()); + String errorMessage = extractErrorMessage(result); + + Map attributes = new LinkedHashMap<>(); + attributes.put("RequestID", new MessageAttributeValue(requestId, "String")); + attributes.put("ErrorCode", new MessageAttributeValue(errorCode, "Number")); + attributes.put("ErrorMessage", new MessageAttributeValue(errorMessage, "String")); + + try { + boolean delivered = switch (AwsArnUtils.parse(arn).service()) { + case "sqs" -> { + RequestScopes.runAs(destinationAccount, () -> + sqsService.get().sendMessage(AwsArnUtils.arnToQueueUrl(arn, baseUrl), + body, 0, null, null, attributes, region)); + yield true; + } + case "sns" -> { + RequestScopes.runAs(destinationAccount, () -> + snsService.get().publish(arn, null, null, body, "Lambda", attributes, region)); + yield true; + } + default -> { + LOG.warnv("Unsupported DeadLetterConfig service, dropping the record: {0}", arn); + yield false; + } + }; + if (delivered) { + LOG.debugv("Lambda DeadLetterConfig delivered to {0}", arn); + } + } catch (Exception e) { + LOG.warnv("Failed to deliver the Lambda DeadLetterConfig for {0} to {1}: {2}", + fn.getFunctionArn(), arn, e.getMessage()); + } + } + + private String extractErrorMessage(InvokeResult result) { + String message = null; + if (result.getPayload() != null && result.getPayload().length > 0) { + try { + JsonNode node = objectMapper.readTree(result.getPayload()); + if (node.hasNonNull("errorMessage")) { + message = node.get("errorMessage").asText(); + } + } catch (Exception ignored) { + // Non-JSON payloads fall back to the function error below. + } + } + if (message == null) { + message = result.getFunctionError() != null ? result.getFunctionError() : "Unknown error"; + } + byte[] bytes = message.getBytes(StandardCharsets.UTF_8); + if (bytes.length > 1024) { + message = new String(bytes, 0, 1024, StandardCharsets.UTF_8); + } + return message; + } + private FunctionEventInvokeConfig.Destination destinationFor(LambdaFunction fn, boolean failed, String invokedQualifier) { FunctionEventInvokeConfig config = (invokedQualifier == null @@ -168,7 +255,7 @@ public class AsyncInvokeDestinationRouter { * function ARN carries the executed version, as it does in a real record. */ private ObjectNode buildRecord(LambdaFunction fn, byte[] requestPayload, - InvokeResult result, boolean failed) { + InvokeResult result, boolean failed, int approximateInvokeCount) { String version = executedVersion(fn); ObjectNode record = objectMapper.createObjectNode(); record.put("version", RECORD_VERSION); @@ -178,7 +265,7 @@ public class AsyncInvokeDestinationRouter { requestContext.put("requestId", result.getRequestId()); requestContext.put("functionArn", qualifiedFunctionArn(fn, version)); requestContext.put("condition", failed ? FAILURE_CONDITION : SUCCESS_CONDITION); - requestContext.put("approximateInvokeCount", APPROXIMATE_INVOKE_COUNT); + requestContext.put("approximateInvokeCount", approximateInvokeCount); record.set("requestPayload", payloadNode(requestPayload)); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorService.java index 64d79bc2c8..0b89071bdf 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorService.java @@ -3,15 +3,18 @@ package io.github.hectorvent.floci.services.lambda; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.services.lambda.launcher.ContainerHandle; +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 jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.time.Clock; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -40,6 +43,9 @@ public class LambdaExecutorService { private final LambdaConcurrencyLimiter concurrencyLimiter; /** Null in the constructor tests use, which exercise execution rather than delivery. */ private final AsyncInvokeDestinationRouter destinationRouter; + private final Instance lambdaServiceInstance; + private final LambdaService directLambdaService; + private final Clock clock; private final ExecutorService asyncExecutor = new ThreadPoolExecutor( Math.max(4, Runtime.getRuntime().availableProcessors() * 2), Math.max(8, Runtime.getRuntime().availableProcessors() * 4), @@ -51,18 +57,60 @@ public class LambdaExecutorService { public LambdaExecutorService(WarmPool warmPool, ObjectMapper objectMapper, LambdaConcurrencyLimiter concurrencyLimiter, - AsyncInvokeDestinationRouter destinationRouter) { + AsyncInvokeDestinationRouter destinationRouter, + Instance lambdaServiceInstance, + Clock clock) { + this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, lambdaServiceInstance, null, clock); + } + + LambdaExecutorService(WarmPool warmPool, + ObjectMapper objectMapper, + LambdaConcurrencyLimiter concurrencyLimiter, + AsyncInvokeDestinationRouter destinationRouter, + LambdaService directLambdaService) { + this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, null, directLambdaService, + Clock.systemUTC()); + } + + LambdaExecutorService(WarmPool warmPool, + ObjectMapper objectMapper, + LambdaConcurrencyLimiter concurrencyLimiter, + AsyncInvokeDestinationRouter destinationRouter, + LambdaService directLambdaService, + Clock clock) { + this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, null, directLambdaService, clock); + } + + private LambdaExecutorService(WarmPool warmPool, + ObjectMapper objectMapper, + LambdaConcurrencyLimiter concurrencyLimiter, + AsyncInvokeDestinationRouter destinationRouter, + Instance lambdaServiceInstance, + LambdaService directLambdaService, + Clock clock) { this.warmPool = warmPool; this.objectMapper = objectMapper; this.concurrencyLimiter = concurrencyLimiter; this.destinationRouter = destinationRouter; + this.lambdaServiceInstance = lambdaServiceInstance; + this.directLambdaService = directLambdaService; + this.clock = clock; } /** Package-private constructor for testing without CDI, leaving destinations unrouted. */ LambdaExecutorService(WarmPool warmPool, ObjectMapper objectMapper, LambdaConcurrencyLimiter concurrencyLimiter) { - this(warmPool, objectMapper, concurrencyLimiter, null); + this(warmPool, objectMapper, concurrencyLimiter, null, (Instance) null, null, + Clock.systemUTC()); + } + + LambdaExecutorService(WarmPool warmPool, + ObjectMapper objectMapper, + LambdaConcurrencyLimiter concurrencyLimiter, + AsyncInvokeDestinationRouter destinationRouter) { + this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, + (Instance) null, null, Clock.systemUTC()); } public InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type) { @@ -101,16 +149,60 @@ public class LambdaExecutorService { LambdaConcurrencyLimiter.Permit permit = concurrencyLimiter.acquire(fn); if (type == InvocationType.Event) { + LambdaService lambdaService = resolveLambdaService(); + FunctionEventInvokeConfig eventInvokeConfig = null; + if (lambdaService != null) { + try { + eventInvokeConfig = lambdaService.findEventInvokeConfig(fn, invokedQualifier).orElse(null); + } catch (Exception e) { + LOG.warnv("Could not read event invoke configuration for {0}: {1}", + fn.getFunctionArn(), e.getMessage()); + } + } + + int maxRetries = eventInvokeConfig != null && eventInvokeConfig.getMaximumRetryAttempts() != null + ? eventInvokeConfig.getMaximumRetryAttempts() : 2; + int maxEventAgeSeconds = eventInvokeConfig != null + && eventInvokeConfig.getMaximumEventAgeInSeconds() != null + ? eventInvokeConfig.getMaximumEventAgeInSeconds() : 21600; + long submitTimeMs = clock.millis(); + try { asyncExecutor.submit(() -> { - InvokeResult asyncResult; + int attempt = 0; + InvokeResult asyncResult = null; try { - asyncResult = executeSync(fn, payload, requestId); + while (attempt <= maxRetries) { + long elapsedSeconds = (clock.millis() - submitTimeMs) / 1000; + if (elapsedSeconds >= maxEventAgeSeconds) { + break; + } + + attempt++; + asyncResult = executeSync(fn, payload, requestId); + if (asyncResult.getFunctionError() == null && asyncResult.getStatusCode() < 300) { + break; + } + } + } catch (Exception e) { + LOG.warnv("Error in async Lambda execution for {0}: {1}", fn.getFunctionName(), e.getMessage()); + if (asyncResult == null) { + asyncResult = new InvokeResult(500, "Unhandled", + buildErrorPayload("Error executing Lambda: " + e.getMessage(), "Lambda.UnknownError"), + null, requestId); + } } finally { permit.close(); } if (destinationRouter != null) { - destinationRouter.route(fn, payload, asyncResult, chainDepth, invokedQualifier); + if (asyncResult == null) { + // This Floci-only placeholder covers expiry before any attempt; AWS documents no payload. + asyncResult = new InvokeResult(200, "Unhandled", + buildErrorPayload("Event age exceeded", "EventAgeExceeded"), + null, requestId); + } + destinationRouter.route(fn, payload, asyncResult, attempt, + chainDepth, invokedQualifier); } }); } catch (RuntimeException e) { @@ -127,6 +219,16 @@ public class LambdaExecutorService { } } + private LambdaService resolveLambdaService() { + if (directLambdaService != null) { + return directLambdaService; + } + if (lambdaServiceInstance != null && lambdaServiceInstance.isResolvable()) { + return lambdaServiceInstance.get(); + } + return null; + } + private InvokeResult executeSync(LambdaFunction fn, byte[] payload, String requestId) { ContainerHandle handle; try { diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouterTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouterTest.java index 288aff03e5..2274c7c86c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouterTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouterTest.java @@ -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 body = ArgumentCaptor.forClass(String.class); + ArgumentCaptor> 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 body = ArgumentCaptor.forClass(String.class); + ArgumentCaptor> 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> 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 Instance instanceOf(T bean) { Instance instance = mock(Instance.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaDeadLetterQueueIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaDeadLetterQueueIntegrationTest.java new file mode 100644 index 0000000000..ed58d22b24 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaDeadLetterQueueIntegrationTest.java @@ -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 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 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()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorServiceTest.java index d4bf6b76d5..4f9d835e9a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorServiceTest.java @@ -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 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 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