feat(lambda): honour the Invoke Qualifier and wait between asynchronous retries as AWS does (#4733)

* feat(lambda): honour the Invoke Qualifier query parameter

* feat(lambda): wait between asynchronous retries as AWS does

A failed Event invocation now waits floci.services.lambda.async-retry-delay-seconds before its first retry and twice that before its second (default 60, matching AWS), capped at the event's remaining maximum age. The concurrency permit is held only for each attempt, and an emulator reset drops retries still waiting.

* test(lambda): prove asynchronous retries end to end

* docs(lambda): document asynchronous retry timing and the Invoke Qualifier

* fix(lambda): drop retries of deleted functions and tighten async retry edges

- Drop a pending asynchronous retry when its function (or version) was deleted.
- Decide expiry once, on the injected clock, when a retry is scheduled.
- Check the reset generation at routing, so no stale outcome is delivered.
- Restore upstream behavior when an attempt throws: stop retrying and route
  the previous result, or UnknownError when there is none.
- Harden tests: in-order permit release, deterministic reset, error types
  and an unqualified-ARN Qualifier case for Invoke.

* fix(lambda): drop a deleted function's pending events on every path

Replace the store lookup with a per-function deletion counter, captured
when the event is invoked and checked wherever an event is attempted or
routed. This covers the expiry path, which bypassed the old check, and a
delete-and-recreate of the same name during the wait, which the lookup
could not see. Verified against AWS that DeleteFunction drops pending
retries without delivering a record.

* fix(lambda): clear deletion counts before bumping the reset generation

An invoke between the two statements of clear() captured the new
generation with a stale deletion count and its event was dropped.
The expiry-path deletion test now drops inside the first attempt,
so it no longer races the one-second maximum event age.

* fix(lambda): keep deletion counts across a reset

Clearing them while the old generation was still current let a
deleted function's pending event see a zero count and be routed.
A reset now only bumps the generation, in one atomic step.

* fix(lambda): drop an Event invoke that races DeleteFunction

An Event invoke that resolved the function just before a concurrent
DeleteFunction could take its deletion-count snapshot after the delete
had already moved the count. The event then never looked stale, so the
deleted function could still be started and a failure record could
still reach its destination.

DeleteFunction now moves the deletion count only after the function has
left the store, and an Event invoke checks that the function is still in
the store after it takes its snapshot and before it queues the event.
Either the check sees the function gone and the invoke answers 202
without queueing anything, or the snapshot predates the count change and
the event is dropped as stale later.

* fix(lambda): validate the Invoke Qualifier query parameter

Invoke treated an empty or blank Qualifier as if none had been given
and ran $LATEST, and it passed a qualifier longer than 128 characters on
to the lookup, which answered 404. AWS rejects both with a 400.

A supplied Qualifier must now be 1 to 128 characters of letters,
digits, $, _ and -, or Invoke fails with ValidationException. The
controller reads the parameter from the raw query, because @QueryParam
reports a present but empty value as null and the check could not see
it.

* fix(lambda): stop pending events before a delete or reset removes state

DeleteFunction moved a function's deletion count only after it had
removed the function's code and store entry. A retry whose timer fired
in that gap still passed the staleness check, tried to start a function
with no code, and could deliver a failure record to its destination. An
attempt that finished in that gap could deliver its OnFailure record.
DeleteFunction now moves the count before it deletes anything, which
stops every queued or running event, and again after the store entry is
gone, which stops an Event invoke that read the count in between.

An emulator reset wiped storage before the executor's clear() moved the
reset generation, so a retry firing during the wipe could run or deliver
against half-cleared state. The executor now also moves the generation
in beforeReset(), which runs before the wipe. clear() still moves it, to
drop events accepted between the two.

* test(lambda): fix a doc comment and name the tolerated Docker ping failure

The class comment now reads "wait as they do on AWS". The Docker ping
check names its caught exception "expected" and says why returning
false is safe: the test is then skipped rather than failed.

* fix(lambda): count version and alias invokes against the function's reservation

Routing the Invoke Qualifier to a published version meant a qualified
invoke took its permit against the version's snapshot, which carries no
reservation, so a reserved concurrency of 0 on the function no longer
throttled it and a positive one stopped counting those invokes. The
name-qualified path (fn:1, fn:alias) already had the same gap.

Reserved concurrency is function-wide in AWS, so the executor now takes
the permit against the function's $LATEST record, which holds the
reservation. That covers direct Invoke with a Qualifier, qualified names
and ARNs, aliases, event source mappings and asynchronous retries alike.
It reads the stored record rather than the limiter's region registry
because event source pollers can invoke before LambdaService has
rehydrated that registry after a restart.

* fix(lambda): drop a deleted function's pending events before draining its containers

DeleteFunction drained the warm pool before fencing pending asynchronous
events, and draining blocks while idle containers stop. A retry whose
timer fired in that window still passed the staleness check and could
cold-start a container after the drain, leaving it warm for a function
that no longer exists. The fence now goes up first.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-01 10:00:47 -04:00
1 parent 8a2b998378
commit fa4d4663a2
16 files changed
+1156 -81

No files matched your search

@@ -14,14 +14,18 @@ import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -242,6 +246,28 @@ class LambdaArnInvocationAccountTest {
assertTrue(rawAliases.get(targetAccount + "/" + aliasKey).isEmpty());
}
@Test
void deleteFunctionDropsPendingEventsBeforeDrainingAndAfterRemovingTheFunction() {
String defaultAccount = "000000000000";
String region = "ap-south-1";
String functionName = "deleted-function";
LambdaFunctionStore functionStore = new LambdaFunctionStore(
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, defaultAccount));
functionStore.save(region, function(functionName,
"arn:aws:lambda:" + region + ":" + defaultAccount + ":function:" + functionName, "$LATEST"));
LambdaExecutorService executor = mock(LambdaExecutorService.class);
WarmPool warmPool = mock(WarmPool.class);
LambdaService service = service(functionStore, null, executor, warmPool, region, defaultAccount);
List<String> steps = new ArrayList<>();
doAnswer(invocation -> steps.add(service.isLive(invocation.getArgument(0)) ? "drop stored" : "drop gone"))
.when(executor).dropPending(any());
doAnswer(invocation -> steps.add("drain")).when(warmPool).drainFunction(functionName);
service.deleteFunction(region, functionName);
assertEquals(List.of("drop stored", "drain", "drop gone"), steps);
}
private static LambdaFunction function(String functionName, String functionArn, String version) {
LambdaFunction function = new LambdaFunction();
function.setFunctionName(functionName);
@@ -256,11 +282,21 @@ class LambdaArnInvocationAccountTest {
LambdaExecutorService executor,
String region,
String defaultAccount) {
return service(functionStore, aliasStore, executor, new WarmPool(), region, defaultAccount);
}
private static LambdaService service(
LambdaFunctionStore functionStore,
LambdaAliasStore aliasStore,
LambdaExecutorService executor,
WarmPool warmPool,
String region,
String defaultAccount) {
return new LambdaService(
functionStore,
executor,
new LambdaConcurrencyLimiter(),
new WarmPool(),
warmPool,
new CodeStore(Path.of("target/test-data/lambda-code")),
new ZipExtractor(),
null,
@@ -0,0 +1,226 @@
package io.github.hectorvent.floci.services.lambda;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.sqs.model.Message;
import io.github.hectorvent.floci.services.sqs.model.Queue;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Runs a real failing function to prove the asynchronous retries wait as they do on AWS (scaled down by
* the test config to 1 s then 2 s) and that Invoke's Qualifier selects the alias's asynchronous settings.
*/
@QuarkusTest
class LambdaAsyncRetryDockerIntegrationTest {
private static final String BASE_PATH = "/2015-03-31";
private static final String CONFIG_PATH = "/2019-09-25";
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String ROLE = "arn:aws:iam::" + ACCOUNT + ":role/lambda-role";
private static final Duration RECEIVE_DEADLINE = Duration.ofSeconds(60);
private static final ObjectMapper MAPPER = new ObjectMapper();
@Inject
DockerClient dockerClient;
@Inject
SqsService sqsService;
@BeforeEach
void requireDocker() {
Assumptions.assumeTrue(isDockerAvailable(),
"Docker daemon must be available for Lambda asynchronous retry integration tests");
}
@Test
void anAliasInvocationIsRetriedWithGrowingWaitsUnderTheAliasSettings() throws Exception {
Fixture fixture = setUp();
try {
long started = System.nanoTime();
given()
.header("X-Amz-Invocation-Type", "Event")
.body("{\"probe\":\"alias\"}")
.when()
.post(BASE_PATH + "/functions/" + fixture.functionName() + "/invocations?Qualifier=live")
.then()
.statusCode(202);
JsonNode record = awaitRecord(fixture.aliasQueueUrl());
long elapsedMillis = Duration.ofNanos(System.nanoTime() - started).toMillis();
assertTrue(elapsedMillis >= 3000,
"the retries should wait 1 s and then 2 s, but the record arrived after " + elapsedMillis + " ms");
assertEquals("RetriesExhausted", record.path("requestContext").path("condition").asText());
assertEquals(3, record.path("requestContext").path("approximateInvokeCount").asInt());
String functionArn = record.path("requestContext").path("functionArn").asText();
assertTrue(functionArn.endsWith(":1"), "functionArn should name the executed version: " + functionArn);
assertEquals("1", record.path("responseContext").path("executedVersion").asText());
assertEquals("alias", record.path("requestPayload").path("probe").asText());
assertTrue(receiveOnce(fixture.latestQueueUrl()).isEmpty(),
"the unqualified OnFailure destination should receive nothing");
} finally {
deleteFunction(fixture.functionName());
}
}
@Test
void anUnqualifiedInvocationUsesTheFunctionSettings() throws Exception {
Fixture fixture = setUp();
try {
given()
.header("X-Amz-Invocation-Type", "Event")
.body("{\"probe\":\"latest\"}")
.when()
.post(BASE_PATH + "/functions/" + fixture.functionName() + "/invocations")
.then()
.statusCode(202);
JsonNode record = awaitRecord(fixture.latestQueueUrl());
assertEquals("RetriesExhausted", record.path("requestContext").path("condition").asText());
assertEquals(1, record.path("requestContext").path("approximateInvokeCount").asInt());
assertEquals("latest", record.path("requestPayload").path("probe").asText());
assertTrue(receiveOnce(fixture.aliasQueueUrl()).isEmpty(),
"the alias OnFailure destination should receive nothing");
} finally {
deleteFunction(fixture.functionName());
}
}
private Fixture setUp() throws Exception {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String functionName = "async-retry-" + suffix;
String latestQueueUrl = createQueue("async-retry-latest-" + suffix);
String aliasQueueUrl = createQueue("async-retry-alias-" + suffix);
given()
.contentType("application/json")
.body("""
{
"FunctionName": "%s",
"Runtime": "nodejs20.x",
"Role": "%s",
"Handler": "index.handler",
"Timeout": 10,
"Code": {"ZipFile": "%s"}
}
""".formatted(functionName, ROLE, failingZipBase64()))
.when()
.post(BASE_PATH + "/functions")
.then()
.statusCode(201);
given()
.contentType("application/json")
.body("{}")
.when()
.post(BASE_PATH + "/functions/" + functionName + "/versions")
.then()
.statusCode(201);
given()
.contentType("application/json")
.body("{\"Name\":\"live\",\"FunctionVersion\":\"1\"}")
.when()
.post(BASE_PATH + "/functions/" + functionName + "/aliases")
.then()
.statusCode(201);
given()
.contentType("application/json")
.body("{\"MaximumRetryAttempts\":0,\"DestinationConfig\":{\"OnFailure\":{\"Destination\":\"%s\"}}}"
.formatted(queueArn(latestQueueUrl)))
.when()
.put(CONFIG_PATH + "/functions/" + functionName + "/event-invoke-config")
.then()
.statusCode(200);
given()
.contentType("application/json")
.body("{\"MaximumRetryAttempts\":2,\"DestinationConfig\":{\"OnFailure\":{\"Destination\":\"%s\"}}}"
.formatted(queueArn(aliasQueueUrl)))
.when()
.put(CONFIG_PATH + "/functions/" + functionName + "/event-invoke-config?Qualifier=live")
.then()
.statusCode(200);
return new Fixture(functionName, latestQueueUrl, aliasQueueUrl);
}
private String createQueue(String queueName) {
Queue queue = RequestScopes.callAs(ACCOUNT, () -> sqsService.createQueue(queueName, Map.of(), REGION));
return queue.getQueueUrl();
}
private String queueArn(String queueUrl) {
return RequestScopes.callAs(ACCOUNT, () ->
sqsService.getQueueAttributes(queueUrl, List.of("QueueArn"), REGION).get("QueueArn"));
}
private List<Message> receiveOnce(String queueUrl) {
return RequestScopes.callAs(ACCOUNT, () -> sqsService.receiveMessage(queueUrl, 1, 30, 0, REGION));
}
private JsonNode awaitRecord(String queueUrl) throws Exception {
long deadline = System.nanoTime() + RECEIVE_DEADLINE.toNanos();
while (System.nanoTime() < deadline) {
List<Message> messages = receiveOnce(queueUrl);
if (!messages.isEmpty()) {
return MAPPER.readTree(messages.get(0).getBody());
}
Thread.sleep(250);
}
return fail("no OnFailure record reached " + queueUrl + " within " + RECEIVE_DEADLINE.toSeconds() + " s");
}
private static void deleteFunction(String functionName) {
given().when().delete(BASE_PATH + "/functions/" + functionName);
}
private static String failingZipBase64() throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write("exports.handler = async () => { throw new Error('boom'); };\n"
.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return Base64.getEncoder().encodeToString(bytes.toByteArray());
}
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();
return true;
} catch (Exception expected) {
// Docker is unreachable, so requireDocker() skips the test rather than failing it.
return false;
}
}
private record Fixture(String functionName, String latestQueueUrl, String aliasQueueUrl) {
}
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.lambda;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.lambda.launcher.ContainerHandle;
import io.github.hectorvent.floci.services.lambda.model.ContainerState;
import io.github.hectorvent.floci.services.lambda.model.FunctionEventInvokeConfig;
@@ -10,18 +11,24 @@ import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.lambda.model.PendingInvocation;
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.AfterEach;
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.InOrder;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
@@ -30,12 +37,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
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.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.after;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
@@ -50,6 +60,7 @@ class LambdaExecutorServiceTest {
@Mock WarmPool warmPool;
@Mock LambdaConcurrencyLimiter concurrencyLimiter;
private final List<LambdaExecutorService> retryExecutors = new ArrayList<>();
private LambdaExecutorService executor;
private LambdaFunction fn;
@@ -65,6 +76,13 @@ class LambdaExecutorServiceTest {
when(concurrencyLimiter.acquire(any())).thenReturn(() -> {});
}
@AfterEach
void shutDownRetryExecutors() {
for (LambdaExecutorService retryExecutor : retryExecutors) {
retryExecutor.shutdown();
}
}
@Test
void asyncInvocationPastTheChainBound_isDroppedWithoutRunningTheFunction() {
// AWS stops the next invocation in a chain of requests once the same originating event has
@@ -78,6 +96,26 @@ class LambdaExecutorServiceTest {
verify(warmPool, never()).acquire(any());
}
@Test
void aVersionTakesItsPermitAgainstTheFunctionsReservation() {
// A version's snapshot carries no reservation; reserved concurrency is function-wide.
fn.setReservedConcurrentExecutions(0);
LambdaFunction version = new LambdaFunction();
version.setFunctionName("test-fn");
version.setVersion("1");
version.setFunctionArn(fn.getFunctionArn() + ":1");
LambdaService lambdaService = mock(LambdaService.class);
when(lambdaService.findLatest(version)).thenReturn(Optional.of(fn));
LambdaExecutorService versionExecutor = new LambdaExecutorService(warmPool, new ObjectMapper(),
new LambdaConcurrencyLimiter(), null, lambdaService);
AwsException ex = assertThrows(AwsException.class,
() -> versionExecutor.invoke(version, "{}".getBytes(), InvocationType.RequestResponse));
assertEquals("TooManyRequestsException", ex.getErrorCode());
verify(warmPool, never()).acquire(any());
}
@Test
void asyncInvocationShortOfTheChainBound_stillRuns() {
executor.invoke(fn, "{}".getBytes(), InvocationType.Event, LambdaInvocationChain.MAX_DEPTH - 1);
@@ -282,6 +320,7 @@ class LambdaExecutorServiceTest {
config.setMaximumRetryAttempts(2);
config.setMaximumEventAgeInSeconds(21600);
when(lambdaService.findEventInvokeConfig(fn, null)).thenReturn(Optional.of(config));
when(lambdaService.isLive(fn)).thenReturn(true);
LambdaExecutorService retryExecutor =
new LambdaExecutorService(warmPool, new ObjectMapper(), concurrencyLimiter, router, lambdaService);
@@ -319,6 +358,7 @@ class LambdaExecutorServiceTest {
config.setMaximumRetryAttempts(2);
config.setMaximumEventAgeInSeconds(0);
when(lambdaService.findEventInvokeConfig(fn, null)).thenReturn(Optional.of(config));
when(lambdaService.isLive(fn)).thenReturn(true);
LambdaExecutorService retryExecutor =
new LambdaExecutorService(warmPool, new ObjectMapper(), concurrencyLimiter, router, lambdaService);
@@ -348,9 +388,10 @@ class LambdaExecutorServiceTest {
config.setMaximumRetryAttempts(2);
config.setMaximumEventAgeInSeconds(1);
when(lambdaService.findEventInvokeConfig(fn, null)).thenReturn(Optional.of(config));
when(lambdaService.isLive(fn)).thenReturn(true);
MutableClock clock = new MutableClock();
LambdaExecutorService retryExecutor =
new LambdaExecutorService(warmPool, new ObjectMapper(), concurrencyLimiter, router, lambdaService, clock);
LambdaExecutorService retryExecutor = new LambdaExecutorService(warmPool, new ObjectMapper(),
concurrencyLimiter, router, lambdaService, clock, Duration.ZERO);
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
ContainerHandle handle = new ContainerHandle("cid-age-after-failure", "test-fn", rtas, ContainerState.WARM);
@@ -381,6 +422,199 @@ class LambdaExecutorServiceTest {
"age expiration should preserve the last invocation result");
}
@Test
void eventInvocation_waitsLongerBeforeEachRetry() throws Exception {
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
LambdaExecutorService retryExecutor =
retryingExecutor(router, eventInvokeConfig(2, 21600), Duration.ofMillis(300));
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
InvokeResult failure = failedAttempt("req-wait");
List<Long> enqueuedAt = failEveryAttempt(rtas, failure);
CountDownLatch routed = countRoutes(router);
byte[] payload = "{}".getBytes();
retryExecutor.invoke(fn, payload, InvocationType.Event);
assertTrue(routed.await(10, TimeUnit.SECONDS), "destination routing never ran");
assertEquals(3, enqueuedAt.size());
long firstWaitMs = TimeUnit.NANOSECONDS.toMillis(enqueuedAt.get(1) - enqueuedAt.get(0));
long secondWaitMs = TimeUnit.NANOSECONDS.toMillis(enqueuedAt.get(2) - enqueuedAt.get(1));
assertTrue(firstWaitMs >= 300, "first retry came after " + firstWaitMs + " ms");
assertTrue(secondWaitMs >= 600, "second retry came after " + secondWaitMs + " ms");
verify(router).route(eq(fn), eq(payload), eq(failure), eq(3), eq(0), isNull());
}
@Test
void eventInvocation_releasesTheConcurrencyPermitBetweenAttempts() throws Exception {
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
LambdaExecutorService retryExecutor = retryingExecutor(router, eventInvokeConfig(2, 21600), Duration.ZERO);
LambdaConcurrencyLimiter.Permit permit = mock(LambdaConcurrencyLimiter.Permit.class);
when(concurrencyLimiter.acquire(fn)).thenReturn(permit);
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
failEveryAttempt(rtas, failedAttempt("req-permit"));
CountDownLatch routed = countRoutes(router);
retryExecutor.invoke(fn, "{}".getBytes(), InvocationType.Event);
assertTrue(routed.await(10, TimeUnit.SECONDS), "destination routing never ran");
InOrder inOrder = inOrder(concurrencyLimiter, permit);
for (int attempt = 1; attempt <= 3; attempt++) {
inOrder.verify(concurrencyLimiter).acquire(fn);
inOrder.verify(permit).close();
}
inOrder.verifyNoMoreInteractions();
}
@Test
void eventInvocation_throttledRetryPollsAgainWithoutSpendingAnAttempt() throws Exception {
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
LambdaExecutorService retryExecutor = retryingExecutor(router, eventInvokeConfig(1, 21600), Duration.ZERO);
LambdaConcurrencyLimiter.Permit permit = mock(LambdaConcurrencyLimiter.Permit.class);
when(concurrencyLimiter.acquire(fn))
.thenReturn(permit)
.thenThrow(new AwsException("TooManyRequestsException", "Rate exceeded", 429))
.thenReturn(permit);
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
List<Long> enqueuedAt = failEveryAttempt(rtas, failedAttempt("req-throttled"));
CountDownLatch routed = countRoutes(router);
byte[] payload = "{}".getBytes();
retryExecutor.invoke(fn, payload, InvocationType.Event);
assertTrue(routed.await(10, TimeUnit.SECONDS), "destination routing never ran");
assertEquals(2, enqueuedAt.size());
verify(concurrencyLimiter, times(3)).acquire(fn);
verify(router).route(eq(fn), eq(payload), any(InvokeResult.class), eq(2), eq(0), isNull());
}
@Test
void eventInvocation_expiryDuringTheRetryWaitRoutesTheLastAttempt() throws Exception {
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
LambdaExecutorService retryExecutor =
retryingExecutor(router, eventInvokeConfig(2, 1), Duration.ofSeconds(10));
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
InvokeResult failure = failedAttempt("req-expiry");
List<Long> enqueuedAt = failEveryAttempt(rtas, failure);
CountDownLatch routed = countRoutes(router);
byte[] payload = "{}".getBytes();
retryExecutor.invoke(fn, payload, InvocationType.Event);
assertTrue(routed.await(5, TimeUnit.SECONDS),
"the retry wait should end when the event expires, not after the full delay");
assertEquals(1, enqueuedAt.size());
verify(router).route(eq(fn), eq(payload), eq(failure), eq(1), eq(0), isNull());
}
@Test
void eventInvocation_resetDropsAPendingRetry() {
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
LambdaExecutorService retryExecutor =
retryingExecutor(router, eventInvokeConfig(2, 21600), Duration.ofMillis(500));
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
ContainerHandle handle = new ContainerHandle("cid-reset", "test-fn", rtas, ContainerState.WARM);
when(warmPool.acquire(any())).thenReturn(handle);
InvokeResult failure = failedAttempt("req-reset");
doAnswer(invocation -> {
retryExecutor.clear();
PendingInvocation pendingInvocation = invocation.getArgument(0);
pendingInvocation.getResultFuture().complete(failure);
return pendingInvocation.getResultFuture();
}).when(rtas).enqueue(any(PendingInvocation.class));
retryExecutor.invoke(fn, "{}".getBytes(), InvocationType.Event);
verify(router, after(1500).never()).route(any(), any(), any(), anyInt(), anyInt(), any());
verify(rtas, times(1)).enqueue(any(PendingInvocation.class));
}
@Test
void eventInvocation_resetDropsAPendingRetryBeforeStorageIsWiped() {
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
LambdaExecutorService retryExecutor =
retryingExecutor(router, eventInvokeConfig(2, 21600), Duration.ofMillis(500));
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
ContainerHandle handle = new ContainerHandle("cid-before-reset", "test-fn", rtas, ContainerState.WARM);
when(warmPool.acquire(any())).thenReturn(handle);
InvokeResult failure = failedAttempt("req-before-reset");
doAnswer(invocation -> {
retryExecutor.beforeReset();
PendingInvocation pendingInvocation = invocation.getArgument(0);
pendingInvocation.getResultFuture().complete(failure);
return pendingInvocation.getResultFuture();
}).when(rtas).enqueue(any(PendingInvocation.class));
retryExecutor.invoke(fn, "{}".getBytes(), InvocationType.Event);
verify(router, after(1500).never()).route(any(), any(), any(), anyInt(), anyInt(), any());
verify(rtas, times(1)).enqueue(any(PendingInvocation.class));
}
@Test
void eventInvocation_dropsThePendingRetryOfADeletedFunction() {
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
LambdaExecutorService retryExecutor = retryingExecutor(router, eventInvokeConfig(2, 21600), Duration.ZERO);
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
ContainerHandle handle = new ContainerHandle("cid-deleted", "test-fn", rtas, ContainerState.WARM);
when(warmPool.acquire(any())).thenReturn(handle);
InvokeResult failure = failedAttempt("req-deleted");
doAnswer(invocation -> {
retryExecutor.dropPending(fn);
PendingInvocation pendingInvocation = invocation.getArgument(0);
pendingInvocation.getResultFuture().complete(failure);
return pendingInvocation.getResultFuture();
}).when(rtas).enqueue(any(PendingInvocation.class));
retryExecutor.invoke(fn, "{}".getBytes(), InvocationType.Event);
verify(router, after(1000).never()).route(any(), any(), any(), anyInt(), anyInt(), any());
verify(rtas, times(1)).enqueue(any(PendingInvocation.class));
}
@Test
void eventInvocation_dropsTheExpiringEventOfADeletedFunction() {
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
LambdaExecutorService retryExecutor =
retryingExecutor(router, eventInvokeConfig(2, 1), Duration.ofSeconds(10));
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
ContainerHandle handle = new ContainerHandle("cid-deleted-expiry", "test-fn", rtas, ContainerState.WARM);
when(warmPool.acquire(any())).thenReturn(handle);
InvokeResult failure = failedAttempt("req-deleted-expiry");
doAnswer(invocation -> {
retryExecutor.dropPending(fn);
PendingInvocation pendingInvocation = invocation.getArgument(0);
pendingInvocation.getResultFuture().complete(failure);
return pendingInvocation.getResultFuture();
}).when(rtas).enqueue(any(PendingInvocation.class));
retryExecutor.invoke(fn, "{}".getBytes(), InvocationType.Event);
verify(router, after(2000).never()).route(any(), any(), any(), anyInt(), anyInt(), any());
verify(rtas, times(1)).enqueue(any(PendingInvocation.class));
}
@Test
void eventInvocation_ofAFunctionDeletedAfterItWasResolved_isDroppedWithoutAnAttempt() {
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
LambdaService lambdaService = eventInvokeConfig(2, 21600);
LambdaExecutorService retryExecutor = retryingExecutor(router, lambdaService, Duration.ZERO);
LambdaConcurrencyLimiter.Permit permit = mock(LambdaConcurrencyLimiter.Permit.class);
when(concurrencyLimiter.acquire(fn)).thenReturn(permit);
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
failEveryAttempt(rtas, failedAttempt("req-deleted-before-invoke"));
// DeleteFunction ran between the caller resolving fn and this invoke: the function has left
// the store and its deletion count has already moved.
when(lambdaService.isLive(fn)).thenReturn(false);
retryExecutor.dropPending(fn);
InvokeResult result = retryExecutor.invoke(fn, "{}".getBytes(), InvocationType.Event);
assertEquals(202, result.getStatusCode());
verify(warmPool, after(1000).never()).acquire(any());
verify(router, never()).route(any(), any(), any(), anyInt(), anyInt(), any());
verify(permit).close();
}
@Test
void exceptionDuringInvocation_destroysHandle_doesNotRelease() {
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
@@ -401,4 +635,49 @@ class LambdaExecutorServiceTest {
assertEquals("Unhandled", result.getFunctionError());
assertTrue(new String(result.getPayload()).contains("InvocationError"));
}
private LambdaExecutorService retryingExecutor(AsyncInvokeDestinationRouter router, LambdaService lambdaService,
Duration asyncRetryDelay) {
LambdaExecutorService retryExecutor = new LambdaExecutorService(warmPool, new ObjectMapper(),
concurrencyLimiter, router, lambdaService, Clock.systemUTC(), asyncRetryDelay);
retryExecutors.add(retryExecutor);
return retryExecutor;
}
private LambdaService eventInvokeConfig(int maximumRetryAttempts, int maximumEventAgeInSeconds) {
FunctionEventInvokeConfig config = new FunctionEventInvokeConfig();
config.setMaximumRetryAttempts(maximumRetryAttempts);
config.setMaximumEventAgeInSeconds(maximumEventAgeInSeconds);
LambdaService lambdaService = mock(LambdaService.class);
when(lambdaService.findEventInvokeConfig(fn, null)).thenReturn(Optional.of(config));
when(lambdaService.isLive(fn)).thenReturn(true);
return lambdaService;
}
private static InvokeResult failedAttempt(String requestId) {
return new InvokeResult(200, "Unhandled", "{\"errorMessage\":\"fails\"}".getBytes(), null, requestId);
}
/** Makes every attempt fail with {@code failure}; the list records when each one reached the runtime. */
private List<Long> failEveryAttempt(RuntimeApiServer rtas, InvokeResult failure) {
ContainerHandle handle = new ContainerHandle("cid-failing", "test-fn", rtas, ContainerState.WARM);
when(warmPool.acquire(any())).thenReturn(handle);
List<Long> enqueuedAt = new CopyOnWriteArrayList<>();
doAnswer(invocation -> {
enqueuedAt.add(System.nanoTime());
PendingInvocation pendingInvocation = invocation.getArgument(0);
pendingInvocation.getResultFuture().complete(failure);
return pendingInvocation.getResultFuture();
}).when(rtas).enqueue(any(PendingInvocation.class));
return enqueuedAt;
}
private static CountDownLatch countRoutes(AsyncInvokeDestinationRouter router) {
CountDownLatch routed = new CountDownLatch(1);
doAnswer(invocation -> {
routed.countDown();
return null;
}).when(router).route(any(), any(), any(), anyInt(), anyInt(), any());
return routed;
}
}
@@ -0,0 +1,194 @@
package io.github.hectorvent.floci.services.lambda;
import io.quarkus.test.junit.QuarkusTest;
import org.hamcrest.Matcher;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.equalTo;
/**
* Invoke ignored the {@code Qualifier} query parameter, so {@code ?Qualifier=} ran {@code $LATEST}
* and an alias's asynchronous invocation settings were never applied.
*/
@QuarkusTest
class LambdaInvokeQualifierIntegrationTest {
private static String zipB64(String body) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry("handler.py"));
zos.write(("def handler(e, c):\n return {'body': '" + body + "'}\n")
.getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
}
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
private static Matcher<Integer> anyOf200Or201() {
return anyOf(equalTo(200), equalTo(201));
}
private static String createFunction(String body) throws Exception {
String name = "inv-qual-" + Long.toString(System.nanoTime(), 36);
given()
.contentType("application/json")
.body("""
{"FunctionName": "%s", "Runtime": "python3.12",
"Role": "arn:aws:iam::000000000000:role/r", "Handler": "handler.handler",
"Code": {"ZipFile": "%s"}}
""".formatted(name, zipB64(body)))
.when()
.post("/2015-03-31/functions")
.then()
.statusCode(anyOf200Or201());
return name;
}
private static void publishVersion(String fn, String expectedVersion) {
given().contentType("application/json").body("{}")
.when().post("/2015-03-31/functions/" + fn + "/versions")
.then().statusCode(201).body("Version", equalTo(expectedVersion));
}
@Test
void aQualifierQueryParameterSelectsThePublishedVersion() throws Exception {
String fn = createFunction("v1");
publishVersion(fn, "1");
given()
.contentType("application/json")
.body("{\"ZipFile\": \"%s\"}".formatted(zipB64("v2")))
.when()
.put("/2015-03-31/functions/" + fn + "/code")
.then()
.statusCode(200);
given().header("X-Amz-Invocation-Type", "DryRun").body("{}")
.when().post("/2015-03-31/functions/" + fn + "/invocations?Qualifier=1")
.then().statusCode(204).header("X-Amz-Executed-Version", "1");
given().header("X-Amz-Invocation-Type", "DryRun").body("{}")
.when().post("/2015-03-31/functions/" + fn + "/invocations")
.then().statusCode(204).header("X-Amz-Executed-Version", "$LATEST");
}
@Test
void aQualifierQueryParameterResolvesAnAlias() throws Exception {
String fn = createFunction("v1");
publishVersion(fn, "1");
given()
.contentType("application/json")
.body("{\"Name\": \"live\", \"FunctionVersion\": \"1\"}")
.when()
.post("/2015-03-31/functions/" + fn + "/aliases")
.then()
.statusCode(201);
given().header("X-Amz-Invocation-Type", "DryRun").body("{}")
.when().post("/2015-03-31/functions/" + fn + "/invocations?Qualifier=live")
.then().statusCode(204).header("X-Amz-Executed-Version", "1");
}
@Test
void aQualifierQueryParameterThatDisagreesWithTheNameIsRejected() throws Exception {
String fn = createFunction("v1");
publishVersion(fn, "1");
given().header("X-Amz-Invocation-Type", "DryRun").body("{}")
.when().post("/2015-03-31/functions/" + fn + ":1/invocations?Qualifier=2")
.then().statusCode(400).body("__type", equalTo("InvalidParameterValueException"));
given().header("X-Amz-Invocation-Type", "DryRun").body("{}")
.when().post("/2015-03-31/functions/" + fn + ":1/invocations?Qualifier=1")
.then().statusCode(204).header("X-Amz-Executed-Version", "1");
}
@Test
void aQualifierQueryParameterThatDoesNotResolveIsNotFound() throws Exception {
String fn = createFunction("v1");
given().header("X-Amz-Invocation-Type", "DryRun").body("{}")
.when().post("/2015-03-31/functions/" + fn + "/invocations?Qualifier=99")
.then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void aQualifierQueryParameterAppliesToAnUnqualifiedFunctionArn() throws Exception {
String fn = createFunction("v1");
publishVersion(fn, "1");
String functionArn = given()
.when().get("/2015-03-31/functions/" + fn + "/configuration")
.then().statusCode(200).extract().path("FunctionArn");
given().header("X-Amz-Invocation-Type", "DryRun").body("{}")
.when().post("/2015-03-31/functions/{functionArn}/invocations?Qualifier=1", functionArn)
.then().statusCode(204).header("X-Amz-Executed-Version", "1");
}
@Test
void aZeroReservationThrottlesQualifiedInvokes() throws Exception {
String fn = createFunction("v1");
publishVersion(fn, "1");
given()
.contentType("application/json")
.body("{\"Name\": \"live\", \"FunctionVersion\": \"1\"}")
.when()
.post("/2015-03-31/functions/" + fn + "/aliases")
.then()
.statusCode(201);
given()
.contentType("application/json")
.body("{\"ReservedConcurrentExecutions\": 0}")
.when()
.put("/2017-10-31/functions/" + fn + "/concurrency")
.then()
.statusCode(200);
for (String target : new String[] {fn + "/invocations?Qualifier=1", fn + "/invocations?Qualifier=live",
fn + ":1/invocations", fn + ":live/invocations"}) {
given().header("X-Amz-Invocation-Type", "Event").body("{}")
.when().post("/2015-03-31/functions/" + target)
.then().statusCode(429).body("__type", equalTo("TooManyRequestsException"));
}
}
@Test
void anEmptyQualifierQueryParameterIsRejected() throws Exception {
String fn = createFunction("v1");
given().header("X-Amz-Invocation-Type", "DryRun").queryParam("Qualifier", "").body("{}")
.when().post("/2015-03-31/functions/" + fn + "/invocations")
.then().statusCode(400).body("__type", equalTo("ValidationException"));
}
@Test
void aQualifierQueryParameterLongerThan128CharactersIsRejected() throws Exception {
String fn = createFunction("v1");
given().header("X-Amz-Invocation-Type", "DryRun").queryParam("Qualifier", "a".repeat(129)).body("{}")
.when().post("/2015-03-31/functions/" + fn + "/invocations")
.then().statusCode(400).body("__type", equalTo("ValidationException"));
given().header("X-Amz-Invocation-Type", "DryRun").queryParam("Qualifier", "a".repeat(128)).body("{}")
.when().post("/2015-03-31/functions/" + fn + "/invocations")
.then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void aQualifierQueryParameterWithAnInvalidCharacterIsRejected() throws Exception {
String fn = createFunction("v1");
given().header("X-Amz-Invocation-Type", "DryRun").queryParam("Qualifier", " ").body("{}")
.when().post("/2015-03-31/functions/" + fn + "/invocations")
.then().statusCode(400).body("__type", equalTo("ValidationException"));
}
}