diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md index 3ae76f1082..f0a75991e7 100644 --- a/docs/configuration/advanced/application-yml.md +++ b/docs/configuration/advanced/application-yml.md @@ -172,6 +172,7 @@ floci: poll-interval-ms: 1000 async-retry-delay-seconds: 60 # Wait before the first retry of a failed Event invocation; the second waits twice this container-idle-timeout-seconds: 300 # Remove idle containers after this + init-timeout-seconds: 10 # Time a cold runtime has to request its first invocation; the function's Timeout wins when longer # warm-pool-max-per-function: # Idle containers kept per function (default max(4, cpus)) warm-pool-max-total: 0 # Idle containers kept across all functions; 0 = unbounded region-concurrency-limit: 1000 # Concurrent executions ceiling per region diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index db8581f745..795e30b7c3 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -253,6 +253,7 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s | `FLOCI_SERVICES_LAMBDA_POLL_INTERVAL_MS` | `1000` | How often (ms) the SQS and Kinesis event source pollers check for new messages | | `FLOCI_SERVICES_LAMBDA_ASYNC_RETRY_DELAY_SECONDS` | `60` | Wait before the first retry of a failed asynchronous invocation (seconds); the second waits twice this, `0` retries back to back | | `FLOCI_SERVICES_LAMBDA_CONTAINER_IDLE_TIMEOUT_SECONDS` | `300` | Seconds of inactivity before an idle Lambda container is removed | +| `FLOCI_SERVICES_LAMBDA_INIT_TIMEOUT_SECONDS` | `10` | Seconds a newly started runtime has, counted from its container's start, to finish its init and request its first invocation; warm containers are not affected; a function whose `Timeout` plus 2 seconds is longer waits that long instead. The function's `Timeout` starts at dispatch. See [Slow cold starts](../services/lambda.md#slow-cold-starts) | | `FLOCI_SERVICES_LAMBDA_CONTAINER_DRAIN_TIMEOUT_SECONDS` | `15` | Shared shutdown drain budget for Lambda containers; 1 through 300 seconds, invalid values fail initialization | | `FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_PER_FUNCTION` | `max(4, cpus)` | Maximum idle (warm) containers kept per function; a container released beyond this is stopped | | `FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_TOTAL` | `0` | Maximum idle (warm) containers kept across all functions. Beyond it, the least-recently-used idle container of any function is stopped to make room for the one just released. `0` leaves the total unbounded; a negative value is ignored with a warning. See [Bounding warm containers](../services/lambda.md#bounding-warm-containers) | diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 3d58055c5e..4451916972 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -572,6 +572,7 @@ These AWS Lambda operations have no handler in Floci. Calls will return `404` or | `FLOCI_SERVICES_LAMBDA_POLL_INTERVAL_MS` | `1000` | Event-source mapping poll interval (milliseconds) | | `FLOCI_SERVICES_LAMBDA_ASYNC_RETRY_DELAY_SECONDS` | `60` | Wait before the first retry of a failed asynchronous invocation (seconds); the second waits twice this, `0` retries back to back | | `FLOCI_SERVICES_LAMBDA_CONTAINER_IDLE_TIMEOUT_SECONDS` | `300` | Idle container shutdown timeout (seconds) | +| `FLOCI_SERVICES_LAMBDA_INIT_TIMEOUT_SECONDS` | `10` | Time a newly started runtime has to finish its init and request its first invocation (seconds). A function whose `Timeout` plus 2 seconds is longer waits that long instead. See [Slow cold starts](#slow-cold-starts) | | `FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_PER_FUNCTION` | `max(4, cpus)` | Maximum idle (warm) containers kept per function | | `FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_TOTAL` | `0` | Maximum idle (warm) containers kept across all functions, LRU-evicted beyond it. `0` = unbounded. See the note below | | `FLOCI_SERVICES_LAMBDA_REGION_CONCURRENCY_LIMIT` | `1000` | Maximum concurrent executions per region | @@ -650,6 +651,34 @@ These AWS Lambda operations have no handler in Floci. Calls will return `404` or trades some warm hits for the memory bound. A negative value is ignored with a warning and leaves the total unbounded, like `0`. +### Slow cold starts + +A cold start has two budgets. The Init phase runs from the moment the container has started +until its runtime requests the first invocation, which covers runtime startup and the +function's static initialization. The function's `Timeout` starts only when the invocation is +handed to the runtime, so in Floci a slow init never shortens the handler's time and +`getRemainingTimeInMillis()` reports the full `Timeout`. AWS differs here: an init that runs +past its 10-second limit is retried with the first invocation, inside the function's +`Timeout`, so there a slow init does eat into the handler's time. + +The Init phase may last `init-timeout-seconds` (default 10, the limit AWS applies), counted +from the container's start, so launching extensions and attaching logs use part of it. A +function whose `Timeout` plus 2 seconds is longer than what is left of the budget waits that +long instead. A runtime that has not asked for its invocation by then is stopped, the +invocation fails with `Function.TimedOut`, and Floci logs a warning naming the setting. Java +and other JVM runtimes on a busy CI host can need more than 10 seconds; raise the budget there: + +```bash +FLOCI_SERVICES_LAMBDA_INIT_TIMEOUT_SECONDS=120 +``` + +Image pulls and container creation happen before the Init phase and are not counted +against it. The budget applies only until the runtime first requests an invocation: a warm +or provisioned container whose runtime stops asking is given its `Timeout` plus 2 seconds. +SQS event source mappings add the budget to the visibility timeout they receive messages +with, so a message is not delivered to another consumer while its cold start is still within +the budget. + ### Runtime API host override When a Lambda container starts, it calls back into Floci's Runtime API to fetch diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 2dbc3567ba..ef0080b5ca 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -3052,6 +3052,17 @@ public interface EmulatorConfig { @WithDefault("300") int containerIdleTimeoutSeconds(); + /** + * Seconds a newly started runtime has to finish its init and request its first invocation, + * matching the 10 second Init phase AWS allows. A function whose Timeout is longer waits + * that long instead, as AWS re-runs a slow init inside the invoke. The function's Timeout + * itself starts when the invocation is dispatched. + * + * Env var: FLOCI_SERVICES_LAMBDA_INIT_TIMEOUT_SECONDS + */ + @WithDefault("10") + int initTimeoutSeconds(); + /** * One shutdown drain budget shared by provisioned and on-demand Lambda containers. * Values outside 1 through 300 seconds fail initialization. diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorService.java index 5b84b73747..99a0c418ae 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorService.java @@ -12,6 +12,7 @@ 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.lambda.model.PendingInvocation; +import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Instance; @@ -69,6 +70,7 @@ public class LambdaExecutorService implements Resettable { private final Clock clock; private final long asyncRetryDelayMs; private final boolean dockerExecutor; + private final int initTimeoutSeconds; /** Moved on by a reset so that retries still waiting from before it are dropped. */ private final AtomicLong generation = new AtomicLong(); private final Map deletions = new ConcurrentHashMap<>(); @@ -89,7 +91,8 @@ public class LambdaExecutorService implements Resettable { EmulatorConfig config) { this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, lambdaServiceInstance, null, clock, Duration.ofSeconds(config.services().lambda().asyncRetryDelaySeconds()), - !"kubernetes".equalsIgnoreCase(config.services().lambda().executor().trim())); + !"kubernetes".equalsIgnoreCase(config.services().lambda().executor().trim()), + config.services().lambda().initTimeoutSeconds()); } LambdaExecutorService(WarmPool warmPool, @@ -98,7 +101,7 @@ public class LambdaExecutorService implements Resettable { AsyncInvokeDestinationRouter destinationRouter, LambdaService directLambdaService) { this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, null, directLambdaService, - Clock.systemUTC(), Duration.ZERO, true); + Clock.systemUTC(), Duration.ZERO, true, 0); } LambdaExecutorService(WarmPool warmPool, @@ -109,7 +112,7 @@ public class LambdaExecutorService implements Resettable { Clock clock, Duration asyncRetryDelay) { this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, null, directLambdaService, clock, - asyncRetryDelay, true); + asyncRetryDelay, true, 0); } private LambdaExecutorService(WarmPool warmPool, @@ -120,7 +123,8 @@ public class LambdaExecutorService implements Resettable { LambdaService directLambdaService, Clock clock, Duration asyncRetryDelay, - boolean dockerExecutor) { + boolean dockerExecutor, + int initTimeoutSeconds) { this.warmPool = warmPool; this.objectMapper = objectMapper; this.concurrencyLimiter = concurrencyLimiter; @@ -130,6 +134,7 @@ public class LambdaExecutorService implements Resettable { this.clock = clock; this.asyncRetryDelayMs = asyncRetryDelay.toMillis(); this.dockerExecutor = dockerExecutor; + this.initTimeoutSeconds = initTimeoutSeconds; } /** Package-private constructor for testing without CDI, leaving destinations unrouted. */ @@ -137,7 +142,7 @@ public class LambdaExecutorService implements Resettable { ObjectMapper objectMapper, LambdaConcurrencyLimiter concurrencyLimiter) { this(warmPool, objectMapper, concurrencyLimiter, null, (Instance) null, null, - Clock.systemUTC(), Duration.ZERO, true); + Clock.systemUTC(), Duration.ZERO, true, 0); } LambdaExecutorService(WarmPool warmPool, @@ -145,7 +150,15 @@ public class LambdaExecutorService implements Resettable { LambdaConcurrencyLimiter concurrencyLimiter, AsyncInvokeDestinationRouter destinationRouter) { this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, - (Instance) null, null, Clock.systemUTC(), Duration.ZERO, true); + (Instance) null, null, Clock.systemUTC(), Duration.ZERO, true, 0); + } + + LambdaExecutorService(WarmPool warmPool, + ObjectMapper objectMapper, + LambdaConcurrencyLimiter concurrencyLimiter, + int initTimeoutSeconds) { + this(warmPool, objectMapper, concurrencyLimiter, null, (Instance) null, null, + Clock.systemUTC(), Duration.ZERO, true, initTimeoutSeconds); } public InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type) { @@ -360,18 +373,21 @@ public class LambdaExecutorService implements Resettable { buildErrorPayload(initFailureMessage(e, dockerExecutor), "Lambda.InitError"), null, requestId); } + long deadlineMs = System.currentTimeMillis() + (long) fn.getTimeout() * 1000; + PendingInvocation invocation = new PendingInvocation( + requestId, payload, deadlineMs, fn.getFunctionArn(), + new CompletableFuture<>()); + invocation.setClientContext(clientContext); + RuntimeApiServer runtimeApiServer = handle.getRuntimeApiServer(); + boolean initializing = !runtimeApiServer.hasRuntimePolled(); + long dispatchWaitMs = dispatchWaitMs(fn.getTimeout(), initializing, + runtimeApiServer.getContainerStartedAtMs(), System.currentTimeMillis()); try { - long deadlineMs = System.currentTimeMillis() + (long) fn.getTimeout() * 1000; - PendingInvocation invocation = new PendingInvocation( - requestId, payload, deadlineMs, fn.getFunctionArn(), - new CompletableFuture<>()); - invocation.setClientContext(clientContext); - - handle.getRuntimeApiServer().enqueue(invocation); + runtimeApiServer.enqueue(invocation); CompletableFuture.anyOf( invocation.getDispatchedFuture(), invocation.getResultFuture()) - .get(fn.getTimeout() + RUNTIME_DISPATCH_GRACE_SECONDS, TimeUnit.SECONDS); + .get(dispatchWaitMs, TimeUnit.MILLISECONDS); InvokeResult result = invocation.getResultFuture().get(); warmPool.release(handle); @@ -384,7 +400,12 @@ public class LambdaExecutorService implements Resettable { } catch (Exception e) { Throwable cause = e instanceof ExecutionException && e.getCause() != null ? e.getCause() : e; if (cause instanceof TimeoutException) { - LOG.warnv("Function {0} timed out after {1}s", fn.getFunctionName(), fn.getTimeout()); + if (initializing && !invocation.getDispatchedFuture().isDone()) { + LOG.warnv("Function {0} did not finish its init within {1}s of its container starting; raise floci.services.lambda.init-timeout-seconds if its init is slow", + fn.getFunctionName(), initTimeoutSeconds); + } else { + LOG.warnv("Function {0} timed out after {1}s", fn.getFunctionName(), fn.getTimeout()); + } warmPool.destroyHandle(handle); return new InvokeResult(200, "Unhandled", buildErrorPayload("Task timed out after " + fn.getTimeout() + " seconds", "Function.TimedOut"), @@ -397,6 +418,21 @@ public class LambdaExecutorService implements Resettable { } } + /** + * How long an invocation waits for its runtime to take it. A runtime that has never polled /next + * is still in its Init phase, which runs from its container's start for the Init budget; once the + * runtime polls, only the function's Timeout and a dispatch grace apply. The Timeout itself + * restarts when the invocation is dispatched (PendingInvocation#prepareForDispatch). + */ + long dispatchWaitMs(int timeoutSeconds, boolean initializing, long containerStartedAtMs, long nowMs) { + long dispatchWaitMs = (timeoutSeconds + RUNTIME_DISPATCH_GRACE_SECONDS) * 1000L; + if (!initializing) { + return dispatchWaitMs; + } + long sinceStartMs = containerStartedAtMs > 0 ? Math.max(0, nowMs - containerStartedAtMs) : 0; + return Math.max(initTimeoutSeconds * 1000L - sinceStartMs, dispatchWaitMs); + } + /** * Drops the pending asynchronous events of a deleted function: AWS runs no further attempt and * delivers no record for them. DeleteFunction calls it twice. The call before it drains the warm pool diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java index 3b280dc858..9430fcc469 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java @@ -55,6 +55,7 @@ public class SqsEventSourcePoller implements Resettable { private final LambdaTargetResolver targetResolver; private final EsmStore esmStore; private final long pollIntervalMs; + private final int initTimeoutSeconds; private final String baseUrl; private final ObjectMapper objectMapper; private final PipesFilterMatcher filterMatcher; @@ -85,6 +86,7 @@ public class SqsEventSourcePoller implements Resettable { this.targetResolver = targetResolver; this.esmStore = esmStore; this.pollIntervalMs = config.services().lambda().pollIntervalMs(); + this.initTimeoutSeconds = Math.max(0, config.services().lambda().initTimeoutSeconds()); this.baseUrl = config.effectiveBaseUrl(); this.objectMapper = objectMapper; this.filterMatcher = filterMatcher; @@ -183,11 +185,12 @@ public class SqsEventSourcePoller implements Resettable { // the window since the first buffered message expires. int window = esm.getMaximumBatchingWindowInSeconds() == null ? 0 : esm.getMaximumBatchingWindowInSeconds(); - // A message can be buffered for the whole window and then processed for the full - // function timeout, so visibility has to cover both plus AWS's 30s margin, not the - // larger of the two. Otherwise a long invoke can outlive the visibility and another - // consumer receives the message, causing a duplicate delivery and a stale handle. - int visibilityTimeout = fn.getTimeout() + Math.max(window, 0) + 30; + // A message can be buffered for the whole window, wait out a cold start's Init + // budget and then be processed for the full function timeout, so visibility has to + // cover all three plus AWS's 30s margin, not the largest of them. Otherwise a long + // invoke can outlive the visibility and another consumer receives the message, + // causing a duplicate delivery and a stale handle. + int visibilityTimeout = fn.getTimeout() + Math.max(window, 0) + initTimeoutSeconds + 30; PendingBatch pending = pendingBatches.get(esm.getUuid()); int alreadyBuffered = pending != null ? pending.messages.size() : 0; diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java index 38638c21b4..89e7eb0490 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java @@ -439,6 +439,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { // Now start the container with code in place lifecycleManager.startCreated(containerId, spec); + runtimeApiServer.markContainerStarted(); watchForUnexpectedExit(dockerClient, containerId, runtimeApiServer); // Extensions can log as soon as they start, which is before the container's own log stream diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java index 1b752beeff..d2cc595052 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java @@ -229,6 +229,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher { LOG.infov("Created pod {0} for function {1}", podName, fn.getFunctionName()); awaitRunning(namespace, podName, fn.getFunctionName()); + runtimeApiServer.markContainerStarted(); ContainerHandle handle = new ContainerHandle(podName, fn.getFunctionName(), runtimeApiServer, ContainerState.WARM, false); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServer.java b/src/main/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServer.java index 1fb7b7a760..62bfc3dc8b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServer.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServer.java @@ -114,6 +114,8 @@ public class RuntimeApiServer { private final Object lock = new Object(); private final CompletableFuture initialization = new CompletableFuture<>(); private boolean runtimeNextReceived; + // When the launcher started this runtime's container, in epoch millis; 0 until then. + private volatile long containerStartedAtMs; // Invocations queued before a /next poller arrived. Guarded by lock. private final ArrayDeque pendingQueue = new ArrayDeque<>(); @@ -309,6 +311,26 @@ public class RuntimeApiServer { } } + /** Records that the container running this runtime has started, which opens its Init phase. */ + public void markContainerStarted() { + containerStartedAtMs = System.currentTimeMillis(); + } + + /** Epoch millis at which the container started, or 0 when no launcher has recorded it. */ + public long getContainerStartedAtMs() { + return containerStartedAtMs; + } + + /** + * Whether the runtime has polled {@code /next} at least once, which ends its Init phase. + * Unlike {@link #isInitialized()} this does not wait for extensions. + */ + public boolean hasRuntimePolled() { + synchronized (lock) { + return runtimeNextReceived; + } + } + private void completeInitializationIfReady() { synchronized (lock) { CountDownLatch latch = extensionsReady; diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index d95b3fe489..ff838a33d7 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -440,6 +440,7 @@ floci: poll-interval-ms: 1000 async-retry-delay-seconds: 60 # FLOCI_SERVICES_LAMBDA_ASYNC_RETRY_DELAY_SECONDS - a failed Event invocation waits this before its first retry and twice this before its second (AWS: 1 min, then 2); 0 retries back to back container-idle-timeout-seconds: 300 + init-timeout-seconds: 10 # FLOCI_SERVICES_LAMBDA_INIT_TIMEOUT_SECONDS - time a cold runtime has to request its first invocation; the function's Timeout wins when longer container-drain-timeout-seconds: 15 # FLOCI_SERVICES_LAMBDA_CONTAINER_DRAIN_TIMEOUT_SECONDS - shared shutdown budget for both Lambda pools # warm-pool-max-per-function: # FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_PER_FUNCTION - idle containers kept per function (default max(4, cpus)) warm-pool-max-total: 0 # FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_TOTAL - idle containers kept across all functions, LRU evicted beyond it; 0 = unbounded diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorServiceTest.java index 7c84baabf8..52e86c127f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorServiceTest.java @@ -217,6 +217,39 @@ class LambdaExecutorServiceTest { assertNull(result.getFunctionError()); } + @Test + void dispatchWait_coldRuntimeGetsTheInitBudget() { + LambdaExecutorService withBudget = new LambdaExecutorService(warmPool, new ObjectMapper(), concurrencyLimiter, 10); + try { + assertEquals(10_000, withBudget.dispatchWaitMs(1, true, 50_000, 50_000)); + } finally { + withBudget.shutdown(); + } + } + + @Test + void dispatchWait_warmRuntimeGetsTheTimeoutPlusGraceNotTheInitBudget() { + LambdaExecutorService withBudget = new LambdaExecutorService(warmPool, new ObjectMapper(), concurrencyLimiter, 10); + try { + assertEquals(3_000, withBudget.dispatchWaitMs(1, false, 50_000, 50_000)); + } finally { + withBudget.shutdown(); + } + } + + @Test + void dispatchWait_lateStartedRuntimeGetsWhatIsLeftOfTheInitBudget() { + LambdaExecutorService withBudget = new LambdaExecutorService(warmPool, new ObjectMapper(), concurrencyLimiter, 10); + try { + // The launcher spent 4 of the 10 seconds after the start (extensions, log attach). + assertEquals(6_000, withBudget.dispatchWaitMs(1, true, 50_000, 54_000)); + // Once less is left than Timeout plus grace, that wait applies instead. + assertEquals(3_000, withBudget.dispatchWaitMs(1, true, 50_000, 59_000)); + } finally { + withBudget.shutdown(); + } + } + @Test void resultAfterConfiguredDeadline_timesOutAndDestroysHandle() { RuntimeApiServer rtas = mock(RuntimeApiServer.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java index c8aeee0e45..d94fbbd571 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java @@ -640,6 +640,37 @@ class SqsEventSourcePollerTest { assertEquals(120 + 60 + 30, visibility.getValue()); } + @Test + void visibilityTimeoutAlsoCoversTheInitBudget() { + EmulatorConfig config = mock(EmulatorConfig.class); + EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); + EmulatorConfig.LambdaServiceConfig lambdaConfig = mock(EmulatorConfig.LambdaServiceConfig.class); + when(config.services()).thenReturn(services); + when(services.lambda()).thenReturn(lambdaConfig); + when(lambdaConfig.pollIntervalMs()).thenReturn(1000L); + when(lambdaConfig.initTimeoutSeconds()).thenReturn(120); + when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566"); + SqsEventSourcePoller slowInitPoller = new SqsEventSourcePoller(mock(Vertx.class), sqsService, + executorService, new LambdaTargetResolver(functionStore, aliasStore), mock(EsmStore.class), + config, OBJECT_MAPPER, new PipesFilterMatcher(OBJECT_MAPPER)); + EventSourceMapping esm = esm(); + LambdaFunction fn = new LambdaFunction(); + fn.setFunctionName("throwfn"); + fn.setTimeout(3); + when(functionStore.getForAccount("000000000000", "us-east-1", "throwfn")) + .thenReturn(Optional.of(fn)); + when(sqsService.receiveMessage(eq(esm.getQueueUrl()), anyInt(), anyInt(), anyInt(), eq("us-east-1"))) + .thenReturn(List.of()); + + slowInitPoller.pollAndInvoke(esm); + + ArgumentCaptor visibility = ArgumentCaptor.forClass(Integer.class); + verify(sqsService, timeout(2000)).receiveMessage( + eq(esm.getQueueUrl()), anyInt(), visibility.capture(), anyInt(), eq("us-east-1")); + // up to 120s for a cold runtime to request the invocation, then 3s executing, plus the 30s margin + assertEquals(3 + 120 + 30, visibility.getValue()); + } + @Test void turningTheBatchingWindowOffDeliversAnAlreadyBufferedBatch() { LambdaFunction fn = stubThrowFn(); diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServerTest.java index 66204f3716..6c2cbd3bd5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServerTest.java @@ -86,6 +86,21 @@ class RuntimeApiServerTest { + server.waitingContextsSize()); } + @Test + @Timeout(10) + void nextEndpoint_firstPollEndsTheInitPhase() throws Exception { + assertFalse(server.hasRuntimePolled()); + + httpClient.sendAsync(HttpRequest.newBuilder() + .uri(URI.create("http://localhost:" + port + "/2018-06-01/runtime/invocation/next")) + .GET() + .build(), + HttpResponse.BodyHandlers.ofString()); + awaitWaitingContexts(1); + + assertTrue(server.hasRuntimePolled()); + } + @Test @Timeout(15) void nextEndpoint_blocksUntilInvocationArrives() throws Exception {