feat(lambda): deliver asynchronous invocation results to configured destinations (#4247)

* feat(lambda): deliver asynchronous invocation results to configured destinations

An event invoke configuration was stored and returned faithfully but never
applied, so a function with an OnSuccess or OnFailure destination computed its
result and the emulator dropped it. A CDK application that carries a function's
output on to a bus, as the Loan Broker sample does with an EventBridge
destination, saw nothing arrive.

An Event invocation now hands its result to AsyncInvokeDestinationRouter, which
delivers the invocation record AWS sends to all four destination kinds, routed
by the service in the destination ARN: an EventBridge event bus, an SQS queue,
an SNS topic, and another Lambda function. On a bus the record is the event
detail, under the source "lambda" and the detail type "Lambda Function
Invocation Result - Success" or "... - Failure", so a rule matching
detail.responsePayload.<field> sees the function's own response where AWS puts
it. A function error routes to OnFailure with a condition of RetriesExhausted, a
responseContext.functionError, and the error as the responsePayload.

The router is its own bean and reaches its collaborators through Instance
lookups because the dependency graph runs the other way: SnsService invokes its
Lambda subscribers and EventBridgeInvoker its Lambda targets, so injecting
those services into LambdaExecutorService eagerly would close a CDI cycle. The
lookup happens per delivery, which is also when a destination is first known to
exist, so a function without one costs a single map read. Delivery runs on the
invocation's pool thread under the destination account's request scope, and a
destination that rejects the record is logged: the caller was answered with 202
long before, and has nowhere to receive a late failure.

Retries and event age are still not applied, so a failure reaches its
destination once and approximateInvokeCount is always 1. The docs say so.

* fix(lambda): read an event invoke configuration as the function's own account

The configuration store is account-aware: PutFunctionEventInvokeConfig writes
into the caller's partition, keyed by that account. findEventInvokeConfig is
called from the asynchronous invoke pool, which carries no request context, so
the read fell back to the default account. A function in any other account
therefore looked as though it had no configuration and its destination was
silently skipped, with nothing logged, because having no destination is the
ordinary case this path is built to return quickly.

The read now runs under the function's owning account, taken from the function
itself and falling back to the account in its ARN, the same way the other
background workers re-establish an account before touching an account-aware
store.

* fix(lambda): bound a Lambda destination chain that leads back into itself

A function whose OnSuccess or OnFailure destination is a Lambda function, and
whose chain of those leads back to a function already in it, invoked forever.
Real AWS is not unbounded here either: recursive loop detection halts such a
chain after about sixteen invocations, so looping without end was a deviation
and not merely a hazard, and on a laptop it is a worse one than on AWS.

The number of destination hops that reached an invocation is now carried with
it, from the router through invokeArnFromDestination and into the executor, and
a Lambda destination at the sixteenth hop is dropped with a warning naming the
function the chain started from. A ThreadLocal, which is how the EventBridge
invoker bounds bus-to-bus forwarding, cannot serve here: every hop is an Event
invocation and so runs on a different pool thread.

The bound applies to Lambda destinations alone, the only kind that re-enters
this path. A queue, topic or bus at the last hop is still delivered, since it
ends the chain rather than extending it.

* docs(lambda): state the destination limits in the service docs

The alias constraint was recorded only in findEventInvokeConfig's javadoc, which
serves a maintainer reading the code and not a user reading the service docs,
and AGENTS.md asks for an intentional deviation to be documented. A destination
configured on an alias is not found, because the lookup matches the version the
invocation ran; $LATEST and an explicit version both work, and the CDK onSuccess
and onFailure properties store theirs under $LATEST.

Records the Lambda destination chain bound alongside it, so both limits of this
feature are in one place.

* refactor(lambda): make the destination routing switch an expression

AGENTS.md asks for switch expressions over switch statements without
qualification. The routing switch was a statement whose arms fell through to a
shared log line, with two of them returning early to skip it. Each arm now
yields whether the record was delivered and the log line is guarded on that,
which also removes the two returns hidden inside the arms.

The Lambda arm moves into its own method so its chain-bound check reads as a
condition on delivery rather than a second exit from the switch. No behaviour
changes: a record dropped for an unsupported ARN or for reaching the chain bound
is still logged at warn and still leaves the debug line unwritten.

* fix(lambda): carry the function and destination as event resources, and say S3 is not delivered

Two parity gaps against the capturing-records page, both found in review.

putOnEventBus set no Resources. AWS fills the event's resource field with the
invoked function and the destination, and EventBridgeService already emits the
member and matches rules against it (buildEventEnvelope reads entry Resources at
:1041 and writes `resources` at :1064; matchesPattern reads it at :894). Without
it a rule whose pattern matches on `resources` never fires -- the field arrives
empty rather than absent, so the pattern does not match and the record is dropped
at the bus rather than at the destination. Rules matching on `detail`, which is
the case the tests cover, are unaffected, which is why it stayed invisible.

The docs claimed all four destination kinds are supported. AWS has five: an S3
bucket, on failure only. The router keys on the service in the destination ARN
and has no s3 arm, so such a record reaches the default arm and is dropped with a
warning. That is the deploys-green-nothing-arrives shape this branch exists to
remove, so it is now a third bullet in the limits list rather than an omission,
and the opening sentence says four of five instead of all four.

The Resources test is measured killing a mutant: with the entry.put removed it
fails with "was: null", which is the defect verbatim.

* docs(lambda): correct the pre-fix mechanism, and scope the hop bound honestly

Two corrections from review, both to things this branch asserted.

The Resources javadoc and its test comment said the member "arrives empty
rather than absent, so the pattern simply does not match". It was absent, and
the route is worse than a mismatch: matchesPattern casts event.get("Resources")
to an ArrayNode unconditionally (EventBridgeService.java:894), so an absent
member throws NPE, the surrounding catch swallows it, and it is logged as
"Failed to parse event pattern" and reported as no-match. The record is dropped
at the bus and the log blames the caller's pattern. SesEventPublisher.java:215
already documents the same shape in almost the same words.

The limits list said a chain "stops at 16 hops" without qualification. The bound
is keyed on the destination being a Lambda ARN, so a cycle that leaves and
re-enters Lambda another way is not bounded at all: SnsService.java:1688 and
EventBridgeInvoker.java:109 each start a fresh chain at zero, so a topic that
fans back to the function, or a bus rule targeting it, loops forever. With
CallerRunsPolicy on the async executor that grows the stack once the queue
saturates rather than just spinning.

The code fix needs the depth threaded through both re-entry points, so it is
filed rather than done inline. The docs no longer claim what the code does not
do, which is the half that must not wait.

* fix(lambda): always emit millisecond precision in the record timestamp

Instant.toString() emits micro or nanosecond precision on JDK 9+, and emits no
fractional part at all when the nanos are zero. AWS always emits milliseconds
(2019-11-14T18:16:05.568Z), so a consumer parsing the record with a fixed .SSS
pattern breaks on the whole-second case. Same formatter shape as
ElasticBeanstalkQueryHandler, which already had this problem.

The test is deterministic on purpose. An assertion that only formats now() is
passed by truncatedTo(MILLIS).toString() about 999 runs in 1000, since that
differs only on an exact second -- I measured exactly that: the first version of
this test let the near-miss through, 16/16 green. formatRecordTimestamp is
package-private so the deciding input can be pinned, and the mutant now fails
with "expected 2019-11-14T18:16:05.000Z but was 2019-11-14T18:16:05Z".

LambdaEventInvokeConfigAccountScopeTest becomes an IntegrationTest. The earlier
round dismissed the conformance warning as a rule the repo ignores; review
counted it, and it does not: 778 of 922 @QuarkusTest classes follow the naming,
and 26 of 29 within services/lambda. The dismissal was wrong.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-23 18:32:06 -04:00
1 parent a574a6d01f
commit 97a2a08e1f
8 files changed
+891 -11

No files matched your search

@@ -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;
}
}
@@ -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);
@@ -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());
}
}
@@ -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);
}
@Test
void exceptionDuringInvocation_destroysHandle_doesNotRelease() {
RuntimeApiServer rtas = mock(RuntimeApiServer.class);