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,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";
}
}
@@ -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.
*/
@ApplicationScoped
public 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 {
@Inject
public 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();
@@ -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");
}