mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(lambda): queue throttled asynchronous invocations with backoff (#9071)
Co-authored-by: Dolev Hacohen <dolev.hacohen@forcepoint.com>
This commit is contained in:
1 parent
e8f16911d2
commit
546065dc53
9 files changed
+324
-78
No files matched your search
+11
-5
@@ -159,21 +159,27 @@ class LambdaConcurrencyTest {
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void invoke_whenReservedZero_throwsTooManyRequests() {
|
||||
void invoke_whenReservedZero_throttlesSyncAndAcceptsEvent() {
|
||||
lambda.putFunctionConcurrency(PutFunctionConcurrencyRequest.builder()
|
||||
.functionName(FUNCTION_NAME)
|
||||
.reservedConcurrentExecutions(0)
|
||||
.build());
|
||||
|
||||
// Event-type invoke still goes through the concurrency gate; reserved=0
|
||||
// should throttle every request regardless of invocation type.
|
||||
assertThatThrownBy(() -> lambda.invoke(InvokeRequest.builder()
|
||||
.functionName(FUNCTION_NAME)
|
||||
.invocationType(InvocationType.EVENT)
|
||||
.invocationType(InvocationType.REQUEST_RESPONSE)
|
||||
.payload(SdkBytes.fromUtf8String("{}"))
|
||||
.build()))
|
||||
.isInstanceOf(TooManyRequestsException.class);
|
||||
|
||||
// AWS accepts the event and sends it to the failure destination without an attempt.
|
||||
InvokeResponse response = lambda.invoke(InvokeRequest.builder()
|
||||
.functionName(FUNCTION_NAME)
|
||||
.invocationType(InvocationType.EVENT)
|
||||
.payload(SdkBytes.fromUtf8String("{}"))
|
||||
.build());
|
||||
assertThat(response.statusCode()).isEqualTo(202);
|
||||
|
||||
// Clear so teardown and other tests are not affected
|
||||
lambda.deleteFunctionConcurrency(DeleteFunctionConcurrencyRequest.builder()
|
||||
.functionName(FUNCTION_NAME).build());
|
||||
@@ -216,7 +222,7 @@ class LambdaConcurrencyTest {
|
||||
assertThatThrownBy(() -> lambda.invoke(InvokeRequest.builder()
|
||||
.functionName(FUNCTION_NAME)
|
||||
.qualifier("1")
|
||||
.invocationType(InvocationType.EVENT)
|
||||
.invocationType(InvocationType.REQUEST_RESPONSE)
|
||||
.payload(SdkBytes.fromUtf8String("{}"))
|
||||
.build()))
|
||||
.isInstanceOf(TooManyRequestsException.class);
|
||||
|
||||
+16
-6
@@ -177,11 +177,18 @@ pool. If the invocation fails, it is retried up to `MaximumRetryAttempts` (defau
|
||||
unless the event age exceeds `MaximumEventAgeInSeconds` (default: 21600 seconds, 6 hours). As in AWS, the
|
||||
first retry waits one minute and the second two. `FLOCI_SERVICES_LAMBDA_ASYNC_RETRY_DELAY_SECONDS` sets the
|
||||
first wait (the second is twice it), and `0` retries back to back for fast local test runs. A wait never runs
|
||||
past `MaximumEventAgeInSeconds`, so an event that expires while waiting is reported then. A retry that finds the
|
||||
function's concurrency in use tries again every second until the event expires, where AWS backs off for up to
|
||||
five minutes. Deleting the function drops its pending retries without delivering a record, as AWS does.
|
||||
past `MaximumEventAgeInSeconds`, so an event that expires while waiting is reported then. Deleting the function
|
||||
drops its pending retries without delivering a record, as AWS does.
|
||||
|
||||
When retries are exhausted or event age is exceeded:
|
||||
An event invoked while the function's concurrency is in use is still accepted with `202` and queued, as AWS
|
||||
does. An attempt that finds the concurrency in use waits for a permit without spending an attempt: it asks again
|
||||
after 1 second, and each further wait doubles, up to 30 seconds, until the event expires. The waits start over at
|
||||
1 second once an attempt runs. AWS backs off the same way up to 5 minutes; the lower cap notices a freed permit
|
||||
sooner locally. Under a reserved concurrency of `0`, an event is sent to the `OnFailure` destination or the
|
||||
dead-letter queue at once, without an attempt, as AWS does. Its failure record carries status `429` and a
|
||||
`TooManyRequestsException` response payload, which is Floci's own: AWS documents no content for it.
|
||||
|
||||
When retries are exhausted, event age is exceeded, or the reserved concurrency is `0`:
|
||||
|
||||
- If an `OnFailure` destination is configured, the failure record is delivered to the destination.
|
||||
- Otherwise, if a `DeadLetterConfig` (`TargetArn`) is configured on the function, the original request payload
|
||||
@@ -482,8 +489,11 @@ disabled fails with Lambda's error as the resource status reason.
|
||||
!!! note "Concurrency enforcement"
|
||||
Reserved concurrency is enforced function-wide: invocations of every
|
||||
version and alias count against the function's reservation, and
|
||||
invocations beyond the reserved value return `TooManyRequestsException`
|
||||
(HTTP 429). Functions without a reserved value share a **per-region**
|
||||
synchronous invocations beyond the reserved value return
|
||||
`TooManyRequestsException` (HTTP 429). Asynchronous invocations beyond it
|
||||
are accepted and queued until a permit frees; under a reservation of zero
|
||||
they go to the failure destination without an attempt (see above).
|
||||
Functions without a reserved value share a **per-region**
|
||||
pool. AWS Lambda's "account-level" limit is in fact a
|
||||
per-account-per-region quota, and Floci mirrors that by partitioning
|
||||
counters on the ARN's region segment. The pool size (default 1000) is
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
/** Runs a task after a delay; abstracted so tests can run scheduled tasks on demand instead of on timers. */
|
||||
public interface DelayedTaskScheduler {
|
||||
void schedule(Runnable task, long delayMillis);
|
||||
|
||||
/** Stops the scheduler's threads; one that owns none has nothing to stop. */
|
||||
default void shutdown() {
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.DelayedTaskScheduler;
|
||||
import io.floci.aws.services.dynamodb.model.KeySchemaElement;
|
||||
import io.floci.aws.services.dynamodb.model.KinesisStreamingDestination;
|
||||
import io.floci.aws.services.dynamodb.model.TableDefinition;
|
||||
@@ -58,13 +59,6 @@ public class KinesisStreamingForwarder {
|
||||
static final long INITIAL_BACKOFF_MS = 250;
|
||||
static final long MAX_BACKOFF_MS = 8000;
|
||||
|
||||
/** Schedules drain runs; abstracted so tests can drive drains deterministically. */
|
||||
interface Scheduler {
|
||||
void schedule(Runnable task, long delayMillis);
|
||||
|
||||
void shutdown();
|
||||
}
|
||||
|
||||
enum Health { HEALTHY, RETRYING, GAVE_UP }
|
||||
|
||||
record PendingRecord(String accountId, String region, String streamName, String tableName,
|
||||
@@ -102,7 +96,7 @@ public class KinesisStreamingForwarder {
|
||||
|
||||
private final KinesisService kinesisService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final Scheduler scheduler;
|
||||
private final DelayedTaskScheduler scheduler;
|
||||
private final ConcurrentHashMap<String, DestinationState> states = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
@@ -111,19 +105,19 @@ public class KinesisStreamingForwarder {
|
||||
}
|
||||
|
||||
/** Test seam: inject a deterministic Scheduler so drains run on demand rather than on real timers. */
|
||||
KinesisStreamingForwarder(KinesisService kinesisService, ObjectMapper objectMapper, Scheduler scheduler) {
|
||||
KinesisStreamingForwarder(KinesisService kinesisService, ObjectMapper objectMapper, DelayedTaskScheduler scheduler) {
|
||||
this.kinesisService = kinesisService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.scheduler = scheduler;
|
||||
}
|
||||
|
||||
private static Scheduler defaultScheduler() {
|
||||
private static DelayedTaskScheduler defaultScheduler() {
|
||||
ScheduledExecutorService exec = Executors.newScheduledThreadPool(2, r -> {
|
||||
Thread t = new Thread(r, "cdc-forward-drain");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
return new Scheduler() {
|
||||
return new DelayedTaskScheduler() {
|
||||
@Override
|
||||
public void schedule(Runnable task, long delayMillis) {
|
||||
exec.schedule(task, delayMillis, TimeUnit.MILLISECONDS);
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.DelayedTaskScheduler;
|
||||
import io.floci.aws.core.common.Resettable;
|
||||
import io.floci.aws.services.lambda.launcher.ContainerHandle;
|
||||
import io.floci.aws.services.lambda.launcher.LambdaInitException;
|
||||
@@ -27,6 +28,7 @@ import java.net.UnknownHostException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -55,14 +57,18 @@ public class LambdaExecutorService implements Resettable {
|
||||
private static final Logger LOG = Logger.getLogger(LambdaExecutorService.class);
|
||||
/** Extra time for a newly started runtime to request its first invocation. */
|
||||
private static final int RUNTIME_DISPATCH_GRACE_SECONDS = 2;
|
||||
/** How long a retry that found the function's concurrency in use waits before asking again. */
|
||||
private static final long THROTTLED_RETRY_POLL_MS = 1000;
|
||||
/** How long an attempt that found the function's concurrency in use first waits before asking again. */
|
||||
private static final long THROTTLED_RETRY_FIRST_WAIT_MS = 1000;
|
||||
/** Each further wait of an attempt that keeps finding the concurrency in use doubles, up to this. */
|
||||
static final Duration THROTTLED_RETRY_MAX_WAIT = Duration.ofSeconds(30);
|
||||
/**
|
||||
* Retries run on virtual threads rather than the pool: once the pool's queue is full its
|
||||
* caller-runs fallback would run a whole attempt on the JDK's shared delay thread, which also
|
||||
* fires the invocation timeouts that attempt may be waiting on.
|
||||
*/
|
||||
private static final Executor RETRY_THREADS = task -> Thread.ofVirtual().name("lambda-async-retry").start(task);
|
||||
private static final DelayedTaskScheduler DELAYED_RETRY_THREADS = (task, delayMs) ->
|
||||
CompletableFuture.delayedExecutor(delayMs, TimeUnit.MILLISECONDS, RETRY_THREADS).execute(task);
|
||||
|
||||
private final WarmPool warmPool;
|
||||
private final ObjectMapper objectMapper;
|
||||
@@ -73,6 +79,8 @@ public class LambdaExecutorService implements Resettable {
|
||||
private final LambdaService directLambdaService;
|
||||
private final Clock clock;
|
||||
private final long asyncRetryDelayMs;
|
||||
private final long throttledRetryMaxWaitMs;
|
||||
private final DelayedTaskScheduler retryScheduler;
|
||||
private final boolean dockerExecutor;
|
||||
private final int initTimeoutSeconds;
|
||||
/** Moved on by a reset so that retries still waiting from before it are dropped. */
|
||||
@@ -96,7 +104,7 @@ public class LambdaExecutorService implements Resettable {
|
||||
this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, lambdaServiceInstance, null, clock,
|
||||
Duration.ofSeconds(config.services().lambda().asyncRetryDelaySeconds()),
|
||||
"docker".equalsIgnoreCase(config.services().lambda().executor().trim()),
|
||||
config.services().lambda().initTimeoutSeconds());
|
||||
config.services().lambda().initTimeoutSeconds(), THROTTLED_RETRY_MAX_WAIT, DELAYED_RETRY_THREADS);
|
||||
}
|
||||
|
||||
LambdaExecutorService(WarmPool warmPool,
|
||||
@@ -105,7 +113,7 @@ public class LambdaExecutorService implements Resettable {
|
||||
AsyncInvokeDestinationRouter destinationRouter,
|
||||
LambdaService directLambdaService) {
|
||||
this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, null, directLambdaService,
|
||||
Clock.systemUTC(), Duration.ZERO, true, 0);
|
||||
Clock.systemUTC(), Duration.ZERO, true, 0, THROTTLED_RETRY_MAX_WAIT, DELAYED_RETRY_THREADS);
|
||||
}
|
||||
|
||||
LambdaExecutorService(WarmPool warmPool,
|
||||
@@ -116,7 +124,21 @@ public class LambdaExecutorService implements Resettable {
|
||||
Clock clock,
|
||||
Duration asyncRetryDelay) {
|
||||
this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, null, directLambdaService, clock,
|
||||
asyncRetryDelay, true, 0);
|
||||
asyncRetryDelay, true, 0, THROTTLED_RETRY_MAX_WAIT, DELAYED_RETRY_THREADS);
|
||||
}
|
||||
|
||||
/** Package-private constructor for testing throttled waits. */
|
||||
LambdaExecutorService(WarmPool warmPool,
|
||||
ObjectMapper objectMapper,
|
||||
LambdaConcurrencyLimiter concurrencyLimiter,
|
||||
AsyncInvokeDestinationRouter destinationRouter,
|
||||
LambdaService directLambdaService,
|
||||
Clock clock,
|
||||
Duration asyncRetryDelay,
|
||||
Duration throttledRetryMaxWait,
|
||||
DelayedTaskScheduler retryScheduler) {
|
||||
this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, null, directLambdaService, clock,
|
||||
asyncRetryDelay, true, 0, throttledRetryMaxWait, retryScheduler);
|
||||
}
|
||||
|
||||
private LambdaExecutorService(WarmPool warmPool,
|
||||
@@ -128,7 +150,9 @@ public class LambdaExecutorService implements Resettable {
|
||||
Clock clock,
|
||||
Duration asyncRetryDelay,
|
||||
boolean dockerExecutor,
|
||||
int initTimeoutSeconds) {
|
||||
int initTimeoutSeconds,
|
||||
Duration throttledRetryMaxWait,
|
||||
DelayedTaskScheduler retryScheduler) {
|
||||
this.warmPool = warmPool;
|
||||
this.objectMapper = objectMapper;
|
||||
this.concurrencyLimiter = concurrencyLimiter;
|
||||
@@ -137,6 +161,8 @@ public class LambdaExecutorService implements Resettable {
|
||||
this.directLambdaService = directLambdaService;
|
||||
this.clock = clock;
|
||||
this.asyncRetryDelayMs = asyncRetryDelay.toMillis();
|
||||
this.throttledRetryMaxWaitMs = throttledRetryMaxWait.toMillis();
|
||||
this.retryScheduler = retryScheduler;
|
||||
this.dockerExecutor = dockerExecutor;
|
||||
this.initTimeoutSeconds = initTimeoutSeconds;
|
||||
}
|
||||
@@ -146,7 +172,7 @@ public class LambdaExecutorService implements Resettable {
|
||||
ObjectMapper objectMapper,
|
||||
LambdaConcurrencyLimiter concurrencyLimiter) {
|
||||
this(warmPool, objectMapper, concurrencyLimiter, null, (Instance<LambdaService>) null, null,
|
||||
Clock.systemUTC(), Duration.ZERO, true, 0);
|
||||
Clock.systemUTC(), Duration.ZERO, true, 0, THROTTLED_RETRY_MAX_WAIT, DELAYED_RETRY_THREADS);
|
||||
}
|
||||
|
||||
LambdaExecutorService(WarmPool warmPool,
|
||||
@@ -154,7 +180,8 @@ public class LambdaExecutorService implements Resettable {
|
||||
LambdaConcurrencyLimiter concurrencyLimiter,
|
||||
AsyncInvokeDestinationRouter destinationRouter) {
|
||||
this(warmPool, objectMapper, concurrencyLimiter, destinationRouter,
|
||||
(Instance<LambdaService>) null, null, Clock.systemUTC(), Duration.ZERO, true, 0);
|
||||
(Instance<LambdaService>) null, null, Clock.systemUTC(), Duration.ZERO, true, 0,
|
||||
THROTTLED_RETRY_MAX_WAIT, DELAYED_RETRY_THREADS);
|
||||
}
|
||||
|
||||
LambdaExecutorService(WarmPool warmPool,
|
||||
@@ -162,7 +189,8 @@ public class LambdaExecutorService implements Resettable {
|
||||
LambdaConcurrencyLimiter concurrencyLimiter,
|
||||
int initTimeoutSeconds) {
|
||||
this(warmPool, objectMapper, concurrencyLimiter, null, (Instance<LambdaService>) null, null,
|
||||
Clock.systemUTC(), Duration.ZERO, true, initTimeoutSeconds);
|
||||
Clock.systemUTC(), Duration.ZERO, true, initTimeoutSeconds,
|
||||
THROTTLED_RETRY_MAX_WAIT, DELAYED_RETRY_THREADS);
|
||||
}
|
||||
|
||||
public InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type) {
|
||||
@@ -252,7 +280,6 @@ public class LambdaExecutorService implements Resettable {
|
||||
}
|
||||
|
||||
LambdaService lambdaService = resolveLambdaService();
|
||||
LambdaConcurrencyLimiter.Permit permit = acquire(lambdaService, fn);
|
||||
|
||||
if (type == InvocationType.Event) {
|
||||
FunctionEventInvokeConfig eventInvokeConfig = null;
|
||||
@@ -278,18 +305,13 @@ public class LambdaExecutorService implements Resettable {
|
||||
// again after it removes the function from the store. So either this check sees the function
|
||||
// gone, or the count moves after the event's snapshot and stale() drops the event.
|
||||
if (lambdaService != null && !lambdaService.isLive(fn)) {
|
||||
permit.close();
|
||||
return new InvokeResult(202, null, new byte[0], null, requestId);
|
||||
}
|
||||
try {
|
||||
asyncExecutor.submit(() -> attempt(event, 1, null, permit));
|
||||
} catch (RuntimeException e) {
|
||||
permit.close();
|
||||
throw e;
|
||||
}
|
||||
asyncExecutor.submit(() -> attempt(event, 1, null, THROTTLED_RETRY_FIRST_WAIT_MS));
|
||||
return new InvokeResult(202, null, new byte[0], null, requestId);
|
||||
}
|
||||
|
||||
LambdaConcurrencyLimiter.Permit permit = concurrencyLimiter.acquire(latest(lambdaService, fn));
|
||||
try {
|
||||
return executeSync(fn, payload, requestId, clientContext, invokedQualifier, listener, traceId, logTail);
|
||||
} finally {
|
||||
@@ -311,39 +333,47 @@ public class LambdaExecutorService implements Resettable {
|
||||
* Reserved concurrency is function-wide, so the permit is taken against the function's {@code $LATEST}
|
||||
* record, which holds the reservation, rather than a version's snapshot, which has none.
|
||||
*/
|
||||
private LambdaConcurrencyLimiter.Permit acquire(LambdaService lambdaService, LambdaFunction fn) {
|
||||
LambdaFunction function = lambdaService != null ? lambdaService.findLatest(fn).orElse(fn) : fn;
|
||||
return concurrencyLimiter.acquire(function);
|
||||
private static LambdaFunction latest(LambdaService lambdaService, LambdaFunction fn) {
|
||||
return lambdaService != null ? lambdaService.findLatest(fn).orElse(fn) : fn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs one attempt of an asynchronous event and either routes the outcome or schedules the next
|
||||
* attempt. Retry n waits n times the configured delay, never past the event's maximum age, and
|
||||
* the pending event of a function deleted meanwhile is dropped, whether it was waiting to retry
|
||||
* or to expire. The concurrency permit covers only the attempt; {@code held} is the one the
|
||||
* invoke itself took.
|
||||
* or to expire. The concurrency permit covers only the attempt; one that finds the concurrency in
|
||||
* use waits {@code throttledWaitMs} without spending an attempt.
|
||||
*/
|
||||
private void attempt(AsyncEvent event, int attempt, InvokeResult previous,
|
||||
LambdaConcurrencyLimiter.Permit held) {
|
||||
private void attempt(AsyncEvent event, int attempt, InvokeResult previous, long throttledWaitMs) {
|
||||
if (stale(event) || clock.millis() >= event.expiresAtMs()) {
|
||||
if (held != null) {
|
||||
held.close();
|
||||
}
|
||||
route(event, previous, attempt - 1);
|
||||
return;
|
||||
}
|
||||
LambdaFunction function;
|
||||
try {
|
||||
function = latest(resolveLambdaService(), event.fn());
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Could not look up {0} for an async attempt: {1}", event.fn().getFunctionName(), e.getMessage());
|
||||
route(event, previous != null ? previous : new InvokeResult(500, "Unhandled",
|
||||
buildErrorPayload("Error executing Lambda: " + e.getMessage(), "Lambda.UnknownError"),
|
||||
null, event.requestId()), attempt);
|
||||
return;
|
||||
}
|
||||
LambdaConcurrencyLimiter.Permit permit;
|
||||
if (held != null) {
|
||||
permit = held;
|
||||
} else {
|
||||
try {
|
||||
permit = acquire(resolveLambdaService(), event.fn());
|
||||
} catch (AwsException throttled) {
|
||||
// ponytail: AWS backs a throttled retry off exponentially, up to five minutes; one
|
||||
// fixed poll is enough locally, and the event still expires on time.
|
||||
schedule(event, THROTTLED_RETRY_POLL_MS, attempt, previous);
|
||||
try {
|
||||
permit = concurrencyLimiter.acquire(function);
|
||||
} catch (AwsException throttled) {
|
||||
if (Objects.equals(function.getReservedConcurrentExecutions(), 0)) {
|
||||
// This Floci-only placeholder covers an event a zero reservation turns away; AWS documents no payload.
|
||||
route(event, previous != null ? previous : new InvokeResult(429, "Unhandled",
|
||||
buildErrorPayload(throttled.getMessage(), throttled.getErrorCode()), null,
|
||||
event.requestId()), attempt - 1);
|
||||
return;
|
||||
}
|
||||
// ponytail: AWS backs a throttled event off up to five minutes; a lower cap notices a freed
|
||||
// permit sooner locally, and the event still expires on time.
|
||||
schedule(event, throttledWaitMs, attempt, previous, Math.min(throttledWaitMs * 2, throttledRetryMaxWaitMs));
|
||||
return;
|
||||
}
|
||||
InvokeResult result;
|
||||
try (permit) {
|
||||
@@ -361,20 +391,20 @@ public class LambdaExecutorService implements Resettable {
|
||||
route(event, result, attempt);
|
||||
return;
|
||||
}
|
||||
schedule(event, asyncRetryDelayMs * attempt, attempt + 1, result);
|
||||
schedule(event, asyncRetryDelayMs * attempt, attempt + 1, result, THROTTLED_RETRY_FIRST_WAIT_MS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides expiry up front, on the injected clock: the delay thread keeps its own time and may
|
||||
* wake a hair early.
|
||||
* wake a hair early. A wait that reaches the event's maximum age ends at it, and the event is
|
||||
* routed then instead of attempted.
|
||||
*/
|
||||
private void schedule(AsyncEvent event, long delayMs, int attempt, InvokeResult previous) {
|
||||
private void schedule(AsyncEvent event, long delayMs, int attempt, InvokeResult previous, long throttledWaitMs) {
|
||||
long remainingMs = event.expiresAtMs() - clock.millis();
|
||||
Runnable next = delayMs < remainingMs
|
||||
? () -> attempt(event, attempt, previous, null)
|
||||
? () -> attempt(event, attempt, previous, throttledWaitMs)
|
||||
: () -> route(event, previous, attempt - 1);
|
||||
CompletableFuture.delayedExecutor(Math.max(0, Math.min(delayMs, remainingMs)), TimeUnit.MILLISECONDS,
|
||||
RETRY_THREADS).execute(next);
|
||||
retryScheduler.schedule(next, Math.max(0, Math.min(delayMs, remainingMs)));
|
||||
}
|
||||
|
||||
private void route(AsyncEvent event, InvokeResult result, int attempts) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.floci.aws.services.dynamodb;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.DelayedTaskScheduler;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
@@ -48,8 +49,8 @@ import static org.mockito.Mockito.when;
|
||||
class DynamoDbTtlForwardingTest {
|
||||
|
||||
/** A Scheduler that never runs the drain, so buffered CDC records stay put for inspection. */
|
||||
private static final KinesisStreamingForwarder.Scheduler NO_DRAIN =
|
||||
new KinesisStreamingForwarder.Scheduler() {
|
||||
private static final DelayedTaskScheduler NO_DRAIN =
|
||||
new DelayedTaskScheduler() {
|
||||
@Override
|
||||
public void schedule(Runnable task, long delayMillis) {
|
||||
// intentionally never executes the drain
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.DelayedTaskScheduler;
|
||||
import io.floci.aws.services.dynamodb.model.AttributeDefinition;
|
||||
import io.floci.aws.services.dynamodb.model.KeySchemaElement;
|
||||
import io.floci.aws.services.dynamodb.model.KinesisStreamingDestination;
|
||||
@@ -41,7 +42,7 @@ import static org.mockito.Mockito.when;
|
||||
*
|
||||
* <p>{@code forward} is proven ENQUEUE-ONLY (no synchronous Kinesis I/O, never throws); the actual send,
|
||||
* retry, terminal-drop, give-up, overflow, FIFO, and lifecycle behaviour are exercised deterministically
|
||||
* by driving a manual {@link KinesisStreamingForwarder.Scheduler} step by step: no real timers, no sleeps
|
||||
* by driving a manual {@link DelayedTaskScheduler} step by step: no real timers, no sleeps
|
||||
* in the delivery assertions.
|
||||
*/
|
||||
class KinesisStreamingForwarderTest {
|
||||
@@ -65,7 +66,7 @@ class KinesisStreamingForwarderTest {
|
||||
// ──────────────────────────── helpers ────────────────────────────
|
||||
|
||||
/** A Scheduler the test drives by hand: tasks queue up and run only when the test asks. */
|
||||
static final class ManualScheduler implements KinesisStreamingForwarder.Scheduler {
|
||||
static final class ManualScheduler implements DelayedTaskScheduler {
|
||||
final ArrayDeque<Runnable> tasks = new ArrayDeque<>();
|
||||
final List<Long> delays = new ArrayList<>();
|
||||
boolean shutdown;
|
||||
@@ -100,7 +101,7 @@ class KinesisStreamingForwarderTest {
|
||||
}
|
||||
|
||||
/** A Scheduler that rejects while {@code reject} is set (executor-shutdown simulation), else queues. */
|
||||
static final class RejectingScheduler implements KinesisStreamingForwarder.Scheduler {
|
||||
static final class RejectingScheduler implements DelayedTaskScheduler {
|
||||
final ArrayDeque<Runnable> tasks = new ArrayDeque<>();
|
||||
boolean reject = true;
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.floci.aws.services.lambda;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.DelayedTaskScheduler;
|
||||
import io.floci.aws.services.lambda.launcher.ContainerHandle;
|
||||
import io.floci.aws.services.lambda.model.ContainerState;
|
||||
import io.floci.aws.services.lambda.model.FunctionEventInvokeConfig;
|
||||
@@ -10,6 +11,7 @@ import io.floci.aws.services.lambda.model.InvokeResult;
|
||||
import io.floci.aws.services.lambda.model.LambdaFunction;
|
||||
import io.floci.aws.services.lambda.model.PendingInvocation;
|
||||
import io.floci.aws.services.lambda.runtime.RuntimeApiServer;
|
||||
import io.floci.aws.testing.ManualClock;
|
||||
import io.floci.aws.testing.MutableClock;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -24,12 +26,15 @@ import org.mockito.quality.Strictness;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
@@ -57,6 +62,8 @@ import static org.mockito.Mockito.when;
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class LambdaExecutorServiceTest {
|
||||
|
||||
private static final AwsException THROTTLED = new AwsException("TooManyRequestsException", "Rate Exceeded.", 429);
|
||||
|
||||
@Mock WarmPool warmPool;
|
||||
@Mock LambdaConcurrencyLimiter concurrencyLimiter;
|
||||
|
||||
@@ -588,11 +595,12 @@ class LambdaExecutorServiceTest {
|
||||
@Test
|
||||
void eventInvocation_throttledRetryPollsAgainWithoutSpendingAnAttempt() throws Exception {
|
||||
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
|
||||
LambdaExecutorService retryExecutor = retryingExecutor(router, eventInvokeConfig(1, 21600), Duration.ZERO);
|
||||
ManualRetries retries = new ManualRetries();
|
||||
LambdaExecutorService retryExecutor = manualRetryExecutor(router, eventInvokeConfig(1, 21600), retries);
|
||||
LambdaConcurrencyLimiter.Permit permit = mock(LambdaConcurrencyLimiter.Permit.class);
|
||||
when(concurrencyLimiter.acquire(fn))
|
||||
.thenReturn(permit)
|
||||
.thenThrow(new AwsException("TooManyRequestsException", "Rate exceeded", 429))
|
||||
.thenThrow(THROTTLED)
|
||||
.thenReturn(permit);
|
||||
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
|
||||
List<Long> enqueuedAt = failEveryAttempt(rtas, failedAttempt("req-throttled"));
|
||||
@@ -600,13 +608,160 @@ class LambdaExecutorServiceTest {
|
||||
|
||||
byte[] payload = "{}".getBytes();
|
||||
retryExecutor.invoke(fn, payload, InvocationType.Event);
|
||||
retries.runUntil(routed);
|
||||
|
||||
assertTrue(routed.await(10, TimeUnit.SECONDS), "destination routing never ran");
|
||||
assertEquals(List.of(0L, 1000L), retries.delays);
|
||||
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_throttledWhenInvoked_isAcceptedAndRunsOnceAPermitFrees() throws Exception {
|
||||
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
|
||||
ManualRetries retries = new ManualRetries();
|
||||
LambdaExecutorService retryExecutor = manualRetryExecutor(router, eventInvokeConfig(0, 21600), retries);
|
||||
LambdaConcurrencyLimiter.Permit permit = mock(LambdaConcurrencyLimiter.Permit.class);
|
||||
when(concurrencyLimiter.acquire(fn))
|
||||
.thenThrow(THROTTLED)
|
||||
.thenReturn(permit);
|
||||
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
|
||||
List<Long> enqueuedAt = failEveryAttempt(rtas, failedAttempt("req-throttled-invoke"));
|
||||
CountDownLatch routed = countRoutes(router);
|
||||
|
||||
byte[] payload = "{}".getBytes();
|
||||
InvokeResult result = retryExecutor.invoke(fn, payload, InvocationType.Event);
|
||||
retries.runUntil(routed);
|
||||
|
||||
assertEquals(202, result.getStatusCode());
|
||||
assertEquals(List.of(1000L), retries.delays);
|
||||
assertEquals(1, enqueuedAt.size());
|
||||
verify(concurrencyLimiter, times(2)).acquire(fn);
|
||||
verify(permit).close();
|
||||
verify(router).route(eq(fn), eq(payload), any(InvokeResult.class), eq(1), eq(0), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventInvocation_throttledWaitsDoubleUpToTheCapAndNeverPassTheEventAge() throws Exception {
|
||||
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
|
||||
ManualRetries retries = new ManualRetries();
|
||||
LambdaExecutorService retryExecutor = manualRetryExecutor(router, eventInvokeConfig(2, 100), retries);
|
||||
when(concurrencyLimiter.acquire(fn))
|
||||
.thenThrow(THROTTLED);
|
||||
CountDownLatch routed = countRoutes(router);
|
||||
|
||||
byte[] payload = "{}".getBytes();
|
||||
retryExecutor.invoke(fn, payload, InvocationType.Event);
|
||||
retries.runUntil(routed);
|
||||
|
||||
// 1 to 16 seconds, then the 30 second cap, bring the event to 91 s of its 100 s age; the last wait ends there.
|
||||
assertEquals(List.of(1000L, 2000L, 4000L, 8000L, 16000L, 30000L, 30000L, 9000L), retries.delays);
|
||||
verify(warmPool, never()).acquire(any());
|
||||
ArgumentCaptor<InvokeResult> outcome = ArgumentCaptor.forClass(InvokeResult.class);
|
||||
verify(router).route(eq(fn), eq(payload), outcome.capture(), eq(0), eq(0), isNull());
|
||||
assertTrue(new String(outcome.getValue().getPayload()).contains("EventAgeExceeded"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventInvocation_throttledWaitStartsOverAfterAnAttemptRuns() throws Exception {
|
||||
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
|
||||
ManualRetries retries = new ManualRetries();
|
||||
LambdaExecutorService retryExecutor = manualRetryExecutor(router, eventInvokeConfig(1, 21600), retries);
|
||||
when(concurrencyLimiter.acquire(fn))
|
||||
.thenThrow(THROTTLED)
|
||||
.thenThrow(THROTTLED)
|
||||
.thenReturn(() -> { })
|
||||
.thenThrow(THROTTLED)
|
||||
.thenReturn(() -> { });
|
||||
failEveryAttempt(mock(RuntimeApiServer.class), failedAttempt("req-backoff-reset"));
|
||||
CountDownLatch routed = countRoutes(router);
|
||||
|
||||
retryExecutor.invoke(fn, "{}".getBytes(), InvocationType.Event);
|
||||
retries.runUntil(routed);
|
||||
|
||||
// Two throttled waits, the zero retry delay after the failed attempt, then a fresh one-second wait.
|
||||
assertEquals(List.of(1000L, 2000L, 0L, 1000L), retries.delays);
|
||||
verify(router).route(eq(fn), any(), any(InvokeResult.class), eq(2), eq(0), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventInvocation_whoseFunctionLookupFails_isRoutedAsAFailedAttempt() throws Exception {
|
||||
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
|
||||
LambdaService lambdaService = eventInvokeConfig(2, 21600);
|
||||
when(lambdaService.findLatest(fn)).thenThrow(new IllegalStateException("store unavailable"));
|
||||
ManualRetries retries = new ManualRetries();
|
||||
LambdaExecutorService retryExecutor = manualRetryExecutor(router, lambdaService, retries);
|
||||
CountDownLatch routed = countRoutes(router);
|
||||
|
||||
byte[] payload = "{}".getBytes();
|
||||
InvokeResult result = retryExecutor.invoke(fn, payload, InvocationType.Event);
|
||||
|
||||
assertEquals(202, result.getStatusCode());
|
||||
assertTrue(routed.await(5, TimeUnit.SECONDS), "the event was lost");
|
||||
ArgumentCaptor<InvokeResult> outcome = ArgumentCaptor.forClass(InvokeResult.class);
|
||||
verify(router).route(eq(fn), eq(payload), outcome.capture(), eq(1), eq(0), isNull());
|
||||
assertEquals(500, outcome.getValue().getStatusCode());
|
||||
assertTrue(new String(outcome.getValue().getPayload()).contains("Lambda.UnknownError"));
|
||||
assertEquals(List.of(), retries.delays);
|
||||
verify(warmPool, never()).acquire(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventInvocation_throttledWaitStopsAtAnInjectedCap() throws Exception {
|
||||
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
|
||||
ManualRetries retries = new ManualRetries();
|
||||
LambdaExecutorService retryExecutor = manualRetryExecutor(router, eventInvokeConfig(2, 30), retries,
|
||||
Duration.ofSeconds(8));
|
||||
when(concurrencyLimiter.acquire(fn))
|
||||
.thenThrow(THROTTLED);
|
||||
CountDownLatch routed = countRoutes(router);
|
||||
|
||||
retryExecutor.invoke(fn, "{}".getBytes(), InvocationType.Event);
|
||||
retries.runUntil(routed);
|
||||
|
||||
assertEquals(List.of(1000L, 2000L, 4000L, 8000L, 8000L, 7000L), retries.delays);
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventInvocation_withZeroReservedConcurrency_goesToTheFailureDestinationWithoutAnAttempt() throws Exception {
|
||||
fn.setReservedConcurrentExecutions(0);
|
||||
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
|
||||
LambdaService lambdaService = eventInvokeConfig(2, 21600);
|
||||
when(lambdaService.findLatest(fn)).thenReturn(Optional.of(fn));
|
||||
ManualRetries retries = new ManualRetries();
|
||||
LambdaExecutorService zeroExecutor = registerExecutor(new LambdaExecutorService(warmPool, new ObjectMapper(),
|
||||
new LambdaConcurrencyLimiter(), router, lambdaService, retries.clock, Duration.ZERO,
|
||||
LambdaExecutorService.THROTTLED_RETRY_MAX_WAIT, retries));
|
||||
CountDownLatch routed = countRoutes(router);
|
||||
|
||||
byte[] payload = "{}".getBytes();
|
||||
InvokeResult result = zeroExecutor.invoke(fn, payload, InvocationType.Event);
|
||||
|
||||
assertEquals(202, result.getStatusCode());
|
||||
assertTrue(routed.await(5, TimeUnit.SECONDS), "the event never reached the failure destination");
|
||||
ArgumentCaptor<InvokeResult> outcome = ArgumentCaptor.forClass(InvokeResult.class);
|
||||
verify(router).route(eq(fn), eq(payload), outcome.capture(), eq(0), eq(0), isNull());
|
||||
assertEquals(429, outcome.getValue().getStatusCode());
|
||||
assertEquals("Unhandled", outcome.getValue().getFunctionError());
|
||||
assertTrue(new String(outcome.getValue().getPayload()).contains("TooManyRequestsException"));
|
||||
assertEquals(List.of(), retries.delays);
|
||||
verify(warmPool, never()).acquire(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void syncInvocation_withZeroReservedConcurrency_isThrottled() {
|
||||
fn.setReservedConcurrentExecutions(0);
|
||||
LambdaExecutorService zeroExecutor = registerExecutor(new LambdaExecutorService(warmPool, new ObjectMapper(),
|
||||
new LambdaConcurrencyLimiter()));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> zeroExecutor.invoke(fn, "{}".getBytes(), InvocationType.RequestResponse));
|
||||
|
||||
assertEquals("TooManyRequestsException", ex.getErrorCode());
|
||||
assertEquals(429, ex.getHttpStatus());
|
||||
verify(warmPool, never()).acquire(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventInvocation_expiryDuringTheRetryWaitRoutesTheLastAttempt() throws Exception {
|
||||
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
|
||||
@@ -718,8 +873,6 @@ class LambdaExecutorServiceTest {
|
||||
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
|
||||
@@ -730,9 +883,9 @@ class LambdaExecutorServiceTest {
|
||||
InvokeResult result = retryExecutor.invoke(fn, "{}".getBytes(), InvocationType.Event);
|
||||
|
||||
assertEquals(202, result.getStatusCode());
|
||||
verify(warmPool, after(1000).never()).acquire(any());
|
||||
verify(warmPool, never()).acquire(any());
|
||||
verify(router, never()).route(any(), any(), any(), anyInt(), anyInt(), any());
|
||||
verify(permit).close();
|
||||
verify(concurrencyLimiter, never()).acquire(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -763,6 +916,17 @@ class LambdaExecutorServiceTest {
|
||||
return retryExecutor;
|
||||
}
|
||||
|
||||
private LambdaExecutorService manualRetryExecutor(AsyncInvokeDestinationRouter router, LambdaService lambdaService,
|
||||
ManualRetries retries) {
|
||||
return manualRetryExecutor(router, lambdaService, retries, LambdaExecutorService.THROTTLED_RETRY_MAX_WAIT);
|
||||
}
|
||||
|
||||
private LambdaExecutorService manualRetryExecutor(AsyncInvokeDestinationRouter router, LambdaService lambdaService,
|
||||
ManualRetries retries, Duration throttledRetryMaxWait) {
|
||||
return registerExecutor(new LambdaExecutorService(warmPool, new ObjectMapper(), concurrencyLimiter, router,
|
||||
lambdaService, retries.clock, Duration.ZERO, throttledRetryMaxWait, retries));
|
||||
}
|
||||
|
||||
private LambdaService eventInvokeConfig(int maximumRetryAttempts, int maximumEventAgeInSeconds) {
|
||||
FunctionEventInvokeConfig config = new FunctionEventInvokeConfig();
|
||||
config.setMaximumRetryAttempts(maximumRetryAttempts);
|
||||
@@ -791,6 +955,33 @@ class LambdaExecutorServiceTest {
|
||||
return enqueuedAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queues each retry the executor schedules instead of starting a timer, recording its delay; running a
|
||||
* queued retry first moves the clock on by that delay, so a whole sequence of waits plays out at once.
|
||||
*/
|
||||
private static final class ManualRetries implements DelayedTaskScheduler {
|
||||
private final ManualClock clock = new ManualClock(Instant.parse("2026-01-01T00:00:00Z"));
|
||||
private final List<Long> delays = new CopyOnWriteArrayList<>();
|
||||
private final BlockingQueue<Runnable> due = new LinkedBlockingQueue<>();
|
||||
|
||||
@Override
|
||||
public void schedule(Runnable task, long delayMs) {
|
||||
delays.add(delayMs);
|
||||
due.add(() -> {
|
||||
clock.advance(Duration.ofMillis(delayMs));
|
||||
task.run();
|
||||
});
|
||||
}
|
||||
|
||||
void runUntil(CountDownLatch routed) throws InterruptedException {
|
||||
while (routed.getCount() > 0) {
|
||||
Runnable next = due.poll(5, TimeUnit.SECONDS);
|
||||
assertNotNull(next, "the event was neither routed nor scheduled again");
|
||||
next.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static CountDownLatch countRoutes(AsyncInvokeDestinationRouter router) {
|
||||
CountDownLatch routed = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
|
||||
+5
-2
@@ -137,7 +137,7 @@ class LambdaInvokeQualifierIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void aZeroReservationThrottlesQualifiedInvokes() throws Exception {
|
||||
void aZeroReservationThrottlesQualifiedSyncInvokesAndAcceptsQualifiedEvents() throws Exception {
|
||||
String fn = createFunction("v1");
|
||||
publishVersion(fn, "1");
|
||||
given()
|
||||
@@ -157,9 +157,12 @@ class LambdaInvokeQualifierIntegrationTest {
|
||||
|
||||
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("{}")
|
||||
given().header("X-Amz-Invocation-Type", "RequestResponse").body("{}")
|
||||
.when().post("/2015-03-31/functions/" + target)
|
||||
.then().statusCode(429).body("__type", equalTo("TooManyRequestsException"));
|
||||
given().header("X-Amz-Invocation-Type", "Event").body("{}")
|
||||
.when().post("/2015-03-31/functions/" + target)
|
||||
.then().statusCode(202);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user