Light, fluffy, and always free - The AWS Local Emulator alternative
feat(lambda): deliver asynchronous invocation results to configured destinations (#4247)
Allen Sanborn97a2a08e1f3e
diff --git a/docs/services/lambda.md b/docs/services/lambda.mdindex 49a4cbfc86..ab797054b4 100644--- a/docs/services/lambda.md+++ b/docs/services/lambda.md@@ -52,8 +52,63 @@ 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, event age or-destination settings.+provisions it from a stack. Asynchronous invocations do not yet apply its retry or event age+settings.++### 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.++Every destination receives the same invocation record AWS sends:++```json+{+ "version": "1.0",+ "timestamp": "2026-09-22T10:15:31.123Z",+ "requestContext": {+ "requestId": "8ea123e4-1db7-4aba-9559-05a9a25c8b78",+ "functionArn": "arn:aws:lambda:us-east-1:000000000000:function:bank-pawnshop:$LATEST",+ "condition": "Success",+ "approximateInvokeCount": 1+ },+ "requestPayload": { "bankId": "BANK-PawnShop" },+ "responseContext": { "statusCode": 200, "executedVersion": "$LATEST" },+ "responsePayload": { "bankId": "PawnShop", "rate": 3.5 }+}+```++On an EventBridge destination the record is the event `detail`, under the source `lambda` and the+detail type `Lambda Function Invocation Result - Success`, so a rule can match a field of the+function's own response at `detail.responsePayload.<field>`. 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.++Three limits are worth knowing:++- **A destination configured on an alias does not fire.** The configuration is matched against the+ version the invocation actually ran, so one stored for `$LATEST` or for an explicit version is+ found, while one stored for an alias (`Qualifier: prod`) is not, and nothing is delivered. The+ CDK `onSuccess` and `onFailure` properties store theirs under `$LATEST`, so a destination+ declared that way is unaffected.+- **An S3 `OnFailure` destination is not delivered.** AWS added an S3 bucket as a fifth+ destination kind, on failure only. Floci routes on the service in the destination ARN and has+ no `s3` arm, so such a record is dropped with a warning rather than written to the bucket. The+ configuration is still stored and read back, so Terraform and CloudFormation converge; only the+ delivery is missing.+- **A chain of Lambda destinations stops at 16 hops, but only a chain of Lambda destinations.** A+ function whose `OnSuccess` names another function would otherwise invoke forever; AWS halts such+ a chain at about the same depth through recursive loop detection, and here the record at the+ sixteenth hop is dropped with a warning. The bound is keyed on the destination being a Lambda+ ARN, so a cycle that leaves and re-enters Lambda by another route is **not** bounded: a topic+ that fans back to the function, or a bus rule targeting it, each start a fresh chain at zero.+ Avoid configuring one until this is closed.## Hot-Reloading via Reactive S3 Syncdiff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouter.java b/src/main/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouter.javanew file mode 100644index 0000000000..8b6a2e87dd--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouter.java@@ -0,0 +1,314 @@+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.RequestScopes;+import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;+import io.github.hectorvent.floci.services.lambda.model.FunctionEventInvokeConfig;+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.sns.SnsService;+import io.github.hectorvent.floci.services.sqs.SqsService;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.enterprise.inject.Instance;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.nio.charset.StandardCharsets;+import java.time.Instant;+import java.time.ZoneOffset;+import java.time.format.DateTimeFormatter;+import java.util.LinkedHashMap;+import java.util.List;+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.+ *+ * <p>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+ * ({@code detail.responsePayload.<field>}). An EventBridge destination puts that record on the+ * bus as the event {@code detail}; SQS, SNS and Lambda destinations receive it as the message or+ * the event payload.+ *+ * <p>This lives outside {@link LambdaExecutorService} and reaches its collaborators through+ * {@link Instance} because the dependency graph runs the other way: {@code SnsService} invokes+ * its Lambda subscribers and {@code EventBridgeInvoker} its Lambda targets, so injecting those+ * 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.+ *+ * <p>Retries and event age are not applied, so a failed invocation reaches {@code OnFailure}+ * once and its record's {@code approximateInvokeCount} is always 1.+ */+@ApplicationScoped+public class AsyncInvokeDestinationRouter {++ private static final Logger LOG = Logger.getLogger(AsyncInvokeDestinationRouter.class);++ /**+ * Milliseconds, always three digits. {@code Instant.toString()} emits micro or nanosecond+ * precision on JDK 9+, and emits NO fractional part at all when the nanos happen to be zero,+ * so a consumer parsing the record with a fixed {@code .SSS} pattern breaks roughly once in a+ * billion records. AWS always emits milliseconds. Same formatter shape as+ * {@code ElasticBeanstalkQueryHandler}.+ */+ private static final DateTimeFormatter RECORD_TIMESTAMP =+ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);++ private static final String RECORD_VERSION = "1.0";+ private static final String EVENT_SOURCE = "lambda";+ 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";+ 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. */+ private static final int APPROXIMATE_INVOKE_COUNT = 1;+ /**+ * How many Lambda destination hops a single originating invocation may take. A function whose+ * destination leads back into itself would otherwise invoke forever, which on a laptop is a+ * worse failure than on AWS, where recursive loop detection halts the chain. The bound matches+ * the depth AWS stops at.+ */+ private static final int MAX_DESTINATION_CHAIN_DEPTH = 16;++ private final Instance<LambdaService> lambdaService;+ private final Instance<EventBridgeService> eventBridgeService;+ private final Instance<SqsService> sqsService;+ private final Instance<SnsService> snsService;+ private final ObjectMapper objectMapper;+ private final String baseUrl;++ @Inject+ public AsyncInvokeDestinationRouter(Instance<LambdaService> lambdaService,+ Instance<EventBridgeService> eventBridgeService,+ Instance<SqsService> sqsService,+ Instance<SnsService> snsService,+ ObjectMapper objectMapper,+ EmulatorConfig config) {+ this.lambdaService = lambdaService;+ this.eventBridgeService = eventBridgeService;+ this.sqsService = sqsService;+ this.snsService = snsService;+ this.objectMapper = objectMapper;+ this.baseUrl = config.baseUrl();+ }++ /**+ * Delivers the result of one asynchronous invocation to the destination configured for its+ * outcome, and does nothing at all when the function has no event invoke configuration or+ * that configuration names no destination for this side.+ *+ * <p>Never throws. The caller answered the invoke with 202 long before the function+ * finished, so a destination that rejects the record has nowhere left to be reported and is+ * logged instead.+ *+ * @param chainDepth how many Lambda destination deliveries led to this invocation, which+ * bounds a chain of them that leads back into itself+ */+ public void route(LambdaFunction fn, byte[] requestPayload, InvokeResult result, int chainDepth) {+ // 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;+ FunctionEventInvokeConfig.Destination destination;+ try {+ destination = destinationFor(fn, failed);+ } catch (Exception e) {+ LOG.warnv("Could not read the event invoke configuration of {0}: {1}",+ fn.getFunctionArn(), e.getMessage());+ return;+ }+ if (destination == null || destination.getDestination() == null+ || destination.getDestination().isBlank()) {+ return;+ }++ String arn = destination.getDestination();+ try {+ deliver(arn, fn, buildRecord(fn, requestPayload, result, failed), 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 FunctionEventInvokeConfig.Destination destinationFor(LambdaFunction fn, boolean failed) {+ FunctionEventInvokeConfig config = lambdaService.get().findEventInvokeConfig(fn).orElse(null);+ if (config == null || config.getDestinationConfig() == null) {+ return null;+ }+ return failed+ ? config.getDestinationConfig().getOnFailure()+ : config.getDestinationConfig().getOnSuccess();+ }++ /**+ * The record timestamp, always with exactly three fractional digits.+ *+ * <p>Package-private so a test can pin it at a ZERO-NANOSECOND instant. That input is the+ * only one that separates this from {@code truncatedTo(MILLIS).toString()}, which looks+ * equivalent and drops the fraction entirely on an exact second. A test that only formats+ * {@code now()} passes against both roughly 999 times in 1000.+ */+ static String formatRecordTimestamp(Instant instant) {+ return RECORD_TIMESTAMP.format(instant);+ }++ /**+ * The asynchronous invocation record, the shape AWS delivers to every destination kind. The+ * function ARN carries the executed version, as it does in a real record.+ */+ private ObjectNode buildRecord(LambdaFunction fn, byte[] requestPayload,+ InvokeResult result, boolean failed) {+ String version = executedVersion(fn);+ ObjectNode record = objectMapper.createObjectNode();+ record.put("version", RECORD_VERSION);+ record.put("timestamp", formatRecordTimestamp(Instant.now()));++ ObjectNode requestContext = record.putObject("requestContext");+ 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);++ record.set("requestPayload", payloadNode(requestPayload));++ ObjectNode responseContext = record.putObject("responseContext");+ responseContext.put("statusCode", result.getStatusCode());+ responseContext.put("executedVersion", version);+ // Present only on a failure record, carrying the same Handled/Unhandled value the+ // synchronous invoke reports in its X-Amz-Function-Error header.+ if (result.getFunctionError() != null) {+ responseContext.put("functionError", result.getFunctionError());+ }++ record.set("responsePayload", payloadNode(result.getPayload()));+ return record;+ }++ private void deliver(String arn, LambdaFunction fn, ObjectNode record, boolean failed, int chainDepth) {+ String region = AwsArnUtils.regionOrDefault(arn,+ AwsArnUtils.regionOrDefault(fn.getFunctionArn(), null));+ String accountId = AwsArnUtils.accountOrDefault(arn, fn.getAccountId());+ String body = record.toString();++ // The invocation ran on a pool thread that carries no request context, so the account the+ // destination lives in has to be re-established before any account-aware store is read.+ boolean delivered = switch (AwsArnUtils.isArn(arn) ? AwsArnUtils.parse(arn).service() : "") {+ case "events" -> {+ RequestScopes.runAs(accountId, () ->+ putOnEventBus(arn, body, region, failed, fn.getFunctionArn()));+ yield true;+ }+ case "sqs" -> {+ RequestScopes.runAs(accountId, () ->+ sqsService.get().sendMessage(AwsArnUtils.arnToQueueUrl(arn, baseUrl), body, 0, region));+ yield true;+ }+ case "sns" -> {+ RequestScopes.runAs(accountId, () ->+ snsService.get().publish(arn, null, body, "Lambda", region));+ yield true;+ }+ case "lambda" -> invokeDestinationFunction(arn, fn, body, accountId, failed, chainDepth);+ default -> {+ LOG.warnv("Unsupported Lambda {0} destination, dropping the record: {1}", side(failed), arn);+ yield false;+ }+ };+ if (delivered) {+ LOG.debugv("Lambda {0} destination delivered to {1}", side(failed), arn);+ }+ }++ /**+ * Invokes a Lambda destination unless the chain that reached it is already at its bound, and+ * answers whether it did.+ */+ private boolean invokeDestinationFunction(String arn, LambdaFunction fn, String body,+ String accountId, boolean failed, int chainDepth) {+ if (chainDepth >= MAX_DESTINATION_CHAIN_DEPTH) {+ LOG.warnv("Lambda {0} destination chain from {1} reached {2} hops at {3}; dropping the "+ + "record rather than continuing a chain that leads back into itself",+ side(failed), fn.getFunctionArn(), MAX_DESTINATION_CHAIN_DEPTH, arn);+ return false;+ }+ RequestScopes.runAs(accountId, () ->+ lambdaService.get().invokeArnFromDestination(+ arn, body.getBytes(StandardCharsets.UTF_8), chainDepth + 1));+ return true;+ }++ /**+ * Puts the record on the bus as the event {@code detail}. The source and detail type are the+ * fixed ones AWS uses, which is what a rule on a Lambda destination matches against.+ *+ * <p>{@code Resources} carries the invoked function and the destination, as AWS fills it.+ * Without it a rule whose pattern matches on {@code resources} never fires, and by a worse+ * route than a plain mismatch: {@code EventBridgeService.matchesPattern} casts+ * {@code event.get("Resources")} to an ArrayNode unconditionally, so an ABSENT member throws+ * NPE, which is swallowed by the surrounding catch, logged as {@code Failed to parse event+ * pattern} and reported as no-match. The record is then dropped at the bus rather than at the+ * destination, and the log blames the caller's pattern. Rules matching on {@code detail} are+ * unaffected, which is why this stayed invisible.+ */+ private void putOnEventBus(String busArn, String detail, String region, boolean failed,+ String functionArn) {+ Map<String, Object> entry = new LinkedHashMap<>();+ // PutEvents takes a full event-bus ARN as EventBusName and validates it.+ entry.put("EventBusName", busArn);+ entry.put("Source", EVENT_SOURCE);+ entry.put("DetailType", failed ? FAILURE_DETAIL_TYPE : SUCCESS_DETAIL_TYPE);+ entry.put("Detail", detail);+ ArrayNode resources = objectMapper.createArrayNode();+ if (functionArn != null && !functionArn.isBlank()) {+ resources.add(functionArn);+ }+ resources.add(busArn);+ entry.put("Resources", resources);+ // A null account routes the bus lookup through the request context just established,+ // the only path that carries the un-prefixed legacy-key fallback.+ EventBridgeService.PutEventsResult result =+ eventBridgeService.get().putEvents(List.of(entry), region, null);+ if (result.failedCount() > 0) {+ LOG.warnv("EventBridge rejected the Lambda {0} destination record for {1}: {2}",+ side(failed), busArn, result.entries());+ }+ }++ /**+ * The payload as JSON when it parses as JSON, and as a JSON string otherwise. AWS records the+ * event and the response verbatim and both are JSON for every runtime, so the string arm only+ * catches a runtime that wrote something else, which is still worth reporting.+ */+ private JsonNode payloadNode(byte[] payload) {+ if (payload == null || payload.length == 0) {+ return objectMapper.nullNode();+ }+ try {+ return objectMapper.readTree(payload);+ } catch (Exception e) {+ return objectMapper.getNodeFactory().textNode(new String(payload, StandardCharsets.UTF_8));+ }+ }++ private static String qualifiedFunctionArn(LambdaFunction fn, String version) {+ String arn = fn.getFunctionArn();+ return arn.endsWith(":" + version) ? arn : arn + ":" + version;+ }++ private static String executedVersion(LambdaFunction fn) {+ String version = fn.getVersion();+ return version == null || version.isBlank() ? DEFAULT_VERSION : version;+ }++ private static String side(boolean failed) {+ return failed ? "OnFailure" : "OnSuccess";+ }+}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.javaindex 4ab412af05..b52463f236 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@@ -23,6 +23,10 @@ import java.util.concurrent.TimeoutException;/*** Orchestrates Lambda function invocations.* Handles RequestResponse (sync), Event (async fire-and-forget), and DryRun modes.+ *+ * <p>An Event invocation answers 202 straight away and, once the function has finished on the+ * pool, hands its result to {@link AsyncInvokeDestinationRouter}, which delivers it to the+ * function's configured destination when it has one.*/@ApplicationScopedpublic class LambdaExecutorService {@@ -34,6 +38,8 @@ public class LambdaExecutorService {private final WarmPool warmPool;private final ObjectMapper objectMapper;private final LambdaConcurrencyLimiter concurrencyLimiter;+ /** Null in the constructor tests use, which exercise execution rather than delivery. */+ private final AsyncInvokeDestinationRouter destinationRouter;private final ExecutorService asyncExecutor = new ThreadPoolExecutor(Math.max(4, Runtime.getRuntime().availableProcessors() * 2),Math.max(8, Runtime.getRuntime().availableProcessors() * 4),@@ -44,13 +50,31 @@ public class LambdaExecutorService {@Injectpublic LambdaExecutorService(WarmPool warmPool,ObjectMapper objectMapper,- LambdaConcurrencyLimiter concurrencyLimiter) {+ LambdaConcurrencyLimiter concurrencyLimiter,+ AsyncInvokeDestinationRouter destinationRouter) {this.warmPool = warmPool;this.objectMapper = objectMapper;this.concurrencyLimiter = concurrencyLimiter;+ this.destinationRouter = destinationRouter;+ }++ /** Package-private constructor for testing without CDI, leaving destinations unrouted. */+ LambdaExecutorService(WarmPool warmPool,+ ObjectMapper objectMapper,+ LambdaConcurrencyLimiter concurrencyLimiter) {+ this(warmPool, objectMapper, concurrencyLimiter, null);}public InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type) {+ return invoke(fn, payload, type, 0);+ }++ /**+ * Invokes {@code fn}, carrying the number of Lambda destination deliveries that led here.+ * A direct invoke starts at zero; each delivery to a Lambda destination adds one, which is+ * what bounds a destination chain that points back at a function already in it.+ */+ InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth) {String requestId = UUID.randomUUID().toString();if (type == InvocationType.DryRun) {@@ -62,11 +86,15 @@ public class LambdaExecutorService {if (type == InvocationType.Event) {try {asyncExecutor.submit(() -> {+ InvokeResult asyncResult;try {- executeSync(fn, payload, requestId);+ asyncResult = executeSync(fn, payload, requestId);} finally {permit.close();}+ if (destinationRouter != null) {+ destinationRouter.route(fn, payload, asyncResult, chainDepth);+ }});} catch (RuntimeException e) {permit.close();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.javaindex e0b837aa23..5b8e490231 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@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.CustomResourceLiveness;import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.RequestScopes;import io.github.hectorvent.floci.core.storage.StorageBackedMap;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.core.resource.ExplorerResource;@@ -1046,11 +1047,23 @@ public class LambdaService implements ResourceProvider {/** Invokes a Lambda target ARN using the account encoded in that ARN. */public InvokeResult invokeArn(String functionArn, byte[] payload, InvocationType type) {+ return invokeArn(functionArn, payload, type, 0);+ }++ /**+ * Invokes a Lambda destination, carrying the number of destination deliveries that reached it+ * so {@link AsyncInvokeDestinationRouter} can bound a chain that leads back into itself.+ */+ InvokeResult invokeArnFromDestination(String functionArn, byte[] payload, int chainDepth) {+ return invokeArn(functionArn, payload, InvocationType.Event, chainDepth);+ }++ private InvokeResult invokeArn(String functionArn, byte[] payload, InvocationType type, int chainDepth) {AwsArnUtils.Arn arn = AwsArnUtils.parse(functionArn);LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(functionArn);LambdaFunction fn = resolveInvokeTargetForAccount(arn.accountId(), arn.region(), ref.name(), ref.qualifier());- InvokeResult result = executorService.invoke(fn, payload, type);+ InvokeResult result = executorService.invoke(fn, payload, type, chainDepth);result.setExecutedVersion(fn.getVersion());return result;}@@ -3292,6 +3305,38 @@ public class LambdaService implements ResourceProvider {return result;}+ /**+ * The event invoke configuration that applies to an invocation of {@code fn}, or empty when+ * the function has none. Unlike {@link #getEventInvokeConfig} this answers a background+ * worker rather than an API caller, so an absent configuration is a result and not a fault.+ *+ * <p>The lookup key is the unqualified function ARN plus the version the invocation actually+ * ran, which is where a function-level {@code PutFunctionEventInvokeConfig} stores its+ * settings: that call names {@code $LATEST}, and so does a resolved unpublished function.+ *+ * <p>The read runs as the function's owning account. {@code PutFunctionEventInvokeConfig}+ * stored the configuration in that account's partition of the account-aware backend, and the+ * background worker calling this carries no request context, so without re-establishing the+ * account the read would land in the default partition and a function in any other account+ * would look as though it had no configuration at all.+ */+ public Optional<FunctionEventInvokeConfig> findEventInvokeConfig(LambdaFunction fn) {+ if (fn == null || fn.getFunctionArn() == null) {+ return Optional.empty();+ }+ String qualifier = fn.getVersion() != null ? fn.getVersion() : "$LATEST";+ String functionArn = fn.getFunctionArn();+ if (functionArn.endsWith(":" + qualifier)) {+ functionArn = functionArn.substring(0, functionArn.length() - qualifier.length() - 1);+ }+ String region = AwsArnUtils.regionOrDefault(functionArn, null);+ String key = eventInvokeKey(region, functionArn, qualifier);+ String owner = fn.getAccountId() != null+ ? fn.getAccountId()+ : AwsArnUtils.accountOrDefault(functionArn, null);+ return RequestScopes.callAs(owner, () -> Optional.ofNullable(eventInvokeConfigs.get(key)));+ }+private String eventInvokeKey(String region, String functionArn, String qualifier) {return region + ":" + functionArn + ":" + (qualifier != null ? qualifier : "$LATEST");}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.javanew file mode 100644index 0000000000..280a01b291--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouterTest.java@@ -0,0 +1,339 @@+package io.github.hectorvent.floci.services.lambda;++import com.fasterxml.jackson.databind.JsonNode;+import java.time.Instant;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;+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.LambdaFunction;+import io.github.hectorvent.floci.services.sns.SnsService;+import io.github.hectorvent.floci.services.sqs.SqsService;+import jakarta.enterprise.inject.Instance;+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.util.List;+import java.util.Map;+import java.util.Optional;++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.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++@ExtendWith(MockitoExtension.class)+@MockitoSettings(strictness = Strictness.LENIENT)+class AsyncInvokeDestinationRouterTest {++ private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:bank-pawnshop";+ private static final String BUS_ARN = "arn:aws:events:us-east-1:000000000000:event-bus/quotes-bus";+ private static final String QUEUE_ARN = "arn:aws:sqs:us-east-1:000000000000:quotes-queue";+ private static final String TOPIC_ARN = "arn:aws:sns:us-east-1:000000000000:quotes-topic";+ private static final String COLLECTOR_ARN = "arn:aws:lambda:us-east-1:000000000000:function:collector";++ private static final ObjectMapper MAPPER = new ObjectMapper();++ @Mock LambdaService lambdaService;+ @Mock EventBridgeService eventBridgeService;+ @Mock SqsService sqsService;+ @Mock SnsService snsService;+ @Mock EmulatorConfig config;++ private AsyncInvokeDestinationRouter router;+ private LambdaFunction fn;++ @BeforeEach+ void setUp() {+ when(config.baseUrl()).thenReturn("http://localhost:4566");+ when(eventBridgeService.putEvents(any(), any(), any()))+ .thenReturn(new EventBridgeService.PutEventsResult(0, List.of()));+ when(lambdaService.findEventInvokeConfig(any())).thenReturn(Optional.empty());++ router = new AsyncInvokeDestinationRouter(instanceOf(lambdaService), instanceOf(eventBridgeService),+ instanceOf(sqsService), instanceOf(snsService), MAPPER, config);++ fn = new LambdaFunction();+ fn.setFunctionName("bank-pawnshop");+ fn.setFunctionArn(FUNCTION_ARN);+ fn.setAccountId("000000000000");+ }++ @Test+ void record_timestampAlwaysCarriesExactlyThreeFractionalDigits() {+ // AWS always emits milliseconds (2019-11-14T18:16:05.568Z). Instant.toString() emits+ // micro/nanosecond precision on JDK 9+ and NO fractional part at all when the nanos are+ // zero, so a consumer parsing with a fixed .SSS pattern breaks about once in a billion+ // records -- the kind of defect that never shows up in a test run that happens to be lucky.+ configure(BUS_ARN, null);++ router.route(fn, request(), success("{}"), 0);++ String timestamp = detailOf(capturedEventEntry()).get("timestamp").asText();+ assertTrue(timestamp.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"),+ "timestamp must be ISO-8601 with exactly three fractional digits, was: " + timestamp);++ // The deciding case, pinned rather than left to chance. An exact second is the only input+ // that separates the formatter from truncatedTo(MILLIS).toString(), which drops the+ // fraction there; asserting only on now() passes against both ~999 runs in 1000.+ assertEquals("2019-11-14T18:16:05.000Z",+ AsyncInvokeDestinationRouter.formatRecordTimestamp(Instant.ofEpochSecond(1573755365L)),+ "an exact second must still carry .000");+ }++ @Test+ void eventBridgeDestination_carriesTheFunctionAndDestinationAsEventResources() {+ // AWS fills the event's resources with the invoked function and the destination. Without+ // them a rule matching on `resources` never fires: matchesPattern casts the ABSENT member+ // to an ArrayNode, the NPE is swallowed and logged as a pattern-parse failure, and the+ // record is dropped at the bus while the log blames the caller's pattern. Rules matching+ // on `detail` are unaffected, which is why this stayed invisible.+ configure(BUS_ARN, null);++ router.route(fn, request(), success("{\"bankId\":\"PawnShop\"}"), 0);++ JsonNode resources = capturedEventEntry().get("Resources");+ assertTrue(resources != null && resources.isArray() && resources.size() == 2,+ "the entry must carry both ARNs as Resources, was: " + resources);+ assertEquals(FUNCTION_ARN, resources.get(0).asText());+ assertEquals(BUS_ARN, resources.get(1).asText());+ }++ @Test+ void onSuccessEventBridgeDestination_putsTheRecordOnTheBusAsTheEventDetail() {+ configure(BUS_ARN, null);++ router.route(fn, request(), success("{\"bankId\":\"PawnShop\",\"rate\":3.5}"), 0);++ JsonNode entry = capturedEventEntry();+ assertEquals("lambda", entry.get("Source").asText());+ assertEquals("Lambda Function Invocation Result - Success", entry.get("DetailType").asText());+ assertEquals(BUS_ARN, entry.get("EventBusName").asText());++ JsonNode detail = detailOf(entry);+ assertEquals("1.0", detail.get("version").asText());+ assertTrue(detail.hasNonNull("timestamp"), "record should carry a timestamp");+ assertEquals("Success", detail.path("requestContext").path("condition").asText());+ assertEquals(FUNCTION_ARN + ":$LATEST", detail.path("requestContext").path("functionArn").asText());+ assertEquals("req-1", detail.path("requestContext").path("requestId").asText());+ assertEquals(1, detail.path("requestContext").path("approximateInvokeCount").asInt());+ assertEquals("BANK-PawnShop", detail.path("requestPayload").path("bankId").asText());+ assertEquals(200, detail.path("responseContext").path("statusCode").asInt());+ assertEquals("$LATEST", detail.path("responseContext").path("executedVersion").asText());+ assertTrue(detail.path("responseContext").path("functionError").isMissingNode(),+ "a success record carries no functionError");+ // The rule of a real CDK application matches on this path.+ assertEquals("PawnShop", detail.path("responsePayload").path("bankId").asText());+ assertEquals(3.5, detail.path("responsePayload").path("rate").asDouble());+ }++ @Test+ void onSuccessSqsDestination_sendsTheRecordToTheQueue() {+ configure(QUEUE_ARN, null);++ router.route(fn, request(), success("{\"rate\":3.5}"), 0);++ ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);+ verify(sqsService).sendMessage(eq("http://localhost:4566/000000000000/quotes-queue"),+ body.capture(), eq(0), eq("us-east-1"));++ JsonNode record = read(body.getValue());+ assertEquals("Success", record.path("requestContext").path("condition").asText());+ assertEquals(3.5, record.path("responsePayload").path("rate").asDouble());+ verifyNoInteractions(eventBridgeService);+ }++ @Test+ void onSuccessSnsDestination_publishesTheRecordToTheTopic() {+ configure(TOPIC_ARN, null);++ router.route(fn, request(), success("{\"rate\":3.5}"), 0);++ ArgumentCaptor<String> message = ArgumentCaptor.forClass(String.class);+ verify(snsService).publish(eq(TOPIC_ARN), eq(null), message.capture(), anyString(), eq("us-east-1"));+ assertEquals(3.5, read(message.getValue()).path("responsePayload").path("rate").asDouble());+ }++ @Test+ void onSuccessLambdaDestination_invokesTheFunctionAsynchronously() {+ configure(COLLECTOR_ARN, null);++ router.route(fn, request(), success("{\"rate\":3.5}"), 0);++ ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);+ verify(lambdaService).invokeArnFromDestination(eq(COLLECTOR_ARN), payload.capture(), eq(1));+ assertEquals(3.5, read(new String(payload.getValue())).path("responsePayload").path("rate").asDouble());+ }++ @Test+ void lambdaDestinationPartWayAlongAChain_invokesWithTheNextHopCount() {+ configure(COLLECTOR_ARN, null);++ router.route(fn, request(), success("{\"rate\":3.5}"), 3);++ verify(lambdaService).invokeArnFromDestination(eq(COLLECTOR_ARN), any(), eq(4));+ }++ @Test+ void lambdaDestinationAtTheChainLimit_stopsRatherThanInvokingAgain() {+ configure(COLLECTOR_ARN, null);++ router.route(fn, request(), success("{\"rate\":3.5}"), 16);++ verify(lambdaService, never()).invokeArnFromDestination(anyString(), any(), anyInt());+ }++ @Test+ void nonLambdaDestinationAtTheChainLimit_isStillDelivered() {+ // The bound exists to stop a chain re-entering Lambda; a queue is the end of one.+ configure(QUEUE_ARN, null);++ router.route(fn, request(), success("{\"rate\":3.5}"), 16);++ verify(sqsService).sendMessage(eq("http://localhost:4566/000000000000/quotes-queue"),+ anyString(), eq(0), eq("us-east-1"));+ }++ @Test+ void handlerError_routesToTheFailureDestinationWithTheErrorPayload() {+ configure(BUS_ARN, BUS_ARN);+ InvokeResult failure = new InvokeResult(200, "Unhandled",+ "{\"errorMessage\":\"boom\",\"errorType\":\"Error\"}".getBytes(), null, "req-1");++ router.route(fn, request(), failure, 0);++ JsonNode entry = capturedEventEntry();+ assertEquals("Lambda Function Invocation Result - Failure", entry.get("DetailType").asText());++ JsonNode detail = detailOf(entry);+ assertEquals("RetriesExhausted", detail.path("requestContext").path("condition").asText());+ assertEquals("Unhandled", detail.path("responseContext").path("functionError").asText());+ assertEquals("boom", detail.path("responsePayload").path("errorMessage").asText());+ assertEquals("Error", detail.path("responsePayload").path("errorType").asText());+ }++ @Test+ void handlerErrorWithNoFailureDestination_deliversNothing() {+ configure(BUS_ARN, null);+ InvokeResult failure = new InvokeResult(200, "Unhandled",+ "{\"errorMessage\":\"boom\"}".getBytes(), null, "req-1");++ router.route(fn, request(), failure, 0);++ verifyNoInteractions(eventBridgeService, sqsService, snsService);+ }++ @Test+ void noEventInvokeConfig_deliversNothing() {+ router.route(fn, request(), success("{\"rate\":3.5}"), 0);++ verifyNoInteractions(eventBridgeService, sqsService, snsService);+ verify(lambdaService).findEventInvokeConfig(fn);+ }++ @Test+ void eventInvokeConfigWithoutDestinations_deliversNothing() {+ FunctionEventInvokeConfig config = new FunctionEventInvokeConfig();+ config.setMaximumRetryAttempts(0);+ when(lambdaService.findEventInvokeConfig(fn)).thenReturn(Optional.of(config));++ router.route(fn, request(), success("{\"rate\":3.5}"), 0);++ verifyNoInteractions(eventBridgeService, sqsService, snsService);+ }++ @Test+ void unsupportedDestinationArn_deliversNothing() {+ configure("arn:aws:states:us-east-1:000000000000:stateMachine:quotes", null);++ router.route(fn, request(), success("{\"rate\":3.5}"), 0);++ verifyNoInteractions(eventBridgeService, sqsService, snsService);+ }++ @Test+ void destinationThatRejectsTheRecord_doesNotReachTheCaller() {+ configure(QUEUE_ARN, null);+ when(sqsService.sendMessage(anyString(), anyString(), any(), anyString()))+ .thenThrow(new IllegalStateException("The specified queue does not exist."));++ assertDoesNotThrow(() -> router.route(fn, request(), success("{\"rate\":3.5}"), 0));+ }++ @Test+ void publishedVersion_recordsTheExecutedVersion() {+ fn.setFunctionArn(FUNCTION_ARN + ":3");+ fn.setVersion("3");+ configure(BUS_ARN, null);++ router.route(fn, request(), success("{\"rate\":3.5}"), 0);++ JsonNode detail = detailOf(capturedEventEntry());+ assertEquals(FUNCTION_ARN + ":3", detail.path("requestContext").path("functionArn").asText());+ assertEquals("3", detail.path("responseContext").path("executedVersion").asText());+ }++ private void configure(String onSuccess, String onFailure) {+ FunctionEventInvokeConfig config = new FunctionEventInvokeConfig();+ FunctionEventInvokeConfig.DestinationConfig destinations =+ new FunctionEventInvokeConfig.DestinationConfig();+ if (onSuccess != null) {+ destinations.setOnSuccess(new FunctionEventInvokeConfig.Destination(onSuccess));+ }+ if (onFailure != null) {+ destinations.setOnFailure(new FunctionEventInvokeConfig.Destination(onFailure));+ }+ config.setDestinationConfig(destinations);+ when(lambdaService.findEventInvokeConfig(fn)).thenReturn(Optional.of(config));+ }++ private JsonNode capturedEventEntry() {+ @SuppressWarnings("unchecked")+ ArgumentCaptor<List<Map<String, Object>>> entries = ArgumentCaptor.forClass(List.class);+ verify(eventBridgeService).putEvents(entries.capture(), eq("us-east-1"), eq(null));+ assertEquals(1, entries.getValue().size(), "one entry per delivery");+ return MAPPER.valueToTree(entries.getValue().get(0));+ }++ private static JsonNode detailOf(JsonNode entry) {+ return read(entry.get("Detail").asText());+ }++ private static JsonNode read(String json) {+ try {+ return MAPPER.readTree(json);+ } catch (Exception e) {+ throw new AssertionError("destination record is not JSON: " + json, e);+ }+ }++ private static byte[] request() {+ return "{\"bankId\":\"BANK-PawnShop\",\"amount\":100000}".getBytes();+ }++ private static InvokeResult success(String payload) {+ return new InvokeResult(200, null, payload.getBytes(), null, "req-1");+ }++ @SuppressWarnings("unchecked")+ private static <T> Instance<T> instanceOf(T bean) {+ Instance<T> instance = mock(Instance.class);+ when(instance.get()).thenReturn(bean);+ return instance;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.javaindex e398fcf1b3..2c5924ff85 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java@@ -48,7 +48,7 @@ class LambdaArnInvocationAccountTest {LambdaExecutorService executor = mock(LambdaExecutorService.class);InvokeResult executorResult = new InvokeResult();- when(executor.invoke(eq(function), aryEq("{}".getBytes()), eq(InvocationType.Event)))+ when(executor.invoke(eq(function), aryEq("{}".getBytes()), eq(InvocationType.Event), eq(0))).thenReturn(executorResult);LambdaService service = new LambdaService(store,@@ -75,7 +75,7 @@ class LambdaArnInvocationAccountTest {InvokeResult result = service.invokeArn(functionArn, "{}".getBytes(), InvocationType.Event);assertEquals("$LATEST", result.getExecutedVersion());- verify(executor).invoke(eq(function), aryEq("{}".getBytes()), eq(InvocationType.Event));+ verify(executor).invoke(eq(function), aryEq("{}".getBytes()), eq(InvocationType.Event), eq(0));}@Test@@ -110,7 +110,7 @@ class LambdaArnInvocationAccountTest {"alias::" + region + "::" + functionName + "::live", alias);LambdaExecutorService executor = mock(LambdaExecutorService.class);- when(executor.invoke(eq(version), aryEq("{}".getBytes()), eq(InvocationType.Event)))+ when(executor.invoke(eq(version), aryEq("{}".getBytes()), eq(InvocationType.Event), eq(0))).thenAnswer(ignored -> new InvokeResult());LambdaService service = new LambdaService(functionStore,@@ -142,7 +142,7 @@ class LambdaArnInvocationAccountTest {assertEquals("7", versionResult.getExecutedVersion());assertEquals("7", aliasResult.getExecutedVersion());verify(executor, org.mockito.Mockito.times(2))- .invoke(eq(version), aryEq("{}".getBytes()), eq(InvocationType.Event));+ .invoke(eq(version), aryEq("{}".getBytes()), eq(InvocationType.Event), eq(0));}@Test@@ -176,9 +176,9 @@ class LambdaArnInvocationAccountTest {new AccountAwareStorageBackend<>(rawAliases, null, defaultAccount));LambdaExecutorService executor = mock(LambdaExecutorService.class);- when(executor.invoke(eq(latest), aryEq("{}".getBytes()), eq(InvocationType.Event)))+ when(executor.invoke(eq(latest), aryEq("{}".getBytes()), eq(InvocationType.Event), eq(0))).thenAnswer(ignored -> new InvokeResult());- when(executor.invoke(eq(version), aryEq("{}".getBytes()), eq(InvocationType.Event)))+ when(executor.invoke(eq(version), aryEq("{}".getBytes()), eq(InvocationType.Event), eq(0))).thenAnswer(ignored -> new InvokeResult());LambdaService service = service(functionStore, aliasStore, executor, region, defaultAccount);diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaEventInvokeConfigAccountScopeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaEventInvokeConfigAccountScopeIntegrationTest.javanew file mode 100644index 0000000000..99e22413de--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaEventInvokeConfigAccountScopeIntegrationTest.java@@ -0,0 +1,68 @@+package io.github.hectorvent.floci.services.lambda;++import io.github.hectorvent.floci.core.common.RequestScopes;+import io.github.hectorvent.floci.services.lambda.model.FunctionEventInvokeConfig;+import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;+import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+import org.junit.jupiter.api.Test;++import java.util.HashMap;+import java.util.Map;+import java.util.Optional;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.TimeUnit;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * The event invoke configuration is stored in the owning account's partition of the account-aware+ * backend, and the asynchronous invoke pool that reads it carries no request context. A read that+ * does not re-establish the owner's account lands in the default partition, and a function in any+ * other account is delivered no destination at all.+ */+@QuarkusTest+class LambdaEventInvokeConfigAccountScopeIntegrationTest {++ private static final String REGION = "us-east-1";+ private static final String OTHER_ACCOUNT = "100000000012";++ @Inject+ LambdaService lambdaService;++ @Test+ void findEventInvokeConfig_forAFunctionInAnotherAccount_readsThatAccountsPartition() throws Exception {+ String functionName = "event-invoke-account-scope-fn";+ String destination = "arn:aws:sqs:" + REGION + ":" + OTHER_ACCOUNT + ":event-invoke-account-scope-queue";++ LambdaFunction fn = RequestScopes.callAs(OTHER_ACCOUNT, () -> {+ LambdaFunction created = lambdaService.createFunction(REGION, new HashMap<>(Map.of(+ "FunctionName", functionName,+ "Runtime", "nodejs20.x",+ "Role", "arn:aws:iam::" + OTHER_ACCOUNT + ":role/test-role",+ "Handler", "index.handler")));+ lambdaService.putEventInvokeConfig(REGION, functionName, "$LATEST",+ new HashMap<>(Map.of("DestinationConfig",+ Map.of("OnSuccess", Map.of("Destination", destination)))));+ return created;+ });+ assertEquals(OTHER_ACCOUNT, fn.getAccountId(), "function was not created in the target account");++ // The asynchronous invoke pool runs on a plain thread with no request context. Reading the+ // configuration from one here is what the router does after the function returns.+ ExecutorService offRequest = Executors.newSingleThreadExecutor();+ Optional<FunctionEventInvokeConfig> found;+ try {+ found = offRequest.submit(() -> lambdaService.findEventInvokeConfig(fn))+ .get(10, TimeUnit.SECONDS);+ } finally {+ offRequest.shutdownNow();+ }++ assertTrue(found.isPresent(),+ "the configuration of a function in account " + OTHER_ACCOUNT + " was not found");+ assertEquals(destination, found.get().getDestinationConfig().getOnSuccess().getDestination());+ }+}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.javaindex 6c1d90cfd8..dc36855f24 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@@ -26,6 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyInt;import static org.mockito.Mockito.doAnswer;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;@@ -178,6 +179,36 @@ class LambdaExecutorServiceTest {assertTrue(new String(result.getPayload()).contains("Interrupted"));}+ @Test+ void eventInvocation_answers202AndRoutesTheResultToDestinations() throws Exception {+ AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);+ LambdaExecutorService routingExecutor =+ new LambdaExecutorService(warmPool, new ObjectMapper(), concurrencyLimiter, router);++ RuntimeApiServer rtas = mock(RuntimeApiServer.class);+ ContainerHandle handle = new ContainerHandle("cid-async", "test-fn", rtas, ContainerState.WARM);+ when(warmPool.acquire(any())).thenReturn(handle);+ InvokeResult expected = new InvokeResult(200, null, "{\"ok\":true}".getBytes(), null, "req-async");+ doAnswer(inv -> {+ PendingInvocation pi = inv.getArgument(0);+ pi.getResultFuture().complete(expected);+ return pi.getResultFuture();+ }).when(rtas).enqueue(any(PendingInvocation.class));++ CountDownLatch routed = new CountDownLatch(1);+ doAnswer(inv -> {+ routed.countDown();+ return null;+ }).when(router).route(any(), any(), any(), anyInt());++ 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);+ }+@Testvoid exceptionDuringInvocation_destroysHandle_doesNotRelease() {RuntimeApiServer rtas = mock(RuntimeApiServer.class);