Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(lambda): initialize provisioned concurrency environments (#6320)

Andre Kurait238d16e54169
diff --git a/docs/services/lambda.md b/docs/services/lambda.md
index 6715093f42..ace1d2726f 100644
--- a/docs/services/lambda.md
+++ b/docs/services/lambda.md
@@ -5,36 +5,6 @@
Floci Lambda runs your function code locally inside real Docker containers - close enough as AWS Lambda does (using Firecracker micro VM).
-## Provisioned concurrency configuration
-
-`PutProvisionedConcurrencyConfig`, `GetProvisionedConcurrencyConfig`, and
-`DeleteProvisionedConcurrencyConfig` use the AWS REST JSON route
-`/2019-09-30/functions/{FunctionName}/provisioned-concurrency?Qualifier=...`.
-They accept published versions and aliases pointing to published versions.
-Function names, partial ARNs, and full ARNs resolve in the named account and request region.
-IAM checks use the qualified function resource and the operation's own action.
-
-This stage implements the control plane only. Put returns HTTP 202 and stores the desired
-count. Get reports `IN_PROGRESS` with zero allocated and available environments. No runtime
-is initialized, no handler is invoked, and ordinary invocation routing is unchanged. Runtime
-initialization and routing are separate follow-up work; `READY` is not simulated.
-
-Requested counts share the existing `warm-pool-max-per-function` and `warm-pool-max-total`
-local limits, and cannot exceed the function's reserved concurrency. These local limits are
-not AWS account-quota emulation. A version and an alias targeting it cannot both have a
-configuration. Weighted aliases, hot-reload functions, and durable functions are not eligible
-for Put. Put requires the non-ephemeral Docker executor. Get and Delete still address an
-existing configuration if an alias later becomes
-weighted. An alias with a configuration cannot move to `$LATEST` or to a version already
-configured directly or through another alias. Description-only changes and unconfigured aliases
-remain allowed.
-
-Deleting a version, alias, or function removes its corresponding configurations. Delete is
-idempotent for an existing target without a configuration; an absent target returns
-`ResourceNotFoundException`. Desired configuration uses the Lambda storage mode through
-`StorageFactory` and is restored after restart. Reset removes it. Storage failures propagate
-before the in-memory configuration is replaced or removed, so callers can retry.
-
## Supported Operations
| Operation | Description |
@@ -79,9 +49,9 @@ before the in-memory configuration is replaced or removed, so callers can retry.
| `PutFunctionConcurrency` | Set reserved concurrent executions |
| `GetFunctionConcurrency` | Get reserved concurrent executions |
| `DeleteFunctionConcurrency` | Clear reserved concurrent executions |
-| `PutProvisionedConcurrencyConfig` | Store requested capacity for a version or alias |
-| `GetProvisionedConcurrencyConfig` | Read requested capacity and configuration status |
-| `DeleteProvisionedConcurrencyConfig` | Remove requested capacity |
+| `PutProvisionedConcurrencyConfig` | Initialize Docker environments for a published version or simple alias |
+| `GetProvisionedConcurrencyConfig` | Read the allocation's actual initialization status and capacity |
+| `DeleteProvisionedConcurrencyConfig` | Remove an allocation and stop its environments |
| `GetAccountSettings` | Account limits plus usage derived from the caller's stored functions |
| `PutFunctionEventInvokeConfig` | Set the asynchronous invocation settings of a function, version or alias (retries, event age, destinations) |
| `UpdateFunctionEventInvokeConfig` | Change some of those settings, leaving the rest as they are |
@@ -405,8 +375,7 @@ disabled fails with Lambda's error as the resource status reason.
applies independently to each region. `PutFunctionConcurrency` validates
that the requested value leaves at least
`floci.services.lambda.unreserved-concurrency-min` (default 100) available
- for unreserved functions in that region. Provisioned-concurrency requests
- must fit within any reserved concurrency configured for the function.
+ for unreserved functions in that region.
Reducing or clearing a function's reserved value does not kill
invocations that are already in flight. This matches AWS, which
@@ -483,9 +452,62 @@ A layer ARN outside the caller's partition is refused whatever that setting says
isolated, so no resource policy can ever make such a layer readable, and `GetLayerVersionByArn`
rejects one outright with `InvalidParameterValueException: Invalid layer version ...`.
-## Container shutdown
-
-Shutdown drains on-demand containers concurrently within one
+## Provisioned concurrency
+
+Put, Get and Delete use `/2019-09-30/functions/{FunctionName}/provisioned-concurrency`
+with a required `Qualifier` query parameter. Put accepts a positive integer
+`ProvisionedConcurrentExecutions` and returns HTTP 202 with `IN_PROGRESS`. An existing
+function without a configuration returns `ProvisionedConcurrencyConfigNotFoundException`
+from Get.
+
+An alias and its resolved published version cannot both have configurations. Different
+aliases of the same provisioned version also conflict; other versions remain independent.
+`LastModified` uses Lambda's UTC `+0000` form.
+
+Each environment runs the real function initialization. `READY` requires the runtime and
+every discovered extension to send their first Runtime API `Next` request. Provisioning
+does not enqueue a handler event. Initialization failures become `FAILED`; the initialization
+deadline is the greater of 130 seconds and the configured function timeout. A later ordinary
+Invoke for that exact alias or version uses an available initialized environment, with
+on-demand spillover when all its environments are busy. Other aliases, versions, accounts
+and regions do not borrow that allocation.
+
+Layer initialization uses the stored function's account and partition, including background
+workers without a request context. An unresolved configured layer or missing layer directory
+fails provisioned initialization; it is never silently omitted from a `READY` environment.
+Cross-account layer sharing remains unsupported.
+
+With IAM enforcement enabled, these operations authorize the function owner and qualifier
+against the caller's identity policy and the owner's function policy. A cross-account grant
+for Get does not authorize Put, Delete, or another qualifier.
+
+Provisioned environments are separate from ordinary idle eviction. Desired configurations
+are persisted; restarting Floci initializes new processes before reporting `READY`.
+Deleting the configuration, alias or function removes the owned environments. If an
+alias changes its version, this stage marks its old allocation `FAILED` and retires its
+environments. Invocations use on-demand capacity until a new Put initializes the new
+version. Automatic alias retargeting is a separate follow-up. The requested quota is
+retained until configuration replacement or deletion. An invalid replacement Put preserves
+the existing healthy allocation. An alias with a configuration cannot move to `$LATEST`
+or to a version targeted by another configuration; remove the conflicting configuration
+first. Get and Delete remain available if the alias gains
+unsupported weighted routing.
+
+This implementation supports the non-ephemeral Docker executor with immutable published
+versions and simple aliases. It refuses `$LATEST`, weighted aliases, hot reload, durable
+functions and other executors. Allocations share the configured `warm-pool-max-per-function`
+ceiling across a function's qualifiers, and the optional `warm-pool-max-total` ceiling across
+provisioned allocations. A function's reserved concurrency is also a ceiling. These local
+resource bounds do not implement AWS's complete regional provisioned-concurrency quota
+accounting, automatic scaling, or weighted-alias allocation. Provisioned runtimes receive
+their numeric `AWS_LAMBDA_FUNCTION_VERSION` and
+`AWS_LAMBDA_INITIALIZATION_TYPE=provisioned-concurrency`.
+
+Configuration replacement and deletion remain committed if environment removal fails.
+Failed removals retain ownership and are retried while Floci is running; they continue
+to count against local container limits until cleanup succeeds.
+
+Shutdown drains provisioned and on-demand containers concurrently within one
`floci.services.lambda.container-drain-timeout-seconds` budget. The default is 15 seconds;
set `FLOCI_SERVICES_LAMBDA_CONTAINER_DRAIN_TIMEOUT_SECONDS` when a larger fleet needs more
time for Docker to finish removing stopped containers. Supported values are 1 through 300;
@@ -495,6 +517,7 @@ owned for a later retirement or reset retry; a completed removal is not repeated
A launch that outlasts the deadline is reported as incomplete cleanup. Its invocation is
refused, and any returned container remains owned for a later cleanup retry; the deadline
does not guarantee cancellation of an unresponsive container launcher.
+
If an invocation finishes after the shutdown deadline, releasing its still-owned
container starts a separate bounded cleanup attempt. This does not extend the
initial shutdown wait.
@@ -508,7 +531,7 @@ For a longer drain, explicitly stop with the larger timeout and then start Floci
These AWS Lambda operations have no handler in Floci. Calls will return `404` or an error:
- Layer permissions (`AddLayerVersionPermission`, `RemoveLayerVersionPermission`, `GetLayerVersionPolicy`)
-- `ListProvisionedConcurrencyConfigs`
+- Listing provisioned concurrency (`ListProvisionedConcurrencyConfigs`)
- `InvokeWithResponseStream`
- Code signing enforcement. A configuration is created, read, updated, deleted and listed, and
nothing verifies a signature against it, so it never gates a deployment. Attaching one to a
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 0a70fd0a06..c04df49898 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -3004,7 +3004,7 @@ public interface EmulatorConfig {
int containerIdleTimeoutSeconds();
/**
- * One shutdown drain budget shared by on-demand Lambda containers.
+ * One shutdown drain budget shared by provisioned and on-demand Lambda containers.
* Values outside 1 through 300 seconds fail initialization.
*
* Env var: FLOCI_SERVICES_LAMBDA_CONTAINER_DRAIN_TIMEOUT_SECONDS
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 84a8eae4e7..5b84b73747 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
@@ -233,7 +233,7 @@ public class LambdaExecutorService implements Resettable {
}
try {
- return executeSync(fn, payload, requestId, clientContext);
+ return executeSync(fn, payload, requestId, clientContext, invokedQualifier);
} finally {
permit.close();
}
@@ -289,7 +289,7 @@ public class LambdaExecutorService implements Resettable {
}
InvokeResult result;
try (permit) {
- result = executeSync(event.fn(), event.payload(), event.requestId(), null);
+ result = executeSync(event.fn(), event.payload(), event.requestId(), null, event.invokedQualifier());
} catch (RuntimeException e) {
LOG.warnv("Error in async Lambda execution for {0}: {1}", event.fn().getFunctionName(), e.getMessage());
// Stops retrying, as upstream did: routes the previous attempt's result, or UnknownError when
@@ -347,10 +347,13 @@ public class LambdaExecutorService implements Resettable {
}
private InvokeResult executeSync(LambdaFunction fn, byte[] payload, String requestId,
- String clientContext) {
+ String clientContext, String invokedQualifier) {
ContainerHandle handle;
try {
- handle = warmPool.acquire(fn);
+ handle = warmPool.acquireProvisioned(fn, invokedQualifier);
+ if (handle == null) {
+ handle = warmPool.acquire(fn);
+ }
} catch (Exception e) {
LOG.warnv("Failed to acquire container for function {0}: {1}", fn.getFunctionName(), e.getMessage());
return new InvokeResult(200, "Unhandled",
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/ProvisionedConcurrencyPool.java b/src/main/java/io/github/hectorvent/floci/services/lambda/ProvisionedConcurrencyPool.java
index 17fce92b29..3ce750e6b4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/ProvisionedConcurrencyPool.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/ProvisionedConcurrencyPool.java
@@ -4,41 +4,72 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.ContainerTeardowns;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.lambda.launcher.ContainerHandle;
+import io.github.hectorvent.floci.services.lambda.launcher.LambdaRuntimeLauncher;
+import io.github.hectorvent.floci.services.lambda.model.ContainerState;
import io.github.hectorvent.floci.services.lambda.model.LambdaAlias;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
+import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
-
-/** Stores desired capacity. Runtime allocation is introduced by the next stage. */
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Owns initialized environments separately from the on-demand idle pool.
+ * Persisted requests never imply readiness: every new process must finish real initialization.
+ */
@ApplicationScoped
public class ProvisionedConcurrencyPool implements Resettable {
+ private static final Logger LOG = Logger.getLogger(ProvisionedConcurrencyPool.class);
private static final DateTimeFormatter LAST_MODIFIED =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZone(ZoneOffset.UTC);
private final Object lock = new Object();
+ private final LambdaRuntimeLauncher launcher;
private final LambdaFunctionStore functions;
private final LambdaAliasStore aliases;
private final StorageBackend<String, Configuration> storage;
private final Clock clock;
private final int maxPerFunction;
private final int maxTotal;
- private final boolean supported;
- private final Map<String, Configuration> configurations = new HashMap<>();
+ private final boolean ephemeral;
+ private final long drainTimeoutNanos;
+ private final Map<String, Allocation> allocations = new HashMap<>();
+ private final Map<ContainerHandle, Allocation> leases = new HashMap<>();
+ private final Map<ContainerHandle, Configuration> owned = new HashMap<>();
+ private final Set<Allocation> launchingAllocations = new HashSet<>();
+ private final Set<ContainerHandle> pendingTeardown = new HashSet<>();
+ private final Map<ContainerHandle, CountDownLatch> stopping = new HashMap<>();
+ private final ExecutorService workers = Executors.newVirtualThreadPerTaskExecutor();
+ private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(
+ Thread.ofPlatform().daemon().name("lambda-provisioned-concurrency").factory());
+ private boolean stopped;
+ private int activeLaunches;
+ private long shutdownDeadlineNanos;
@RegisterForReflection
public record Configuration(String account, String region, String name, String functionArn,
@@ -52,32 +83,47 @@ public class ProvisionedConcurrencyPool implements Resettable {
public record Status(int requested, int allocated, int available, String status,
String reason, String lastModified) {}
+ private static final class Allocation {
+ final Configuration configuration;
+ final Set<ContainerHandle> handles = new HashSet<>();
+ final ArrayDeque<ContainerHandle> idle = new ArrayDeque<>();
+ int launching;
+ String status = "IN_PROGRESS";
+ String reason;
+
+ Allocation(Configuration configuration) {
+ this.configuration = configuration;
+ }
+ }
+
+ private static final class TargetUnavailableException extends RuntimeException {
+ TargetUnavailableException() {
+ super("The configured function version or alias is no longer available");
+ }
+ }
+
@Inject
- public ProvisionedConcurrencyPool(LambdaFunctionStore functions, LambdaAliasStore aliases,
- StorageFactory storageFactory, EmulatorConfig config, Clock clock) {
- this(functions, aliases, storageFactory.create("lambda",
+ public ProvisionedConcurrencyPool(LambdaRuntimeLauncher launcher, LambdaFunctionStore functions,
+ LambdaAliasStore aliases, StorageFactory storageFactory,
+ EmulatorConfig config, Clock clock) {
+ this(launcher, functions, aliases, storageFactory.create("lambda",
"lambda-provisioned-concurrency.json", new TypeReference<>() {}),
clock, WarmPool.resolveMaxPerFunction(config), WarmPool.resolveMaxTotal(config),
- !config.services().lambda().ephemeral()
- && "docker".equalsIgnoreCase(config.services().lambda().executor().trim()));
- }
-
- ProvisionedConcurrencyPool(LambdaFunctionStore functions, LambdaAliasStore aliases,
- StorageBackend<String, Configuration> storage,
- Clock clock, int maxPerFunction, int maxTotal) {
- this(functions, aliases, storage, clock, maxPerFunction, maxTotal, true);
+ config.services().lambda().ephemeral(), WarmPool.resolveDrainTimeout(config));
}
- ProvisionedConcurrencyPool(LambdaFunctionStore functions, LambdaAliasStore aliases,
- StorageBackend<String, Configuration> storage,
- Clock clock, int maxPerFunction, int maxTotal, boolean supported) {
- this.supported = supported;
+ ProvisionedConcurrencyPool(LambdaRuntimeLauncher launcher, LambdaFunctionStore functions,
+ LambdaAliasStore aliases, StorageBackend<String, Configuration> storage,
+ Clock clock, int maxPerFunction, int maxTotal, boolean ephemeral, int drainSeconds) {
+ this.launcher = launcher;
this.functions = functions;
this.aliases = aliases;
this.storage = storage;
this.clock = clock;
this.maxPerFunction = maxPerFunction;
this.maxTotal = maxTotal;
+ this.ephemeral = ephemeral;
+ this.drainTimeoutNanos = TimeUnit.SECONDS.toNanos(drainSeconds);
}
@PostConstruct
@@ -86,9 +132,16 @@ public class ProvisionedConcurrencyPool implements Resettable {
List<Configuration> stored = storage instanceof AccountAwareStorageBackend<Configuration> aware
? aware.scanAllAccounts() : storage.scan(ignored -> true);
for (Configuration configuration : stored) {
- configurations.put(configuration.key(), configuration);
+ allocations.put(configuration.key(), new Allocation(configuration));
}
}
+ scheduler.scheduleWithFixedDelay(() -> {
+ try {
+ reconcileSafely();
+ } catch (RuntimeException failure) {
+ LOG.errorv(failure, "Provisioned concurrency reconciliation failed");
+ }
+ }, 0, 1, TimeUnit.SECONDS);
}
public Status put(String region, String name, String qualifier, int count, String account) {
@@ -106,27 +159,35 @@ public class ProvisionedConcurrencyPool implements Resettable {
private Status put(Configuration target) {
int count = target.requested();
- if (!supported) {
+ if (ephemeral || !launcher.supportsProvisionedConcurrency()) {
throw invalid("Provisioned concurrency requires the non-ephemeral Docker Lambda executor");
}
- LambdaFunction fn = functions.getForAccount(target.account(), target.region(), target.name(), target.version())
- .orElseThrow(() -> missing("Function no longer exists"));
+ LambdaFunction fn = currentFunction(target);
if (fn.isHotReload() || fn.isDurable()) {
throw invalid("Provisioned concurrency is not supported for hot-reload or durable functions");
}
+ List<ContainerHandle> retired = List.of();
+ Status result;
synchronized (lock) {
- Configuration previous = configurations.get(target.key());
+ if (stopped) {
+ throw new AwsException("ResourceConflictException", "Lambda executor is stopping", 409);
+ }
+ if (hasPendingTeardown(target)) {
+ throw new AwsException("ResourceConflictException",
+ "The previous provisioned allocation is still being removed", 409);
+ }
+ Allocation previous = allocations.get(target.key());
long otherFunction = 0;
long otherTotal = 0;
boolean versionConflict = false;
- for (Configuration entry : configurations.values()) {
+ for (Allocation entry : allocations.values()) {
if (entry == previous) {
continue;
}
- otherTotal += entry.requested();
- if (target.functionArn().equals(entry.functionArn())) {
- versionConflict |= target.version().equals(pointedVersion(entry));
- otherFunction += entry.requested();
+ otherTotal += entry.configuration.requested();
+ if (target.functionArn().equals(entry.configuration.functionArn())) {
+ versionConflict |= target.version().equals(pointedVersion(entry.configuration));
+ otherFunction += entry.configuration.requested();
}
}
if (otherFunction + count > maxPerFunction
@@ -146,24 +207,33 @@ public class ProvisionedConcurrencyPool implements Resettable {
: "Alias can't be used for Provisioned Concurrency configuration "
+ "on an already Provisioned version", 409);
}
- if (previous != null && sameTarget(previous, target) && previous.requested() == count) {
+ if (previous != null && sameTarget(previous.configuration, target)
+ && previous.configuration.requested() == count && !"FAILED".equals(previous.status)) {
return status(previous);
}
write(target);
- configurations.put(target.key(), target);
- return status(target);
+ Allocation next = new Allocation(target);
+ allocations.put(target.key(), next);
+ if (previous != null) {
+ retired = retire(previous);
+ }
+ result = status(next);
}
+ stop(retired);
+ reconcile();
+ return result;
}
public Status get(String region, String name, String qualifier, String account) {
Target target = resolveTarget(region, name, qualifier, account);
+ reconcile();
synchronized (lock) {
- Configuration configuration = configurations.get(target.key());
- if (configuration == null) {
+ Allocation allocation = allocations.get(target.key());
+ if (allocation == null) {
throw new AwsException("ProvisionedConcurrencyConfigNotFoundException",
"No Provisioned Concurrency Config found for this function", 404);
}
- return status(configuration);
+ return status(allocation);
}
}
@@ -175,6 +245,71 @@ public class ProvisionedConcurrencyPool implements Resettable {
}
}
+ /** Returns null when the matching allocation has no idle capacity: on-demand execution may spill over. */
+ ContainerHandle acquire(LambdaFunction fn, String qualifier) {
+ if (qualifier == null) {
+ return null;
+ }
+ String baseArn = baseArn(fn);
+ List<ContainerHandle> discarded = new ArrayList<>();
+ ContainerHandle selected = null;
+ synchronized (lock) {
+ Allocation allocation = allocations.get(baseArn + ":" + qualifier);
+ if (allocation == null || !allocation.configuration.version().equals(fn.getVersion())) {
+ return null;
+ }
+ try {
+ currentFunction(allocation.configuration);
+ } catch (TargetUnavailableException changed) {
+ return null;
+ }
+ while (!allocation.idle.isEmpty()) {
+ ContainerHandle candidate = allocation.idle.removeFirst();
+ if (healthy(candidate) && current(allocation)) {
+ selected = candidate;
+ leases.put(candidate, allocation);
+ candidate.setState(ContainerState.BUSY);
+ break;
+ }
+ allocation.handles.remove(candidate);
+ pendingTeardown.add(candidate);
+ discarded.add(candidate);
+ }
+ }
+ stop(discarded);
+ return selected;
+ }
+
+ boolean release(ContainerHandle handle, boolean failed) {
+ boolean retire;
+ synchronized (lock) {
+ Allocation allocation = leases.remove(handle);
+ if (allocation == null) {
+ return false;
+ }
+ retire = failed || !current(allocation) || !healthy(handle);
+ if (retire) {
+ allocation.handles.remove(handle);
+ pendingTeardown.add(handle);
+ } else {
+ handle.setState(ContainerState.WARM);
+ allocation.idle.addLast(handle);
+ }
+ }
+ if (retire) {
+ boolean shutdownDrain;
+ long deadline;
+ synchronized (lock) {
+ shutdownDrain = stopped;
+ long now = System.nanoTime();
+ deadline = stopped && shutdownDeadlineNanos > now
+ ? shutdownDeadlineNanos : now + drainTimeoutNanos;
+ }
+ stop(List.of(handle), shutdownDrain, deadline);
+ }
+ return true;
+ }
+
void deleteFunction(LambdaFunction fn) {
deleteMatching(baseArn(fn), null);
}
@@ -188,9 +323,9 @@ public class ProvisionedConcurrencyPool implements Resettable {
return;
}
synchronized (lock) {
- long requested = configurations.values().stream()
- .filter(entry -> entry.functionArn().equals(baseArn(fn)))
- .mapToLong(entry -> entry.requested()).sum();
+ long requested = allocations.values().stream()
+ .filter(entry -> entry.configuration.functionArn().equals(baseArn(fn)))
+ .mapToLong(entry -> entry.configuration.requested()).sum();
if (requested > reserved) {
throw invalid("Reserved concurrency cannot be lower than provisioned concurrency");
}
@@ -198,19 +333,96 @@ public class ProvisionedConcurrencyPool implements Resettable {
}
private void deleteMatching(String functionArn, String qualifier) {
+ List<ContainerHandle> retired = new ArrayList<>();
synchronized (lock) {
- for (Configuration value : new ArrayList<>(configurations.values())) {
+ for (Allocation entry : new ArrayList<>(allocations.values())) {
+ Configuration value = entry.configuration;
if (value.functionArn().equals(functionArn)
&& (qualifier == null || qualifier.equals(value.qualifier()))) {
erase(value);
- configurations.remove(value.key());
+ allocations.remove(value.key());
+ retired.addAll(retire(entry));
+ }
+ }
+ for (ContainerHandle handle : pendingTeardown) {
+ Configuration value = owned.get(handle);
+ if (value.functionArn().equals(functionArn)
+ && (qualifier == null || qualifier.equals(value.qualifier()))) {
+ retired.add(handle);
}
}
}
+ stop(retired);
}
- private Status status(Configuration configuration) {
- return new Status(configuration.requested(), 0, 0, "IN_PROGRESS", null, configuration.lastModified());
+ private boolean hasPendingTeardown(Configuration configuration) {
+ return pendingTeardown.stream().anyMatch(handle ->
+ configuration.key().equals(owned.get(handle).key()));
+ }
+
+ void reconcileSafely() {
+ List<ContainerHandle> retry;
+ synchronized (lock) {
+ if (stopped) {
+ return;
+ }
+ retry = new ArrayList<>(pendingTeardown);
+ }
+ stop(retry);
+ reconcile();
+ }
+
+ void reconcile() {
+ List<ContainerHandle> retired = new ArrayList<>();
+ synchronized (lock) {
+ if (stopped) {
+ return;
+ }
+ for (Allocation allocation : new ArrayList<>(allocations.values())) {
+ if ("FAILED".equals(allocation.status)) {
+ continue;
+ }
+ LambdaFunction fn;
+ try {
+ fn = currentFunction(allocation.configuration);
+ } catch (TargetUnavailableException failure) {
+ allocation.status = "FAILED";
+ allocation.reason = "The configured function version or alias is no longer available";
+ retired.addAll(retire(allocation));
+ continue;
+ }
+ for (ContainerHandle handle : new ArrayList<>(allocation.idle)) {
+ if (!healthy(handle)) {
+ allocation.idle.remove(handle);
+ allocation.handles.remove(handle);
+ pendingTeardown.add(handle);
+ retired.add(handle);
+ }
+ }
+ if (hasPendingTeardown(allocation.configuration)) {
+ continue;
+ }
+ int missing = allocation.configuration.requested()
+ - allocation.handles.size() - allocation.launching;
+ missing = Math.min(missing, availableCapacity(allocation.configuration));
+ if (missing > 0) {
+ allocation.status = "IN_PROGRESS";
+ for (int i = 0; i < missing; i++) {
+ allocation.launching++;
+ launchingAllocations.add(allocation);
+ activeLaunches++;
+ try {
+ workers.execute(() -> initialize(allocation, fn));
+ } catch (RejectedExecutionException failure) {
+ finishedLaunching(allocation);
+ activeLaunches--;
+ throw failure;
+ }
+ }
+ }
+ }
+ }
+ stop(retired);
}
private String pointedVersion(Configuration configuration) {
@@ -225,22 +437,212 @@ public class ProvisionedConcurrencyPool implements Resettable {
void validateAliasUpdate(LambdaFunction fn, String qualifier, String version) {
synchronized (lock) {
String functionArn = baseArn(fn);
- if (!configurations.containsKey(functionArn + ":" + qualifier)) {
+ if (!allocations.containsKey(functionArn + ":" + qualifier)) {
return;
}
if ("$LATEST".equals(version)) {
throw invalid("Provisioned Concurrency Configs cannot be applied to unpublished function versions.");
}
- if (version != null && version.matches("[0-9]+") && configurations.values().stream()
- .anyMatch(entry -> functionArn.equals(entry.functionArn())
- && !qualifier.equals(entry.qualifier())
- && version.equals(pointedVersion(entry)))) {
+ if (version != null && version.matches("[0-9]+") && allocations.values().stream()
+ .anyMatch(entry -> functionArn.equals(entry.configuration.functionArn())
+ && !qualifier.equals(entry.configuration.qualifier())
+ && version.equals(pointedVersion(entry.configuration)))) {
throw new AwsException("ResourceConflictException",
"Alias can't be used for Provisioned Concurrency configuration on an already Provisioned version", 409);
}
}
}
+ private int availableCapacity(Configuration configuration) {
+ long functionOwned = owned.values().stream()
+ .filter(value -> value.functionArn().equals(configuration.functionArn())).count();
+ long functionLaunching = launchingAllocations.stream()
+ .filter(value -> value.configuration.functionArn().equals(configuration.functionArn()))
+ .mapToLong(value -> value.launching).sum();
+ long available = maxPerFunction - functionOwned - functionLaunching;
+ if (maxTotal > 0) {
+ long launching = launchingAllocations.stream().mapToLong(value -> value.launching).sum();
+ available = Math.min(available, maxTotal - owned.size() - launching);
+ }
+ return (int) Math.max(0, available);
+ }
+
+ private void finishedLaunching(Allocation allocation) {
+ allocation.launching--;
+ if (allocation.launching == 0) {
+ launchingAllocations.remove(allocation);
+ }
+ }
+
+ private void initialize(Allocation allocation, LambdaFunction fn) {
+ ContainerHandle handle = null;
+ boolean retained = false;
+ List<ContainerHandle> retired = List.of();
+ try {
+ handle = launcher.launchProvisioned(fn);
+ synchronized (lock) {
+ owned.put(handle, allocation.configuration);
+ finishedLaunching(allocation);
+ if (!current(allocation)) {
+ return;
+ }
+ allocation.handles.add(handle);
+ }
+ long timeoutMs = Math.max(130, fn.getTimeout()) * 1000L;
+ handle.getRuntimeApiServer().awaitInitialization(timeoutMs);
+ synchronized (lock) {
+ currentFunction(allocation.configuration);
+ if (current(allocation) && healthy(handle)) {
+ allocation.idle.addLast(handle);
+ retained = true;
+ if (allocation.handles.size() == allocation.configuration.requested()
+ && allocation.handles.stream().allMatch(this::healthy)) {
+ allocation.status = "READY";
+ }
+ }
+ }
+ } catch (Exception failure) {
+ synchronized (lock) {
+ if (handle == null) {
+ finishedLaunching(allocation);
+ }
+ if (current(allocation)) {
+ allocation.status = "FAILED";
+ allocation.reason = "Execution environment initialization failed: "
+ + failure.getClass().getSimpleName()
+ + (failure.getMessage() == null ? "" : ": " + failure.getMessage());
+ retired = retire(allocation);
+ }
+ }
+ LOG.warnv(failure, "Provisioned Lambda initialization failed");
+ if (failure instanceof InterruptedException) {
+ Thread.currentThread().interrupt();
+ }
+ } finally {
+ Set<ContainerHandle> toStop = new HashSet<>(retired);
+ if (!retained && handle != null) {
+ synchronized (lock) {
+ allocation.handles.remove(handle);
+ allocation.idle.remove(handle);
+ }
+ toStop.add(handle);
+ }
+ boolean shutdownDrain;
+ long deadline;
+ synchronized (lock) {
+ shutdownDrain = stopped;
+ long now = System.nanoTime();
+ deadline = stopped && shutdownDeadlineNanos > now
+ ? shutdownDeadlineNanos : now + drainTimeoutNanos;
+ }
+ try {
+ stop(new ArrayList<>(toStop), shutdownDrain, deadline);
+ } finally {
+ synchronized (lock) {
+ activeLaunches--;
+ lock.notifyAll();
+ }
+ }
+ }
+ }
+
+ private Status status(Allocation allocation) {
+ int healthy = (int) allocation.handles.stream().filter(this::healthy).count();
+ int available = (int) allocation.idle.stream().filter(this::healthy).count();
+ String state = allocation.status;
+ if ("READY".equals(state) && healthy != allocation.configuration.requested()) {
+ state = "IN_PROGRESS";
+ }
+ return new Status(allocation.configuration.requested(), healthy, available, state,
+ allocation.reason, allocation.configuration.lastModified());
+ }
+
+ private boolean healthy(ContainerHandle handle) {
+ return handle.getState() != ContainerState.STOPPED
+ && handle.getRuntimeApiServer().isInitialized();
+ }
+
+ private boolean current(Allocation allocation) {
+ return !stopped && allocations.get(allocation.configuration.key()) == allocation
+ && !"FAILED".equals(allocation.status);
+ }
+
+ private List<ContainerHandle> retire(Allocation allocation) {
+ List<ContainerHandle> result = allocation.handles.stream()
+ .filter(handle -> !leases.containsKey(handle)).toList();
+ allocation.handles.clear();
+ allocation.idle.clear();
+ pendingTeardown.addAll(result);
+ return result;
+ }
+
+ private void stop(List<ContainerHandle> handles) {
+ stop(handles, false);
+ }
+
+ private void stop(List<ContainerHandle> handles, boolean shutdownDrain) {
+ stop(handles, shutdownDrain, System.nanoTime() + drainTimeoutNanos);
+ }
+
+ private void stop(List<ContainerHandle> handles, boolean shutdownDrain, long deadlineNanos) {
+ handles = handles.stream().distinct().toList();
+ synchronized (lock) {
+ for (ContainerHandle handle : handles) {
+ if (owned.containsKey(handle)) {
+ pendingTeardown.add(handle);
+ handle.setState(ContainerState.STOPPED);
+ }
+ }
+ if (stopped && !shutdownDrain) {
+ return;
+ }
+ }
+ ContainerTeardowns.stopInParallel(handles, handle -> stop(handle, shutdownDrain, deadlineNanos),
+ LOG, deadlineNanos);
+ }
+
+ private void stop(ContainerHandle handle, boolean shutdownDrain, long deadlineNanos) {
+ CountDownLatch completion;
+ boolean alreadyStopping;
+ synchronized (lock) {
+ if (!owned.containsKey(handle) || (stopped && !shutdownDrain)) {
+ return;
+ }
+ completion = stopping.get(handle);
+ alreadyStopping = completion != null;
+ if (!alreadyStopping) {
+ completion = new CountDownLatch(1);
+ stopping.put(handle, completion);
+ }
+ }
+ if (alreadyStopping) {
+ // An admitted retry owns this stop. Shutdown joins it within the same bounded
+ // drain instead of returning while it runs, or issuing another Docker stop.
+ if (shutdownDrain) {
+ try {
+ completion.await(Math.max(0, deadlineNanos - System.nanoTime()), TimeUnit.NANOSECONDS);
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ return;
+ }
+ try {
+ launcher.stop(handle);
+ synchronized (lock) {
+ pendingTeardown.remove(handle);
+ owned.remove(handle);
+ }
+ } catch (RuntimeException failure) {
+ LOG.warnv(failure, "Could not stop provisioned Lambda environment {0}", handle.getContainerId());
+ } finally {
+ synchronized (lock) {
+ stopping.remove(handle);
+ }
+ completion.countDown();
+ }
+ }
+
private record Target(String account, String region, String name, String functionArn,
String qualifier, LambdaAlias alias) {
String key() {
@@ -298,6 +700,25 @@ public class ProvisionedConcurrencyPool implements Resettable {
return new Target(account, region, ref.name(), baseArn(latest), qualifier, alias);
}
+ private LambdaFunction currentFunction(Configuration configuration) {
+ functions.getForAccount(configuration.account(), configuration.region(), configuration.name())
+ .orElseThrow(TargetUnavailableException::new);
+ if (!configuration.qualifier().matches("[0-9]+")) {
+ LambdaAlias alias = aliases.getForAccount(configuration.account(), configuration.region(),
+ configuration.name(), configuration.qualifier()).orElseThrow(TargetUnavailableException::new);
+ if (!configuration.version().equals(alias.getFunctionVersion())
+ || (alias.getRoutingConfig() != null && !alias.getRoutingConfig().isEmpty())) {
+ throw new TargetUnavailableException();
+ }
+ }
+ LambdaFunction fn = functions.getForAccount(configuration.account(), configuration.region(),
+ configuration.name(), configuration.version()).orElseThrow(TargetUnavailableException::new);
+ if (!Objects.equals(configuration.revision(), fn.getRevisionId())) {
+ throw new TargetUnavailableException();
+ }
+ return fn;
+ }
+
private static boolean sameTarget(Configuration first, Configuration second) {
return first.key().equals(second.key()) && first.version().equals(second.version())
&& Objects.equals(first.revision(), second.revision());
@@ -327,9 +748,66 @@ public class ProvisionedConcurrencyPool implements Resettable {
@Override
public void clear() {
+ stopManagedContainers();
synchronized (lock) {
storage.clear();
- configurations.clear();
+ stopped = false;
+ }
+ }
+
+ public void stopManagedContainers() {
+ stopManagedContainers(System.nanoTime() + drainTimeoutNanos);
+ }
+
+ void stopManagedContainers(long deadlineNanos) {
+ List<ContainerHandle> retired;
+ synchronized (lock) {
+ if (stopped) {
+ return;
+ }
+ stopped = true;
+ shutdownDeadlineNanos = deadlineNanos;
+ allocations.values().forEach(this::retire);
+ allocations.clear();
+ retired = new ArrayList<>(owned.keySet());
+ }
+ stop(retired, true, deadlineNanos);
+ synchronized (lock) {
+ try {
+ long remaining;
+ while (activeLaunches > 0 && (remaining = deadlineNanos - System.nanoTime()) > 0) {
+ TimeUnit.NANOSECONDS.timedWait(lock, remaining);
+ }
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ if (activeLaunches > 0) {
+ LOG.warnv("Shutdown deadline reached with {0} provisioned Lambda launch(es) still pending",
+ activeLaunches);
+ }
+ }
+ synchronized (lock) {
+ if (!owned.isEmpty()) {
+ LOG.warnv("Shutdown drain ended with {0} provisioned Lambda environment(s) still owned",
+ owned.size());
+ }
+ }
+ }
+
+ void shutdown() {
+ stopManagedContainers();
+ closeExecutors();
+ }
+
+ void closeExecutors() {
+ scheduler.shutdownNow();
+ workers.shutdownNow();
+ }
+
+ @Override
+ public void afterReset() {
+ synchronized (lock) {
+ stopped = false;
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java b/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java
index 9ae52033dd..5f8d6ece0d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java
@@ -95,8 +95,8 @@ public class WarmPool implements ContainerTeardown, Resettable {
@Inject
public WarmPool(LambdaRuntimeLauncher lambdaRuntimeLauncher, EmulatorConfig config, Clock clock,
ProvisionedConcurrencyPool provisioned) {
- this.provisioned = provisioned;
this.lambdaRuntimeLauncher = lambdaRuntimeLauncher;
+ this.provisioned = provisioned;
this.config = config;
this.clock = clock;
this.maxPoolSizePerFunction = resolveMaxPerFunction(config);
@@ -195,13 +195,24 @@ public class WarmPool implements ContainerTeardown, Resettable {
pendingTeardown.addAll(knownHandles);
pendingTeardown.removeIf(handle -> !owned.contains(handle));
}
- drainAll(shutdownState, knownHandles);
+ List<Runnable> drains = new ArrayList<>();
+ if (provisioned != null) {
+ drains.add(() -> provisioned.stopManagedContainers(shutdownState.deadlineNanos));
+ }
+ drains.add(() -> drainAll(shutdownState, knownHandles));
+ ContainerTeardowns.stopInParallel(drains, Runnable::run, LOG, shutdownState.deadlineNanos);
}
@PreDestroy
void shutdown() {
evictionScheduler.shutdownNow();
- stopManagedContainers();
+ try {
+ stopManagedContainers();
+ } finally {
+ if (provisioned != null) {
+ provisioned.closeExecutors();
+ }
+ }
}
@Override
@@ -330,6 +341,9 @@ public class WarmPool implements ContainerTeardown, Resettable {
* Otherwise it is returned to the warm pool.
*/
public void release(ContainerHandle handle) {
+ if (provisioned != null && provisioned.release(handle, false)) {
+ return;
+ }
Lease lease = activeLeases.remove(handle);
if (!owned.contains(handle)) {
return;
@@ -449,12 +463,19 @@ public class WarmPool implements ContainerTeardown, Resettable {
* stop is needed — no pool bookkeeping required.
*/
public void destroyHandle(ContainerHandle handle) {
+ if (provisioned != null && provisioned.release(handle, true)) {
+ return;
+ }
activeLeases.remove(handle);
LOG.debugv("Destroying timed-out container {0} for function {1}",
handle.getContainerId(), handle.getFunctionName());
stopQuietly(handle);
}
+ ContainerHandle acquireProvisioned(LambdaFunction fn, String qualifier) {
+ return provisioned == null ? null : provisioned.acquire(fn, qualifier);
+ }
+
void deleteProvisionedFunction(LambdaFunction fn) {
if (provisioned != null) {
provisioned.deleteFunction(fn);
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 ddcf3094b3..38638c21b4 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
@@ -153,6 +153,20 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
}
public ContainerHandle launch(LambdaFunction fn) {
+ return launch(fn, false);
+ }
+
+ @Override
+ public boolean supportsProvisionedConcurrency() {
+ return true;
+ }
+
+ @Override
+ public ContainerHandle launchProvisioned(LambdaFunction fn) {
+ return launch(fn, true);
+ }
+
+ private ContainerHandle launch(LambdaFunction fn, boolean provisioned) {
LOG.infov("Launching container for function: {0}", fn.getFunctionName());
// For Zip functions, verify code exists before allocating any resources.
@@ -266,6 +280,10 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
env.removeIf(value -> value.startsWith("AWS_LAMBDA_FUNCTION_VERSION="));
env.add("AWS_LAMBDA_FUNCTION_VERSION=" + fn.getVersion());
+ if (provisioned) {
+ env.removeIf(value -> value.startsWith("AWS_LAMBDA_INITIALIZATION_TYPE="));
+ env.add("AWS_LAMBDA_INITIALIZATION_TYPE=provisioned-concurrency");
+ }
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(containerName)
@@ -391,6 +409,11 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
for (String layerArn : fn.getLayers()) {
LambdaLayerVersion layer = layerService.resolveLayerByArnForAccount(
layerArn, lambdaAccountId, lambdaRegion);
+ if (provisioned && (layer == null || layer.getCodeLocalPath() == null
+ || !Files.isDirectory(Path.of(layer.getCodeLocalPath())))) {
+ throw new IllegalStateException("Configured layer is unavailable for provisioned initialization: "
+ + layerArn);
+ }
if (layer != null && layer.getCodeLocalPath() != null) {
Path layerPath = Path.of(layer.getCodeLocalPath());
if (Files.exists(layerPath)) {
@@ -432,7 +455,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
// (e.g. aws-lambda-web-adapter) never start without this. Best-effort: an extension
// launch failure shouldn't fail the whole container launch, since a function with no
// extensions is the common case and this must be a no-op for it.
- launchExtensions(dockerClient, containerId, fn.getFunctionName(), runtimeApiServer, logDestination);
+ launchExtensions(dockerClient, containerId, fn.getFunctionName(), runtimeApiServer, logDestination, provisioned);
// Init-readiness barrier: the execs above are detached, so without waiting here the caller
// could enqueue the first invocation before an extension is ready to receive it — the
@@ -441,7 +464,9 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
// /extension/event/next rather than its register call. A no-extensions function (the
// common case) does not wait at all; a timeout is non-fatal, since a container that serves
// invocations without a slow extension is strictly better than failing the launch.
- awaitExtensionReadiness(runtimeApiServer, fn.getFunctionName());
+ if (!provisioned) {
+ awaitExtensionReadiness(runtimeApiServer, fn.getFunctionName());
+ }
ContainerHandle handle = new ContainerHandle(
containerId, fn.getFunctionName(), runtimeApiServer, ContainerState.WARM, fn.isHotReload(),
@@ -1372,8 +1397,8 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
}
private void launchExtensions(DockerClient dockerClient, String containerId, String functionName,
- RuntimeApiServer runtimeApiServer, LogDestination logDestination) {
- List<String> extensionNames = listExtensionBinaries(dockerClient, containerId, functionName);
+ RuntimeApiServer runtimeApiServer, LogDestination logDestination, boolean strict) {
+ List<String> extensionNames = listExtensionBinaries(dockerClient, containerId, functionName, strict);
// Arm the readiness barrier before starting any extension process, so the latch already
// exists when the first one starts polling /extension/event/next — otherwise a
// fast-starting extension could become ready before there is anything to count it down.
@@ -1402,6 +1427,9 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
LOG.infov("Launched extension {0} for function {1} (container {2})",
name, functionName, containerId);
} catch (Exception e) {
+ if (strict) {
+ throw new IllegalStateException("Could not launch a provisioned Lambda extension", e);
+ }
LOG.warnv(e, "Failed to launch extension {0} for function {1}; continuing without it",
name, functionName);
}
@@ -1442,7 +1470,8 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
* those utilities present, which would silently look like "no extensions" to a shell-based probe.
* The archive API only talks to the Docker daemon, so it works regardless of the image contents.
*/
- private List<String> listExtensionBinaries(DockerClient dockerClient, String containerId, String functionName) {
+ private List<String> listExtensionBinaries(DockerClient dockerClient, String containerId,
+ String functionName, boolean strict) {
try (InputStream tarStream = dockerClient.copyArchiveFromContainerCmd(containerId, EXTENSIONS_DIR).exec();
TarArchiveInputStream tar = new TarArchiveInputStream(tarStream)) {
@@ -1469,6 +1498,9 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
} catch (NotFoundException e) {
return List.of();
} catch (Exception e) {
+ if (strict) {
+ throw new IllegalStateException("Could not discover provisioned Lambda extensions", e);
+ }
LOG.debugv("Could not list {0} for function {1} ({2}); assuming no extensions",
EXTENSIONS_DIR, functionName, e.getMessage());
return List.of();
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaRuntimeLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaRuntimeLauncher.java
index feaccc01a6..526d48c387 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaRuntimeLauncher.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaRuntimeLauncher.java
@@ -12,6 +12,14 @@ public interface LambdaRuntimeLauncher {
ContainerHandle launch(LambdaFunction fn);
+ default boolean supportsProvisionedConcurrency() {
+ return false;
+ }
+
+ default ContainerHandle launchProvisioned(LambdaFunction fn) {
+ throw new UnsupportedOperationException("Provisioned concurrency is not supported by this Lambda executor");
+ }
+
void stop(ContainerHandle handle);
boolean isAlive(ContainerHandle handle);
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/RegisteredExtension.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/RegisteredExtension.java
index f776ae43f5..a9c8f6c908 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/model/RegisteredExtension.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/RegisteredExtension.java
@@ -59,6 +59,10 @@ public class RegisteredExtension {
return waitingContext != null;
}
+ public boolean hasReceivedFirstNext() {
+ return firstNextReceived;
+ }
+
/**
* Records that this extension has issued its first {@code /extension/event/next}, which is
* what AWS treats as the extension being init-ready (registering alone only obtains an
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 6f8b39d544..1fb7b7a760 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
@@ -24,6 +24,7 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
@@ -111,6 +112,8 @@ public class RuntimeApiServer {
// Guards stopped, pendingQueue, waitingContexts, extensions, closeFuture, and every
// RegisteredExtension's pendingEvents/waitingContext. See class doc for the discipline.
private final Object lock = new Object();
+ private final CompletableFuture<Void> initialization = new CompletableFuture<>();
+ private boolean runtimeNextReceived;
// Invocations queued before a /next poller arrived. Guarded by lock.
private final ArrayDeque<PendingInvocation> pendingQueue = new ArrayDeque<>();
@@ -290,6 +293,32 @@ public class RuntimeApiServer {
return faulted;
}
+ /** Waits for runtime and extension initialization, without enqueuing an invocation. */
+ public void awaitInitialization(long timeoutMs) throws Exception {
+ initialization.get(timeoutMs, TimeUnit.MILLISECONDS);
+ synchronized (lock) {
+ if (stopped || faulted) {
+ throw new IllegalStateException("Lambda execution environment is no longer ready");
+ }
+ }
+ }
+
+ public boolean isInitialized() {
+ synchronized (lock) {
+ return initialization.isDone() && !initialization.isCompletedExceptionally() && !stopped && !faulted;
+ }
+ }
+
+ private void completeInitializationIfReady() {
+ synchronized (lock) {
+ CountDownLatch latch = extensionsReady;
+ if (runtimeNextReceived && !stopped && !faulted && latch != null && latch.getCount() == 0
+ && extensions.values().stream().allMatch(RegisteredExtension::hasReceivedFirstNext)) {
+ initialization.complete(null);
+ }
+ }
+ }
+
/**
* Declares how many extension binaries were launched for this container, arming the
* init-readiness barrier that {@link #awaitExtensionsReady(long)} waits on.
@@ -299,7 +328,10 @@ public class RuntimeApiServer {
* no {@code /opt/extensions} directory) leaves the barrier permanently open.
*/
public void expectExtensions(int count) {
- extensionsReady = new CountDownLatch(Math.max(0, count));
+ synchronized (lock) {
+ extensionsReady = new CountDownLatch(Math.max(0, count));
+ completeInitializationIfReady();
+ }
}
/**
@@ -363,6 +395,8 @@ public class RuntimeApiServer {
// AWS Lambda tears an environment down.
waitingContexts.add(ctx);
} else {
+ runtimeNextReceived = true;
+ completeInitializationIfReady();
toDispatch = pendingQueue.poll();
if (toDispatch == null) {
waitingContexts.add(ctx);
@@ -525,6 +559,7 @@ public class RuntimeApiServer {
if (readyLatch != null) {
readyLatch.countDown();
}
+ completeInitializationIfReady();
if (unknownExtension) {
ctx.response().setStatusCode(403)
.putHeader("Content-Type", "application/json")
@@ -606,6 +641,7 @@ public class RuntimeApiServer {
return;
}
stopped = true;
+ initialization.completeExceptionally(new IllegalStateException("Lambda execution environment stopped"));
extensionWritesFlushed = writesFuture;
ExtensionEvent shutdownEvent = ExtensionEvent.shutdown(System.currentTimeMillis() + 2000, "SPINDOWN");
@@ -911,6 +947,7 @@ public class RuntimeApiServer {
List<PendingInvocation> stranded;
synchronized (lock) {
faulted = true;
+ initialization.completeExceptionally(new IllegalStateException("Lambda runtime initialization failed"));
// Retained for a possible later enqueue(): the invocation that triggered this cold
// start may not exist yet (see fatalRuntimeErrorPayload's doc), in which case
// `stranded` below is empty and this is the only place the real error survives.
@@ -1037,6 +1074,7 @@ public class RuntimeApiServer {
return;
}
faulted = true;
+ initialization.completeExceptionally(new IllegalStateException("Lambda runtime exited: " + exitCode));
// Retained for a possible later enqueue(): the invocation that would have hit this
// container may not exist yet (see fatalRuntimeErrorPayload's doc), so this generic,
// requestId-free payload is built here rather than only per-stranded-invocation below.
@@ -1105,6 +1143,7 @@ public class RuntimeApiServer {
// Set under the lock alongside the unregistration so both land as one atomic
// change.
faulted = true;
+ initialization.completeExceptionally(new IllegalStateException("Lambda extension initialization failed"));
// Anything already queued or parked would otherwise wait forever, since the guards
// in enqueue()/NEXT_PATH now refuse to move work through a condemned environment.
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index b61269f03a..f5e93af0de 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -439,7 +439,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
- container-drain-timeout-seconds: 15 # FLOCI_SERVICES_LAMBDA_CONTAINER_DRAIN_TIMEOUT_SECONDS - shared shutdown budget for on-demand Lambda containers
+ 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
region-concurrency-limit: 1000
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java
index 86863d7f64..52f1478761 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java
@@ -464,7 +464,7 @@ class SamTransformIntegrationTest {
}
@Test
- void samAutoPublishAliasKeepsPublishedConfiguration() {
+ void samAutoPublishAliasKeepsPublishedConfigurationAndQualifiesForProvisionedConcurrency() {
String stackName = "sam-published-config-stack";
String function = "sam-published-config-func";
stacksToDelete.add(stackName);
@@ -503,6 +503,12 @@ class SamTransformIntegrationTest {
.when().get("/2015-03-31/functions/" + function + "/configuration")
.then().statusCode(200).body("Version", equalTo("1"))
.body("MemorySize", equalTo(128)).body("Environment.Variables.MARKER", equalTo("original"));
+
+ // No allocation exists, but the generated alias is an eligible immutable target.
+ given().queryParam("Qualifier", "production")
+ .when().get("/2019-09-30/functions/" + function + "/provisioned-concurrency")
+ .then().statusCode(404)
+ .body("__type", equalTo("ProvisionedConcurrencyConfigNotFoundException"));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/ProvisionedConcurrencyPoolTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/ProvisionedConcurrencyPoolTest.java
index 3e3740ce5b..f726bc7a50 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/ProvisionedConcurrencyPoolTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/ProvisionedConcurrencyPoolTest.java
@@ -5,8 +5,13 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.lambda.launcher.ContainerHandle;
+import io.github.hectorvent.floci.services.lambda.launcher.LambdaRuntimeLauncher;
+import io.github.hectorvent.floci.services.lambda.model.ContainerState;
import io.github.hectorvent.floci.services.lambda.model.LambdaAlias;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
+import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;
+import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -16,19 +21,32 @@ import org.junit.jupiter.params.provider.ValueSource;
import java.nio.file.Path;
import java.time.Clock;
+import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
+import java.util.ArrayList;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
+import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
+import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
class ProvisionedConcurrencyPoolTest {
@@ -45,6 +63,7 @@ class ProvisionedConcurrencyPoolTest {
AccountAwareStorageBackend.inMemory(ACCOUNT);
private final LambdaFunctionStore functions = new LambdaFunctionStore(functionStorage);
private final LambdaAliasStore aliases = new LambdaAliasStore(aliasStorage);
+ private final Launcher launcher = new Launcher();
private ProvisionedConcurrencyPool pool;
private LambdaFunction version;
@@ -56,8 +75,14 @@ class ProvisionedConcurrencyPoolTest {
pool = newPool();
}
+ @AfterEach
+ void tearDown() {
+ launcher.launchGate.complete(null);
+ pool.shutdown();
+ }
+
private ProvisionedConcurrencyPool newPool() {
- return new ProvisionedConcurrencyPool(functions, aliases, storage, Clock.systemUTC(), 4, 8);
+ return new ProvisionedConcurrencyPool(launcher, functions, aliases, storage, Clock.systemUTC(), 4, 8, false, 15);
}
private LambdaFunction function(String account, String region, String number) {
@@ -93,6 +118,7 @@ class ProvisionedConcurrencyPoolTest {
assertEquals("The function resource provided must be an alias or a published version.",
error.getMessage());
}
+ assertEquals(0, launcher.starts.get());
}
@ParameterizedTest
@@ -104,6 +130,7 @@ class ProvisionedConcurrencyPoolTest {
+ "' at 'provisionedConcurrentExecutions' failed to satisfy constraint: "
+ "Member must have value greater than or equal to 1", error.getMessage());
assertTrue(storage.scanAllAccounts().isEmpty());
+ assertEquals(0, launcher.starts.get());
}
@Test
@@ -113,6 +140,7 @@ class ProvisionedConcurrencyPoolTest {
assertEquals("No Provisioned Concurrency Config found for this function", error.getMessage());
assertDoesNotThrow(() -> pool.delete(REGION, "example", "live", ACCOUNT));
assertTrue(storage.scanAllAccounts().isEmpty());
+ assertEquals(0, launcher.starts.get());
}
@ParameterizedTest
@@ -137,6 +165,7 @@ class ProvisionedConcurrencyPoolTest {
}
}
assertTrue(storage.scanAllAccounts().isEmpty());
+ assertEquals(0, launcher.starts.get());
}
@Test
@@ -146,13 +175,15 @@ class ProvisionedConcurrencyPoolTest {
assertEquals("Cannot find alias arn: arn:aws-cn:lambda:cn-north-1:222222222222:function:absent:live",
error.getMessage());
assertTrue(storage.scanAllAccounts().isEmpty());
+ assertEquals(0, launcher.starts.get());
}
@ParameterizedTest
@ValueSource(strings = {"1", "peer"})
- void provisionedAliasRefusesAnotherQualifierOfTheSameVersion(String qualifier) {
+ void provisionedAliasRefusesAnotherQualifierOfTheSameVersion(String qualifier) throws Exception {
alias(ACCOUNT, REGION, "peer", "1", Map.of());
put(1);
+ launched();
AwsException error = assertThrows(AwsException.class,
() -> pool.put(REGION, "example", qualifier, 1, ACCOUNT));
assertEquals("ResourceConflictException", error.getErrorCode());
@@ -160,24 +191,29 @@ class ProvisionedConcurrencyPoolTest {
: "Alias can't be used for Provisioned Concurrency configuration on an already Provisioned version",
error.getMessage());
assertEquals(1, storage.scanAllAccounts().size());
+ assertEquals(1, launcher.starts.get());
}
@Test
- void provisionedVersionRefusesAliasButAllowsADifferentVersion() {
+ void provisionedVersionRefusesAliasButAllowsADifferentVersion() throws Exception {
pool.put(REGION, "example", "1", 1, ACCOUNT);
+ launched();
AwsException error = assertThrows(AwsException.class, () -> put(1));
assertEquals("ResourceConflictException", error.getErrorCode());
assertEquals("Alias can't be used for Provisioned Concurrency configuration on an already Provisioned version",
error.getMessage());
function(ACCOUNT, REGION, "2");
pool.put(REGION, "example", "2", 1, ACCOUNT);
+ launched();
assertEquals(2, storage.scanAllAccounts().size());
+ assertEquals(2, launcher.starts.get());
}
@Test
void lastModifiedUsesLambdasUtcOffsetForm() {
- pool = new ProvisionedConcurrencyPool(functions, aliases, storage,
- Clock.fixed(Instant.parse("2026-10-20T20:11:30.987Z"), ZoneOffset.UTC), 4, 8);
+ pool.shutdown();
+ pool = new ProvisionedConcurrencyPool(launcher, functions, aliases, storage,
+ Clock.fixed(Instant.parse("2026-10-20T20:11:30.987Z"), ZoneOffset.UTC), 4, 8, false, 15);
assertEquals("2026-10-20T20:11:30+0000", put(1).lastModified());
}
@@ -185,131 +221,935 @@ class ProvisionedConcurrencyPoolTest {
return pool.get(REGION, "example", "live", ACCOUNT);
}
+ private Environment launched() throws Exception {
+ Environment environment = launcher.launched.poll(5, TimeUnit.SECONDS);
+ assertNotNull(environment);
+ return environment;
+ }
+
+ private void ready() {
+ await().atMost(Duration.ofSeconds(5)).until(() -> "READY".equals(get().status()));
+ }
+
+ @Test
+ void initializationThenExactQualifierReuseDoesNotInvokeHandler() throws Exception {
+ assertEquals("IN_PROGRESS", put(1).status());
+ Environment first = launched();
+ assertEquals("IN_PROGRESS", get().status());
+ assertEquals(0, get().allocated());
+ assertNull(pool.acquire(version, "live"));
+ first.initialized.complete(null);
+ ready();
+ assertEquals(1, get().allocated());
+ assertEquals(1, get().available());
+ assertNull(pool.acquire(version, null));
+ assertNull(pool.acquire(version, "1"));
+ assertNull(pool.acquire(version, "other"));
+ assertNull(pool.acquire(function("222222222222", REGION, "1"), "live"));
+ assertNull(pool.acquire(function(ACCOUNT, "eu-west-1", "1"), "live"));
+ assertSame(first.handle, pool.acquire(version, "live"));
+ assertEquals(0, get().available());
+ assertTrue(pool.release(first.handle, false));
+ assertSame(first.handle, pool.acquire(version, "live"));
+ assertTrue(pool.release(first.handle, false));
+ verify(first.runtime, never()).enqueue(any());
+ assertEquals(1, launcher.starts.get());
+ }
+
+ @Test
+ void repeatedPutPreservesTheCurrentAllocation() throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ String modified = get().lastModified();
+ assertEquals("READY", put(1).status());
+ assertEquals(modified, get().lastModified());
+ assertEquals(1, launcher.starts.get());
+ }
+
+ @Test
+ void replacingCapacityDefersAUsedEnvironmentUntilRelease() throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ assertSame(first.handle, pool.acquire(version, "live"));
+ put(2);
+ assertEquals(0, first.stops.get());
+ assertEquals(ContainerState.BUSY, first.handle.getState());
+ assertTrue(pool.release(first.handle, false));
+ assertEquals(1, first.stops.get());
+ }
+
@ParameterizedTest
- @ValueSource(strings = {"persistent", "hybrid", "wal"})
- void storedConfigurationSurvivesFactoryRestartAndDeletedConfigurationStaysDeleted(String mode) {
- EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
- when(config.defaultAccountId()).thenReturn(ACCOUNT);
- when(config.services().lambda().executor()).thenReturn("docker");
- when(config.storage().persistentPath()).thenReturn(storagePath.toString());
- when(config.storage().wal().compactionIntervalMs()).thenReturn(60_000L);
- ServiceConfigAccess access = mock(ServiceConfigAccess.class);
- when(access.storageMode("lambda")).thenReturn(mode);
- when(access.storageFlushInterval("lambda")).thenReturn(60_000L);
- for (int restart = 0; restart < 3; restart++) {
- StorageFactory factory = new StorageFactory(config, access);
- try {
- pool = new ProvisionedConcurrencyPool(functions, aliases, factory, config, Clock.systemUTC());
- pool.start();
- if (restart == 0) {
- put(2);
- } else if (restart == 1) {
- assertEquals(2, get().requested());
- assertEquals("IN_PROGRESS", get().status());
- assertEquals(0, get().allocated());
- pool.delete(REGION, "example", "live", ACCOUNT);
+ @CsvSource({"1,0,false", "4,1,false", "4,1,true"})
+ void retiredLeasesStillCountAgainstContainerCeilings(int perFunction, int total,
+ boolean differentAccount) throws Exception {
+ pool.shutdown();
+ pool = new ProvisionedConcurrencyPool(launcher, functions, aliases, storage,
+ Clock.systemUTC(), perFunction, total, false, 15);
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ assertSame(first.handle, pool.acquire(version, "live"));
+ String account = replacementTarget(differentAccount);
+ pool.put(REGION, "example", "live", 1, account);
+ assertNull(launcher.launched.poll(100, TimeUnit.MILLISECONDS));
+ assertEquals(0, first.stops.get());
+
+ assertTrue(pool.release(first.handle, false));
+ pool.reconcile();
+ Environment replacement = launched();
+ replacement.initialized.complete(null);
+ await().atMost(Duration.ofSeconds(5)).until(() ->
+ "READY".equals(pool.get(REGION, "example", "live", account).status()));
+ assertEquals(1, first.stops.get());
+ assertEquals(2, launcher.starts.get());
+ }
+
+ @ParameterizedTest
+ @CsvSource({"1,0,false", "4,1,false", "4,1,true"})
+ void retiredLaunchesStillCountAgainstContainerCeilings(int perFunction, int total,
+ boolean differentAccount) throws Exception {
+ pool.shutdown();
+ pool = new ProvisionedConcurrencyPool(launcher, functions, aliases, storage,
+ Clock.systemUTC(), perFunction, total, false, 15);
+ launcher.launchGate = new CompletableFuture<>();
+ put(1);
+ Environment first = launched();
+ String account = replacementTarget(differentAccount);
+ pool.put(REGION, "example", "live", 1, account);
+ assertNull(launcher.launched.poll(100, TimeUnit.MILLISECONDS));
+
+ launcher.launchGate.complete(null);
+ await().atMost(Duration.ofSeconds(5)).until(() -> first.stops.get() == 1);
+ await().atMost(Duration.ofSeconds(5)).until(() -> {
+ pool.reconcile();
+ return launcher.starts.get() == 2;
+ });
+ Environment replacement = launched();
+ replacement.initialized.complete(null);
+ await().atMost(Duration.ofSeconds(5)).until(() ->
+ "READY".equals(pool.get(REGION, "example", "live", account).status()));
+ assertEquals(2, launcher.starts.get());
+ }
+
+ private String replacementTarget(boolean differentAccount) {
+ String account = differentAccount ? "222222222222" : ACCOUNT;
+ if (differentAccount) {
+ function(account, REGION, "$LATEST");
+ pool.delete(REGION, "example", "live", ACCOUNT);
+ }
+ function(account, REGION, "2");
+ alias(account, REGION, "live", "2", Map.of());
+ return account;
+ }
+
+ @Test
+ void deletingCapacityDefersAUsedEnvironmentUntilRelease() throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ assertSame(first.handle, pool.acquire(version, "live"));
+ pool.delete(REGION, "example", "live", ACCOUNT);
+ assertEquals(0, first.stops.get());
+ assertThrows(AwsException.class, this::get);
+ assertTrue(pool.release(first.handle, false));
+ assertEquals(1, first.stops.get());
+ }
+
+ @Test
+ void synchronousReconciliationFailureReachesTheCaller() throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ IllegalStateException failure = new IllegalStateException("readiness lookup failed");
+ when(first.runtime.isInitialized()).thenThrow(failure);
+ assertSame(failure, assertThrows(IllegalStateException.class, this::get));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void provisioningRechecksFunctionAndReservationAfterTheirMutation(boolean deleted) throws Exception {
+ LambdaFunction latest = functions.getForAccount(ACCOUNT, REGION, "example").orElseThrow();
+ AtomicReference<Thread> requester = new AtomicReference<>();
+ CompletableFuture<ProvisionedConcurrencyPool.Status> request;
+ try (ExecutorService tasks = Executors.newSingleThreadExecutor()) {
+ synchronized (functions.lockForConcurrencyOp(latest.getFunctionArn())) {
+ request = CompletableFuture.supplyAsync(() -> {
+ requester.set(Thread.currentThread());
+ return put(2);
+ }, tasks);
+ awaitBlockedOrDone(requester, request);
+ assertFalse(request.isDone());
+ if (deleted) {
+ functionStorage.deleteForAccount(ACCOUNT, "lambda::" + REGION + "::example::$LATEST");
} else {
- assertThrows(AwsException.class, this::get);
+ latest.setReservedConcurrentExecutions(1);
+ functions.saveForAccount(ACCOUNT, REGION, latest);
}
- } finally {
- factory.shutdownAll();
}
+ ExecutionException failure = assertThrows(ExecutionException.class,
+ () -> request.get(5, TimeUnit.SECONDS));
+ AwsException error = assertInstanceOf(AwsException.class, failure.getCause());
+ assertEquals(deleted ? "ResourceNotFoundException" : "InvalidParameterValueException",
+ error.getErrorCode());
+ assertTrue(storage.scanAllAccounts().isEmpty());
+ assertEquals(0, launcher.starts.get());
}
}
@Test
- void unsupportedExecutorRejectsPutWithoutPersistingButExistingConfigurationCanBeRemoved() {
+ void deleteDuringInitializationStopsOnceAndNeverRestoresReady() throws Exception {
put(1);
- pool = new ProvisionedConcurrencyPool(functions, aliases, storage, Clock.systemUTC(), 4, 8, false);
+ Environment first = launched();
+ pool.delete(REGION, "example", "live", ACCOUNT);
+ await().atMost(Duration.ofSeconds(5)).until(() -> first.stops.get() == 1);
+ first.initialized.complete(null);
+ AwsException missing = assertThrows(AwsException.class, this::get);
+ assertEquals("ProvisionedConcurrencyConfigNotFoundException", missing.getErrorCode());
+ pool.reconcile();
+ assertEquals(1, launcher.starts.get());
+ assertEquals(1, first.stops.get());
+ }
+
+ @Test
+ void deleteBeforeLaunchReturnsStopsTheLateHandle() throws Exception {
+ launcher.launchGate = new CompletableFuture<>();
+ put(1);
+ Environment first = launched();
+ pool.delete(REGION, "example", "live", ACCOUNT);
+ launcher.launchGate.complete(null);
+ await().atMost(Duration.ofSeconds(5)).until(() -> first.stops.get() == 1);
+ assertThrows(AwsException.class, this::get);
+ }
+
+ @Test
+ void failedStopRemainsOwnedAfterDeleteCommits() throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ launcher.stopFailures.set(1);
+ assertDoesNotThrow(() -> pool.delete(REGION, "example", "live", ACCOUNT));
+ assertEquals("ProvisionedConcurrencyConfigNotFoundException",
+ assertThrows(AwsException.class, this::get).getErrorCode());
+ assertTrue(first.alive);
+ pool.reconcileSafely();
+ assertFalse(first.alive);
+ assertEquals(2, first.stops.get());
+ assertDoesNotThrow(() -> pool.delete(REGION, "example", "live", ACCOUNT));
+ }
+
+ @Test
+ void replacingCapacityCommitsAndWaitsForCleanupBeforeInitializing() throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ launcher.stopFailures.set(2);
+
+ assertEquals("IN_PROGRESS", assertDoesNotThrow(() -> put(2)).status());
+ assertTrue(first.alive);
+ assertEquals(1, launcher.starts.get());
+ assertEquals("IN_PROGRESS", get().status());
+ assertEquals(0, get().allocated());
+ assertEquals(2, get().requested());
+ assertEquals("ResourceConflictException", assertThrows(AwsException.class, () -> put(2)).getErrorCode());
+
+ pool.reconcileSafely();
+ assertTrue(first.alive);
+ assertEquals(1, launcher.starts.get());
+
+ pool.reconcileSafely();
+ assertFalse(first.alive);
+ Environment second = launched();
+ Environment third = launched();
+ second.initialized.complete(null);
+ third.initialized.complete(null);
+ ready();
+ assertEquals(3, first.stops.get());
+ assertEquals(3, launcher.starts.get());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"configuration", "alias", "function"})
+ void deletionCommitsWhileAnEarlierStopIsStillRunning(String scope) throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ first.faulted.set(true);
+ first.stopGate = new CompletableFuture<>();
+ CompletableFuture<ContainerHandle> discard = CompletableFuture.supplyAsync(() -> pool.acquire(version, "live"));
+ try {
+ assertSame(first, launcher.stopping.poll(2, TimeUnit.SECONDS));
+ assertDoesNotThrow(() -> {
+ switch (scope) {
+ case "configuration" -> pool.delete(REGION, "example", "live", ACCOUNT);
+ case "alias" -> pool.deleteQualifier(version, "live");
+ case "function" -> pool.deleteFunction(version);
+ default -> throw new AssertionError(scope);
+ }
+ });
+ assertEquals("ProvisionedConcurrencyConfigNotFoundException",
+ assertThrows(AwsException.class, this::get).getErrorCode());
+ assertEquals(1, first.stops.get(), "The admitted stopper retains exclusive ownership");
+ } finally {
+ first.stopGate.complete(null);
+ assertNull(discard.get(5, TimeUnit.SECONDS));
+ }
+ assertFalse(first.alive);
+ assertDoesNotThrow(() -> put(1));
+ Environment replacement = launched();
+ replacement.initialized.complete(null);
+ ready();
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void lateReleaseCleansUpAfterFailedOrExpiredShutdown(boolean expiredDeadline) throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ assertSame(first.handle, pool.acquire(version, "live"));
+ int initialAttempts;
+ if (expiredDeadline) {
+ pool.stopManagedContainers(System.nanoTime() - 1);
+ initialAttempts = 0;
+ } else {
+ launcher.stopFailures.set(1);
+ pool.stopManagedContainers(System.nanoTime() + TimeUnit.SECONDS.toNanos(2));
+ initialAttempts = 1;
+ }
+ assertEquals(initialAttempts, first.stops.get());
+ assertTrue(first.alive);
+ assertTrue(pool.release(first.handle, false));
+ assertFalse(first.alive);
+ assertEquals(initialAttempts + 1, first.stops.get());
+ assertFalse(pool.release(first.handle, false));
+ pool.shutdown();
+ assertEquals(initialAttempts + 1, first.stops.get(),
+ "Repeated release and shutdown do not create another stop");
+ }
+
+ @Test
+ void failedReleaseRetainsOwnedCleanupWithoutChangingCompletedInvocationDispatch() throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ assertSame(first.handle, pool.acquire(version, "live"));
+ pool.delete(REGION, "example", "live", ACCOUNT);
+ launcher.stopFailures.set(1);
+
+ assertTrue(pool.release(first.handle, false));
+ assertTrue(first.alive);
+ assertEquals(1, first.stops.get());
+ assertThrows(AwsException.class, this::get);
+
+ pool.reconcileSafely();
+ assertFalse(first.alive);
+ assertEquals(2, first.stops.get());
+ }
+
+ @Test
+ void initializationFailureIsFailedAndExplicitPutCanRetry() throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.completeExceptionally(new IllegalStateException("controlled init failure"));
+ await().atMost(Duration.ofSeconds(5)).until(() -> "FAILED".equals(get().status()));
+ assertTrue(get().reason().contains("controlled init failure"));
+ assertEquals(0, get().allocated());
+ assertEquals(1, first.stops.get());
+ put(1);
+ Environment second = launched();
+ second.initialized.complete(null);
+ ready();
+ assertEquals(2, launcher.starts.get());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"function", "version", "alias"})
+ void lookupFailuresPropagateWithoutRetiringReadyCapacity(String lookup) throws Exception {
+ pool.shutdown();
+ LambdaFunctionStore functionLookup = spy(functions);
+ LambdaAliasStore aliasLookup = spy(aliases);
+ pool = new ProvisionedConcurrencyPool(launcher, functionLookup, aliasLookup,
+ storage, Clock.systemUTC(), 4, 8, false, 15);
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ IllegalStateException failure = new IllegalStateException("controlled lookup outage");
+ switch (lookup) {
+ case "function" -> doThrow(failure).when(functionLookup).getForAccount(ACCOUNT, REGION, "example");
+ case "version" -> doThrow(failure).when(functionLookup).getForAccount(ACCOUNT, REGION, "example", "1");
+ case "alias" -> doThrow(failure).when(aliasLookup).getForAccount(ACCOUNT, REGION, "example", "live");
+ default -> throw new AssertionError(lookup);
+ }
+ assertSame(failure, assertThrows(IllegalStateException.class, () -> pool.acquire(version, "live")));
+ assertSame(failure, assertThrows(IllegalStateException.class, pool::reconcile));
+ assertSame(failure, assertThrows(IllegalStateException.class, pool::reconcileSafely));
+ assertTrue(first.alive);
+ assertEquals(0, first.stops.get());
+ reset(functionLookup, aliasLookup);
+ assertEquals("READY", get().status());
+ assertSame(first.handle, pool.acquire(version, "live"));
+ assertTrue(pool.release(first.handle, false));
+ }
+
+ @Test
+ void scheduledReconciliationRetriesAfterLookupOutages() throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ pool.shutdown();
+ LambdaAliasStore aliasLookup = spy(aliases);
+ doThrow(new IllegalStateException("controlled scheduler lookup outage"))
+ .when(aliasLookup).getForAccount(ACCOUNT, REGION, "example", "live");
+ pool = new ProvisionedConcurrencyPool(launcher, functions, aliasLookup,
+ storage, Clock.systemUTC(), 4, 8, false, 15);
pool.start();
- assertEquals(1, get().requested());
- AwsException failure = assertThrows(AwsException.class, () -> put(2));
- assertEquals("Provisioned concurrency requires the non-ephemeral Docker Lambda executor", failure.getMessage());
+ await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
+ verify(aliasLookup, atLeast(2)).getForAccount(ACCOUNT, REGION, "example", "live"));
+ doCallRealMethod().when(aliasLookup).getForAccount(ACCOUNT, REGION, "example", "live");
+ Environment replacement = launched();
+ replacement.initialized.complete(null);
+ ready();
+ assertEquals("READY", get().status());
+ assertEquals(1, first.stops.get());
+ }
+
+ @Test
+ void failedEnvironmentIsReplacedAfterReady() throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ first.alive = false;
+ pool.reconcile();
+ assertEquals("IN_PROGRESS", get().status());
+ Environment replacement = launched();
+ replacement.initialized.complete(null);
+ ready();
+ assertEquals(1, first.stops.get());
+ }
+
+ @Test
+ void runtimeFaultReplacesCapacityWithoutDockerHealthChecks() throws Exception {
+ launcher.rejectHealthChecks = true;
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ assertSame(first.handle, pool.acquire(version, "live"));
+ assertTrue(pool.release(first.handle, false));
+ assertEquals("READY", put(1).status());
+ first.faulted.set(true);
+
+ pool.reconcile();
+ assertEquals("IN_PROGRESS", get().status());
+ Environment replacement = launched();
+ replacement.initialized.complete(null);
+ ready();
+ assertSame(replacement.handle, pool.acquire(version, "live"));
+ assertTrue(pool.release(replacement.handle, false));
+ assertEquals(1, first.stops.get());
+ }
+
+ @Test
+ void faultReplacementWaitsUntilTheOldEnvironmentCanBeRemoved() throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ first.faulted.set(true);
+ launcher.stopFailures.set(1);
+
+ pool.reconcile();
+ assertTrue(first.alive);
+ assertEquals(1, launcher.starts.get());
+ assertEquals("IN_PROGRESS", get().status());
+ assertEquals(1, launcher.starts.get());
+
+ pool.reconcileSafely();
+ assertFalse(first.alive);
+ Environment replacement = launched();
+ replacement.initialized.complete(null);
+ ready();
+ assertEquals(2, first.stops.get());
+ assertEquals(2, launcher.starts.get());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"weighted", "latest"})
+ void changedAliasRemainsReadableAndDeletable(String change) throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ alias(ACCOUNT, REGION, "live", "latest".equals(change) ? "$LATEST" : "1",
+ "weighted".equals(change) ? Map.of("2", 0.1) : Map.of());
assertEquals(1, get().requested());
pool.delete(REGION, "example", "live", ACCOUNT);
assertTrue(storage.scanAllAccounts().isEmpty());
+ assertEquals(1, first.stops.get());
+ }
+
+ @Test
+ void aliasCannotMoveToLatestUntilItsProvisionedConfigurationIsDeleted() throws Exception {
+ put(1);
+ launched();
+ AwsException error = assertThrows(AwsException.class,
+ () -> pool.validateAliasUpdate(version, "live", "$LATEST"));
+ assertEquals("Provisioned Concurrency Configs cannot be applied to unpublished function versions.",
+ error.getMessage());
+ assertDoesNotThrow(() -> pool.validateAliasUpdate(version, "live", "2"));
+ pool.delete(REGION, "example", "live", ACCOUNT);
+ assertDoesNotThrow(() -> pool.validateAliasUpdate(version, "live", "$LATEST"));
}
@Test
- void replacementAndRestoreKeepDesiredCapacityWithoutClaimingReadiness() {
- ProvisionedConcurrencyPool.Status initial = put(1);
- assertEquals(initial, put(1));
- assertEquals(2, put(2).requested());
+ void restoredDesiredConfigurationMustInitializeNewProcesses() throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ pool.shutdown();
pool = newPool();
pool.start();
- ProvisionedConcurrencyPool.Status restored = get();
- assertEquals(2, restored.requested());
- assertEquals(0, restored.allocated());
- assertEquals(0, restored.available());
- assertEquals("IN_PROGRESS", restored.status());
- pool.delete(REGION, "example", "live", ACCOUNT);
- assertTrue(storage.scanAllAccounts().isEmpty());
- assertThrows(AwsException.class, this::get);
+ Environment second = launched();
+ assertEquals("IN_PROGRESS", get().status());
+ assertEquals(1, first.stops.get());
+ second.initialized.complete(null);
+ ready();
}
@Test
- void reservationsAndQualifiersShareTheFunctionCeiling() {
- LambdaFunction latest = functions.getForAccount(ACCOUNT, REGION, "example").orElseThrow();
- latest.setReservedConcurrentExecutions(2);
- assertThrows(AwsException.class, () -> put(3));
+ void shutdownDrainsIdleAndBusyEnvironmentsConcurrentlyWithoutDuplicateStops() throws Exception {
+ put(4);
+ List<Environment> environments = new ArrayList<>();
+ for (int i = 0; i < 4; i++) {
+ Environment environment = launched();
+ environments.add(environment);
+ environment.initialized.complete(null);
+ }
+ ready();
+ assertNotNull(pool.acquire(version, "live"));
+ launcher.stopGate = new CompletableFuture<>();
+ CompletableFuture<Void> drained = CompletableFuture.runAsync(pool::stopManagedContainers);
+ try {
+ for (Environment environment : environments) {
+ assertNotNull(launcher.stopping.poll(2, TimeUnit.SECONDS),
+ "Every environment must start stopping before the others finish");
+ }
+ assertFalse(drained.isDone(), "Teardown must wait for the container stops");
+ assertEquals(409, assertThrows(AwsException.class, () -> put(1)).getHttpStatus());
+ pool.stopManagedContainers();
+ for (Environment environment : environments) {
+ assertEquals(1, environment.stops.get());
+ }
+ } finally {
+ launcher.stopGate.complete(null);
+ drained.get(10, TimeUnit.SECONDS);
+ }
+ for (Environment environment : environments) {
+ assertFalse(environment.alive);
+ assertEquals(1, environment.stops.get());
+ }
+ }
+
+ @Test
+ void shutdownWaitsForAndRemovesALaunchThatReturnsAfterAdmissionCloses() throws Exception {
+ launcher.launchGate = new CompletableFuture<>();
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ CompletableFuture<Void> shutdown = CompletableFuture.runAsync(() ->
+ pool.stopManagedContainers(System.nanoTime() + TimeUnit.SECONDS.toNanos(2)));
+ try {
+ assertThrows(TimeoutException.class, () -> shutdown.get(100, TimeUnit.MILLISECONDS));
+ assertEquals(409, assertThrows(AwsException.class, () -> put(1)).getHttpStatus());
+ assertEquals(0, first.stops.get());
+ launcher.launchGate.complete(null);
+ shutdown.get(3, TimeUnit.SECONDS);
+ assertFalse(first.alive);
+ assertEquals(1, first.stops.get());
+ pool.stopManagedContainers();
+ assertEquals(1, first.stops.get());
+ } finally {
+ launcher.launchGate.complete(null);
+ shutdown.get(3, TimeUnit.SECONDS);
+ }
+ }
+
+ @Test
+ void pendingLaunchPreservesShutdownDeadlineAndCleansUpWhenItReturns() throws Exception {
+ launcher.launchGate = new CompletableFuture<>();
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ CompletableFuture<Void> shutdown = CompletableFuture.runAsync(() ->
+ pool.stopManagedContainers(System.nanoTime() + TimeUnit.SECONDS.toNanos(1)));
+ try {
+ shutdown.get(3, TimeUnit.SECONDS);
+ pool.stopManagedContainers();
+ assertEquals(0, first.stops.get());
+ assertEquals(409, assertThrows(AwsException.class, () -> put(1)).getHttpStatus());
+ } finally {
+ launcher.launchGate.complete(null);
+ }
+ await().atMost(Duration.ofSeconds(5)).until(() -> !first.alive);
+ assertEquals(1, first.stops.get());
+ pool.stopManagedContainers();
+ assertEquals(1, first.stops.get());
+ pool.clear();
+ assertEquals(1, first.stops.get());
+ assertTrue(storage.scan(ignored -> true).isEmpty());
+ }
+
+ @Test
+ void suppliedShutdownDeadlineCancelsRemovalAndResetCanRetry() throws Exception {
+ put(1);
+ Environment environment = launched();
+ environment.initialized.complete(null);
+ ready();
+ launcher.stopGate = new CompletableFuture<>();
+ CompletableFuture<Void> drained = CompletableFuture.runAsync(() ->
+ pool.stopManagedContainers(System.nanoTime() + TimeUnit.SECONDS.toNanos(1)));
+ try {
+ assertNotNull(launcher.stopping.poll(2, TimeUnit.SECONDS));
+ drained.get(3, TimeUnit.SECONDS);
+ assertTrue(environment.alive, "Canceled Docker removal must remain owned");
+ pool.stopManagedContainers();
+ assertEquals(1, environment.stops.get(), "The destruction path must not renew the deadline");
+ } finally {
+ launcher.stopGate.complete(null);
+ }
+ pool.clear();
+ await().atMost(Duration.ofSeconds(5)).until(() -> {
+ pool.reconcileSafely();
+ return !environment.alive;
+ });
+ int completedAttempts = environment.stops.get();
+ pool.stopManagedContainers();
+ assertEquals(completedAttempts, environment.stops.get());
+ }
+
+ @Test
+ void configuredBudgetBoundsResetAndNormalRemovalAndRetainsRetry() throws Exception {
+ pool.shutdown();
+ EmulatorConfig config = mock(EmulatorConfig.class);
+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
+ EmulatorConfig.LambdaServiceConfig lambda = mock(EmulatorConfig.LambdaServiceConfig.class);
+ StorageFactory factory = mock(StorageFactory.class);
+ when(config.services()).thenReturn(services);
+ when(services.lambda()).thenReturn(lambda);
+ when(lambda.warmPoolMaxPerFunction()).thenReturn(Optional.of(4));
+ when(lambda.warmPoolMaxTotal()).thenReturn(8);
+ when(lambda.containerDrainTimeoutSeconds()).thenReturn(1);
+ when(factory.<ProvisionedConcurrencyPool.Configuration>create(
+ eq("lambda"), eq("lambda-provisioned-concurrency.json"), any())).thenReturn(storage);
+ pool = new ProvisionedConcurrencyPool(launcher, functions, aliases, factory, config, Clock.systemUTC());
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ first.stopGate = new CompletableFuture<>();
+ CompletableFuture<Void> removal = CompletableFuture.runAsync(() ->
+ pool.delete(REGION, "example", "live", ACCOUNT));
+ try {
+ assertSame(first, launcher.stopping.poll(2, TimeUnit.SECONDS));
+ removal.get(3, TimeUnit.SECONDS);
+ assertTrue(first.alive);
+ } finally {
+ first.stopGate.complete(null);
+ }
+ await().atMost(Duration.ofSeconds(5)).until(() -> {
+ pool.reconcileSafely();
+ return !first.alive;
+ });
+
put(1);
+ Environment second = launched();
+ second.initialized.complete(null);
+ ready();
+ second.stopGate = new CompletableFuture<>();
+ CompletableFuture<Void> reset = CompletableFuture.runAsync(pool::clear);
+ try {
+ assertSame(first, launcher.stopping.poll(2, TimeUnit.SECONDS));
+ assertSame(second, launcher.stopping.poll(2, TimeUnit.SECONDS));
+ reset.get(3, TimeUnit.SECONDS);
+ assertTrue(second.alive);
+ } finally {
+ second.stopGate.complete(null);
+ }
+ await().atMost(Duration.ofSeconds(5)).until(() -> {
+ pool.reconcileSafely();
+ return !second.alive;
+ });
+ assertTrue(storage.scan(ignored -> true).isEmpty());
+ }
+
+ @Test
+ void interruptedDrainRetainsEveryOwnedEnvironmentForRetry() throws Exception {
+ pool.shutdown();
+ pool = new ProvisionedConcurrencyPool(
+ launcher, functions, aliases, storage, Clock.systemUTC(), 32, 32, false, 15);
+ put(32);
+ List<Environment> environments = new ArrayList<>();
+ for (int i = 0; i < 32; i++) {
+ Environment environment = launched();
+ environments.add(environment);
+ environment.initialized.complete(null);
+ }
+ ready();
+ launcher.stopGate = new CompletableFuture<>();
+ AtomicBoolean interruptionPreserved = new AtomicBoolean();
+ Thread drain = Thread.ofPlatform().start(() -> {
+ pool.stopManagedContainers();
+ interruptionPreserved.set(Thread.currentThread().isInterrupted());
+ });
+ try {
+ for (int i = 0; i < environments.size(); i++) {
+ assertNotNull(launcher.stopping.poll(2, TimeUnit.SECONDS));
+ }
+ assertEquals(environments.size(),
+ environments.stream().mapToInt(environment -> environment.stops.get()).sum());
+ drain.interrupt();
+ drain.join(5000);
+ assertFalse(drain.isAlive());
+ assertTrue(interruptionPreserved.get());
+ } finally {
+ drain.interrupt();
+ launcher.stopGate.complete(null);
+ drain.join(5000);
+ }
+ int attempts = environments.stream().mapToInt(environment -> environment.stops.get()).sum();
+ pool.stopManagedContainers();
+ pool.reconcileSafely();
+ assertEquals(attempts, environments.stream().mapToInt(environment -> environment.stops.get()).sum());
+ // A deliberate reset reopens normal reconciliation; repeated shutdown never does.
+ pool.clear();
+ await().atMost(Duration.ofSeconds(5)).until(() -> {
+ pool.reconcileSafely();
+ return environments.stream().noneMatch(environment -> environment.alive);
+ });
+ assertTrue(environments.stream().allMatch(environment -> environment.stops.get() > 0));
+ }
+
+ @Test
+ void failedShutdownIsNotRetriedByReconciliationOrBeanDestruction() throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ launcher.stopFailures.set(1);
+
+ pool.stopManagedContainers();
+ assertTrue(first.alive);
+ assertEquals(1, first.stops.get());
+ pool.reconcileSafely();
+ pool.stopManagedContainers();
+ pool.shutdown();
+
+ assertTrue(first.alive, "A failed stop must remain visible rather than imply cleanup succeeded");
+ assertEquals(1, first.stops.get(), "Shutdown must not renew the drain budget");
+ }
+
+ @Test
+ void reconciliationCannotRetryWhileTheShutdownDrainIsRunning() throws Exception {
+ put(2);
+ Environment held = launched();
+ Environment failed = launched();
+ held.initialized.complete(null);
+ failed.initialized.complete(null);
+ ready();
+ held.stopGate = new CompletableFuture<>();
+ launcher.stopFailures.set(1);
+ CompletableFuture<Void> drained = CompletableFuture.runAsync(pool::stopManagedContainers);
+ try {
+ assertNotNull(launcher.stopping.poll(2, TimeUnit.SECONDS));
+ assertNotNull(launcher.stopping.poll(2, TimeUnit.SECONDS));
+ await().atMost(Duration.ofSeconds(2)).until(() -> launcher.stopFailures.get() == 0);
+ assertFalse(drained.isDone());
+
+ pool.reconcileSafely();
+ assertEquals(1, failed.stops.get(), "The scheduler must not compete with shutdown");
+ assertEquals(1, held.stops.get());
+ } finally {
+ held.stopGate.complete(null);
+ drained.get(5, TimeUnit.SECONDS);
+ }
+ }
+
+ @Test
+ void shutdownWaitsForAnAdmittedRetryWithoutStoppingTheHandleTwice() throws Exception {
+ put(1);
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
function(ACCOUNT, REGION, "2");
pool.put(REGION, "example", "2", 1, ACCOUNT);
- assertThrows(AwsException.class, () -> pool.validateReservation(latest, 1));
- pool.delete(REGION, "example", "2", ACCOUNT);
- assertDoesNotThrow(() -> pool.validateReservation(latest, 1));
- assertEquals(1, get().requested());
+ Environment second = launched();
+ second.initialized.complete(null);
+ await().atMost(Duration.ofSeconds(2)).until(() ->
+ "READY".equals(pool.get(REGION, "example", "2", ACCOUNT).status()));
+ launcher.stopFailures.set(1);
+ pool.delete(REGION, "example", "live", ACCOUNT);
+ launcher.stopping.clear();
+ first.stopGate = new CompletableFuture<>();
+ try (ExecutorService tasks = Executors.newFixedThreadPool(2)) {
+ CompletableFuture<Void> retry = CompletableFuture.runAsync(pool::reconcileSafely, tasks);
+ CompletableFuture<Void> shutdown = null;
+ try {
+ assertSame(first, launcher.stopping.poll(2, TimeUnit.SECONDS));
+ shutdown = CompletableFuture.runAsync(pool::stopManagedContainers, tasks);
+ assertSame(second, launcher.stopping.poll(2, TimeUnit.SECONDS),
+ "Shutdown has admitted its own handle while joining the earlier retry");
+ CompletableFuture<Void> drain = shutdown;
+ assertThrows(TimeoutException.class, () -> drain.get(100, TimeUnit.MILLISECONDS));
+ assertEquals(2, first.stops.get());
+ } finally {
+ first.stopGate.complete(null);
+ retry.get(5, TimeUnit.SECONDS);
+ if (shutdown != null) {
+ shutdown.get(5, TimeUnit.SECONDS);
+ }
+ }
+ }
+ assertFalse(first.alive);
+ assertFalse(second.alive);
+ assertEquals(2, first.stops.get());
+ assertEquals(1, second.stops.get());
+ pool.shutdown();
+ assertEquals(2, first.stops.get());
}
@Test
- void quotaErrorPrecedesVersionConflictAndRejectedReplacementPreservesTheRequest() {
- put(4);
- AwsException failure = assertThrows(AwsException.class,
- () -> pool.put(REGION, "example", "1", 1, ACCOUNT));
- assertEquals("InvalidParameterValueException", failure.getErrorCode());
+ void configurationValidationHasNoLaunchSideEffects() {
+ assertThrows(AwsException.class, () -> put(0));
assertThrows(AwsException.class, () -> put(5));
- assertEquals(4, get().requested());
+ assertThrows(AwsException.class, () -> pool.put(REGION, "example", null, 1, ACCOUNT));
+ assertThrows(AwsException.class, () -> pool.put(REGION, "example", "$LATEST", 1, ACCOUNT));
+ assertThrows(AwsException.class, () -> pool.put(REGION, "absent", "live", 1, ACCOUNT));
+ assertThrows(AwsException.class, () -> pool.put(REGION, "example", "2", 1, ACCOUNT));
+ alias(ACCOUNT, REGION, "weighted", "1", Map.of("2", 0.1));
+ assertThrows(AwsException.class, () -> pool.put(REGION, "example", "weighted", 1, ACCOUNT));
+ launcher.supported = false;
+ assertThrows(AwsException.class, () -> put(1));
+ assertEquals(0, launcher.starts.get());
}
@Test
- void deletionAndResetRespectAccountAndRegionOwnership() {
+ void reservationsAndMultipleQualifiersShareTheFunctionCeiling() throws Exception {
+ LambdaFunction latest = functions.getForAccount(ACCOUNT, REGION, "example").orElseThrow();
+ latest.setReservedConcurrentExecutions(1);
+ assertThrows(AwsException.class, () -> put(2));
put(1);
- for (String account : List.of(ACCOUNT, "222222222222")) {
- function(account, "eu-west-1", "$LATEST");
- function(account, "eu-west-1", "1");
- alias(account, "eu-west-1", "live", "1", Map.of());
- pool.put("eu-west-1", "example", "live", 1, account);
- }
+ launched();
+ assertThrows(AwsException.class, () -> pool.put(REGION, "example", "1", 1, ACCOUNT));
+ assertThrows(AwsException.class, () -> pool.validateReservation(latest, 0));
+ }
+
+ @Test
+ void deletingOneAccountPreservesTheSameFunctionInAnotherAccount() throws Exception {
+ function("222222222222", REGION, "$LATEST");
+ function("222222222222", REGION, "1");
+ alias("222222222222", REGION, "live", "1", Map.of());
+ put(1);
+ Environment first = launched();
+ pool.put(REGION, "example", "live", 1, "222222222222");
+ Environment second = launched();
+ first.initialized.complete(null);
+ second.initialized.complete(null);
+ ready();
pool.deleteFunction(version);
- assertThrows(AwsException.class, this::get);
- assertEquals(2, storage.scanAllAccounts().size());
- for (String account : List.of(ACCOUNT, "222222222222")) {
- assertEquals(1, pool.get("eu-west-1", "example", "live", account).requested());
+ assertEquals(1, first.stops.get());
+ assertEquals(0, second.stops.get());
+ await().atMost(Duration.ofSeconds(5)).until(() ->
+ "READY".equals(pool.get(REGION, "example", "live", "222222222222").status()));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"persistent", "hybrid", "wal"})
+ void storedConfigurationSurvivesFactoryRestartAndDeletedConfigurationStaysDeleted(String mode) throws Exception {
+ pool.shutdown();
+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(config.defaultAccountId()).thenReturn(ACCOUNT);
+ when(config.services().lambda().executor()).thenReturn("docker");
+ when(config.services().lambda().containerDrainTimeoutSeconds()).thenReturn(15);
+ when(config.storage().persistentPath()).thenReturn(storagePath.toString());
+ when(config.storage().wal().compactionIntervalMs()).thenReturn(60_000L);
+ ServiceConfigAccess access = mock(ServiceConfigAccess.class);
+ when(access.storageMode("lambda")).thenReturn(mode);
+ when(access.storageFlushInterval("lambda")).thenReturn(60_000L);
+ for (int restart = 0; restart < 3; restart++) {
+ StorageFactory factory = new StorageFactory(config, access);
+ try {
+ pool = new ProvisionedConcurrencyPool(launcher, functions, aliases, factory, config, Clock.systemUTC());
+ pool.start();
+ if (restart == 0) {
+ put(2);
+ launched().initialized.complete(null);
+ launched().initialized.complete(null);
+ ready();
+ } else if (restart == 1) {
+ assertEquals(2, get().requested());
+ assertEquals("IN_PROGRESS", get().status());
+ assertEquals(0, get().allocated());
+ launched().initialized.complete(null);
+ launched().initialized.complete(null);
+ ready();
+ pool.delete(REGION, "example", "live", ACCOUNT);
+ } else {
+ assertThrows(AwsException.class, this::get);
+ }
+ } finally {
+ pool.shutdown();
+ factory.shutdownAll();
+ }
}
- pool.clear();
- assertTrue(storage.scanAllAccounts().isEmpty());
- pool.start();
- assertThrows(AwsException.class, () -> pool.get("eu-west-1", "example", "live", ACCOUNT));
}
@Test
- void weightedAliasLookupAndDeletionDoNotReapplyPutEligibility() {
+ void changedAliasRequiresExplicitPutBeforeUsingNewVersion() throws Exception {
put(1);
- alias(ACCOUNT, REGION, "live", "1", Map.of("2", 0.1));
+ Environment first = launched();
+ first.initialized.complete(null);
+ ready();
+ function(ACCOUNT, REGION, "2");
+ alias(ACCOUNT, REGION, "live", "2", Map.of());
+ assertNull(pool.acquire(version, "live"));
+ assertEquals("FAILED", get().status());
assertEquals(1, get().requested());
- assertThrows(AwsException.class, () -> put(2));
- pool.delete(REGION, "example", "live", ACCOUNT);
- assertTrue(storage.scanAllAccounts().isEmpty());
+ assertEquals(1, first.stops.get());
+ assertEquals("1", storage.scanAllAccounts().getFirst().version());
+ put(1);
+ Environment second = launched();
+ second.initialized.complete(null);
+ ready();
+ assertEquals("2", storage.scanAllAccounts().getFirst().version());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
- void configuredAliasCannotRetargetToCapacityOwnedByAnotherQualifier(boolean otherAlias) {
+ void configuredAliasCannotRetargetToCapacityOwnedByAnotherQualifier(boolean otherAlias) throws Exception {
function(ACCOUNT, REGION, "2");
alias(ACCOUNT, REGION, "peer", "2", Map.of());
put(1);
+ launched().initialized.complete(null);
+ ready();
String destination = otherAlias ? "peer" : "2";
pool.put(REGION, "example", destination, 1, ACCOUNT);
+ launched().initialized.complete(null);
AwsException conflict = assertThrows(AwsException.class,
() -> pool.validateAliasUpdate(version, "live", "2"));
assertEquals("ResourceConflictException", conflict.getErrorCode());
@@ -325,57 +1165,87 @@ class ProvisionedConcurrencyPoolTest {
assertDoesNotThrow(() -> pool.validateAliasUpdate(version, "live", "2"));
}
- @Test
- void aliasCannotMoveToLatestWhileItHasRequestedCapacity() {
- put(1);
- assertThrows(AwsException.class, () -> pool.validateAliasUpdate(version, "live", "$LATEST"));
- pool.deleteQualifier(version, "live");
- assertDoesNotThrow(() -> pool.validateAliasUpdate(version, "live", "$LATEST"));
- }
+ private static final class Environment {
+ final RuntimeApiServer runtime = mock(RuntimeApiServer.class);
+ final CompletableFuture<Void> initialized = new CompletableFuture<>();
+ final AtomicInteger stops = new AtomicInteger();
+ final AtomicBoolean faulted = new AtomicBoolean();
+ final ContainerHandle handle;
+ volatile CompletableFuture<Void> stopGate = CompletableFuture.completedFuture(null);
+ volatile boolean alive = true;
- @Test
- void failedStorageMutationPreservesTheLastVisibleConfigurationForRetry() {
- AccountAwareStorageBackend<ProvisionedConcurrencyPool.Configuration> backend = spy(storage);
- pool = new ProvisionedConcurrencyPool(functions, aliases, backend, Clock.systemUTC(), 4, 8);
- put(1);
- IllegalStateException outage = new IllegalStateException("storage unavailable");
- doThrow(outage).when(backend)
- .putForAccount(any(), any(), any());
- assertSame(outage, assertThrows(IllegalStateException.class, () -> put(2)));
- assertEquals(1, get().requested());
- doThrow(outage).when(backend)
- .deleteForAccount(any(), any());
- assertSame(outage, assertThrows(IllegalStateException.class,
- () -> pool.delete(REGION, "example", "live", ACCOUNT)));
- assertEquals(1, get().requested());
- doCallRealMethod().when(backend)
- .deleteForAccount(any(), any());
- pool.delete(REGION, "example", "live", ACCOUNT);
- assertThrows(AwsException.class, this::get);
+ Environment(int id, LambdaFunction fn) throws Exception {
+ handle = new ContainerHandle("environment-" + id, fn.getFunctionName(), runtime, ContainerState.WARM);
+ doAnswer(call -> {
+ initialized.get(5, TimeUnit.SECONDS);
+ return null;
+ }).when(runtime).awaitInitialization(anyLong());
+ when(runtime.isInitialized()).thenAnswer(call ->
+ initialized.isDone() && !initialized.isCompletedExceptionally() && alive && !faulted.get());
+ }
}
- @ParameterizedTest
- @ValueSource(booleans = {false, true})
- void putRechecksDeletionAndReservationAfterAcquiringTheSharedLock(boolean deleted) throws Exception {
- AtomicReference<Thread> requester = new AtomicReference<>();
- try (ExecutorService tasks = Executors.newSingleThreadExecutor()) {
- Future<?> put;
- synchronized (functions.lockForConcurrencyOp(functions.getForAccount(ACCOUNT, REGION, "example").orElseThrow().getFunctionArn())) {
- put = tasks.submit(() -> {
- requester.set(Thread.currentThread());
- assertThrows(AwsException.class, () -> put(1));
- });
- awaitBlockedOrDone(requester, put);
- assertFalse(put.isDone());
- if (deleted) {
- functions.delete(REGION, "example");
- } else {
- functions.getForAccount(ACCOUNT, REGION, "example").orElseThrow()
- .setReservedConcurrentExecutions(0);
- }
+ private static final class Launcher implements LambdaRuntimeLauncher {
+ final BlockingQueue<Environment> launched = new LinkedBlockingQueue<>();
+ final BlockingQueue<Environment> stopping = new LinkedBlockingQueue<>();
+ final Map<ContainerHandle, Environment> environments = new ConcurrentHashMap<>();
+ final AtomicInteger starts = new AtomicInteger();
+ final AtomicInteger stopFailures = new AtomicInteger();
+ volatile CompletableFuture<Void> launchGate = CompletableFuture.completedFuture(null);
+ volatile CompletableFuture<Void> stopGate = CompletableFuture.completedFuture(null);
+ boolean supported = true;
+ boolean rejectHealthChecks;
+
+ @Override
+ public ContainerHandle launch(LambdaFunction fn) {
+ throw new AssertionError("Provisioning must not invoke the on-demand launch path");
+ }
+
+ @Override
+ public boolean supportsProvisionedConcurrency() {
+ return supported;
+ }
+
+ @Override
+ public ContainerHandle launchProvisioned(LambdaFunction fn) {
+ try {
+ Environment environment = new Environment(starts.incrementAndGet(), fn);
+ environments.put(environment.handle, environment);
+ launched.add(environment);
+ launchGate.get(5, TimeUnit.SECONDS);
+ return environment.handle;
+ } catch (Exception failure) {
+ throw new IllegalStateException(failure);
}
- put.get(5, TimeUnit.SECONDS);
}
- assertTrue(storage.scanAllAccounts().isEmpty());
+
+ @Override
+ public boolean isAlive(ContainerHandle handle) {
+ if (rejectHealthChecks) {
+ throw new AssertionError("Provisioned health must use runtime fault/exit signals");
+ }
+ return environments.get(handle).alive;
+ }
+
+ @Override
+ public void stop(ContainerHandle handle) {
+ Environment environment = environments.get(handle);
+ environment.stops.incrementAndGet();
+ stopping.add(environment);
+ try {
+ stopGate.get(5, TimeUnit.SECONDS);
+ environment.stopGate.get(5, TimeUnit.SECONDS);
+ } catch (InterruptedException failure) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(failure);
+ } catch (Exception failure) {
+ throw new IllegalStateException(failure);
+ }
+ if (stopFailures.getAndUpdate(value -> Math.max(0, value - 1)) > 0) {
+ throw new IllegalStateException("controlled first stop failure");
+ }
+ environment.alive = false;
+ environment.initialized.completeExceptionally(new IllegalStateException("stopped"));
+ }
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/WarmPoolTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/WarmPoolTest.java
index c5dab6102b..74a0da8688 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/WarmPoolTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/WarmPoolTest.java
@@ -29,6 +29,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static org.awaitility.Awaitility.await;
@@ -38,6 +39,7 @@ 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.anyLong;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
@@ -61,11 +63,11 @@ class WarmPoolTest {
}
private WarmPool buildPool(Optional<Integer> maxPerFunction, int maxTotal) {
- return buildPool(maxPerFunction, maxTotal, 15);
+ return buildPool(maxPerFunction, maxTotal, null, 15);
}
private WarmPool buildPool(Optional<Integer> maxPerFunction, int maxTotal,
- int drainSeconds) {
+ ProvisionedConcurrencyPool provisioned, int drainSeconds) {
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.LambdaServiceConfig lambda = mock(EmulatorConfig.LambdaServiceConfig.class);
when(config.services()).thenReturn(services);
@@ -75,7 +77,7 @@ class WarmPoolTest {
when(lambda.warmPoolMaxPerFunction()).thenReturn(maxPerFunction);
when(lambda.warmPoolMaxTotal()).thenReturn(maxTotal);
when(lambda.containerDrainTimeoutSeconds()).thenReturn(drainSeconds);
- return new WarmPool(containerLauncher, config, clock);
+ return new WarmPool(containerLauncher, config, clock, provisioned);
}
private static LambdaFunction function(String name) {
@@ -189,7 +191,7 @@ class WarmPoolTest {
@Test
void shutdownDeadlineCancelsConcurrentRemovalsAndResetRetainsThemForRetry() throws Exception {
- WarmPool pool = buildPool(Optional.empty(), 0, 1);
+ WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
ContainerHandle first = new ContainerHandle("first", "first", null, ContainerState.WARM);
ContainerHandle second = new ContainerHandle("second", "second", null, ContainerState.WARM);
when(containerLauncher.launch(any())).thenReturn(first, second);
@@ -238,7 +240,7 @@ class WarmPoolTest {
@Test
void releaseAfterShutdownDeadlineRetriesFailedRemoval() throws Exception {
- WarmPool pool = buildPool(Optional.empty(), 0, 1);
+ WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
LambdaFunction fn = function("late-release");
ContainerHandle busy = new ContainerHandle("busy", "late-release", null, ContainerState.WARM);
ContainerHandle slow = new ContainerHandle("slow", "late-release", null, ContainerState.WARM);
@@ -303,7 +305,7 @@ class WarmPoolTest {
@Test
void functionDrainUsesConfiguredBudgetAndMaintenanceRetriesCanceledRemoval() throws Exception {
- WarmPool pool = buildPool(Optional.empty(), 0, 1);
+ WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
ContainerHandle handle = new ContainerHandle("bounded-drain", "bounded", null, ContainerState.WARM);
when(containerLauncher.launch(any())).thenReturn(handle);
AtomicInteger attempts = new AtomicInteger();
@@ -338,6 +340,68 @@ class WarmPoolTest {
verify(containerLauncher, times(2)).stop(handle);
}
+ @Test
+ void bothPoolsUseOneConfiguredDeadlineAndCanceledRemovalRemainsRetryable() throws Exception {
+ ProvisionedConcurrencyPool provisioned = mock(ProvisionedConcurrencyPool.class);
+ WarmPool pool = buildPool(Optional.empty(), 0, provisioned, 1);
+ pool.init();
+ ContainerHandle handle = new ContainerHandle("cid-canceled", "cancel-fn", null, ContainerState.WARM);
+ when(containerLauncher.launch(any())).thenReturn(handle);
+ LambdaFunction fn = function("cancel-fn");
+ pool.release(pool.acquire(fn));
+ CountDownLatch bothStarted = new CountDownLatch(2);
+ CountDownLatch bothInterrupted = new CountDownLatch(2);
+ CountDownLatch release = new CountDownLatch(1);
+ AtomicLong provisionedDeadline = new AtomicLong();
+ doAnswer(invocation -> {
+ provisionedDeadline.set(invocation.getArgument(0));
+ bothStarted.countDown();
+ try {
+ release.await();
+ } catch (InterruptedException interrupted) {
+ bothInterrupted.countDown();
+ Thread.currentThread().interrupt();
+ }
+ return null;
+ }).when(provisioned).stopManagedContainers(anyLong());
+ doAnswer(invocation -> {
+ bothStarted.countDown();
+ try {
+ release.await();
+ } catch (InterruptedException interrupted) {
+ bothInterrupted.countDown();
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(interrupted);
+ }
+ return null;
+ }).when(containerLauncher).stop(handle);
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ long before = System.nanoTime();
+ Future<?> drain = executor.submit(pool::stopManagedContainers);
+ try {
+ assertTrue(bothStarted.await(3, TimeUnit.SECONDS),
+ "Both pools must start draining before either pool finishes");
+ drain.get(5, TimeUnit.SECONDS);
+ assertTrue(bothInterrupted.await(3, TimeUnit.SECONDS));
+ assertTrue(provisionedDeadline.get() >= before + TimeUnit.SECONDS.toNanos(1));
+ assertTrue(provisionedDeadline.get() <= System.nanoTime());
+ assertThrows(RuntimeException.class, () -> pool.acquire(fn));
+ pool.shutdown();
+ verify(containerLauncher, times(1)).stop(handle);
+ verify(provisioned, times(1)).stopManagedContainers(anyLong());
+
+ pool.afterReset();
+ doNothing().when(containerLauncher).stop(handle);
+ pool.drainFunction("cancel-fn");
+ pool.drainFunction("cancel-fn");
+ verify(containerLauncher, times(2)).stop(handle);
+ } finally {
+ release.countDown();
+ executor.shutdownNow();
+ pool.shutdown();
+ }
+ }
+
@Test
void warmHandleRemovedDuringLivenessProbeIsNotOwnedAgain() throws Exception {
WarmPool pool = buildPool();
@@ -373,7 +437,7 @@ class WarmPoolTest {
@Test
void knownWarmHandleStopsWhileColdLaunchRemainsBlocked() throws Exception {
- WarmPool pool = buildPool(Optional.empty(), 0, 1);
+ WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
pool.init();
ContainerHandle warm = new ContainerHandle("cid-known", "known-fn", null, ContainerState.WARM);
ContainerHandle late = new ContainerHandle("cid-blocked", "blocked-fn", null, ContainerState.WARM);
@@ -415,7 +479,7 @@ class WarmPoolTest {
@Test
void oldColdLaunchCannotAcquireAfterResetReopensPool() throws Exception {
- WarmPool pool = buildPool(Optional.empty(), 0, 1);
+ WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
pool.init();
LambdaFunction fn = function("reset-fn");
ContainerHandle old = new ContainerHandle("cid-old-launch", "reset-fn", null, ContainerState.WARM);
@@ -494,7 +558,7 @@ class WarmPoolTest {
@Test
void launchBeyondShutdownDeadlineIsRefusedAndStopped() throws Exception {
- WarmPool pool = buildPool(Optional.empty(), 0, 1);
+ WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
pool.init();
LambdaFunction fn = function("late-fn");
ContainerHandle handle = new ContainerHandle("cid-late", "late-fn", null, ContainerState.WARM);
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java
index b605250c14..14176e664e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java
@@ -89,6 +89,7 @@ class ContainerLauncherTest {
@Mock RuntimeApiServer runtimeApiServer;
@Mock DockerClient dockerClient;
@Mock LambdaExecutionRoleCredentials executionRoleCredentials;
+ @Mock LambdaLayerService layerService;
@TempDir
Path tempDir;
@@ -144,7 +145,7 @@ class ContainerLauncherTest {
LaunchedContainerAwsEnv awsEnv = new LaunchedContainerAwsEnv(reachableEndpoint);
launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver,
runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager,
- mock(io.github.hectorvent.floci.services.lambda.LambdaLayerService.class), awsEnv,
+ layerService, awsEnv,
executionRoleCredentials);
when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer);
@@ -661,6 +662,16 @@ class ContainerLauncherTest {
verify(lifecycleManager, never()).createAndStart(any());
}
+ private static LambdaFunction imageFunction() {
+ LambdaFunction fn = new LambdaFunction();
+ fn.setFunctionName("image-function");
+ fn.setAccountId("222233334444");
+ fn.setFunctionArn("arn:aws:lambda:us-east-1:222233334444:function:image-function");
+ fn.setPackageType("Image");
+ fn.setImageUri("unit-lambda:latest");
+ return fn;
+ }
+
@Test
void launchFunction_injectsDefaultAwsCredentials() throws Exception {
Path codePath = Files.createDirectory(tempDir.resolve("creds-defaults"));
@@ -682,6 +693,120 @@ class ContainerLauncherTest {
"AWS_SESSION_TOKEN should be injected when awsConfigPath is absent");
}
+ @ParameterizedTest
+ @ValueSource(strings = {"$LATEST", "1", "7"})
+ void onDemandLaunchUsesTheSelectedVersion(String version) {
+ LambdaFunction fn = imageFunction();
+ fn.setVersion(version);
+ fn.setEnvironment(Map.of("AWS_LAMBDA_FUNCTION_VERSION", "user-override"));
+
+ launcher.launch(fn);
+
+ assertEquals(List.of("AWS_LAMBDA_FUNCTION_VERSION=" + version),
+ captureRealContainerSpec().env().stream()
+ .filter(value -> value.startsWith("AWS_LAMBDA_FUNCTION_VERSION=")).toList());
+ }
+
+ @Test
+ void provisionedLaunchUsesTheImmutableVersionAndPlatformInitializationType() throws Exception {
+ stubExtensionDiscovery("example-extension");
+ when(logStreamer.execLogCallbackForAccount(anyString(), anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(new ResultCallback.Adapter<>());
+ LambdaFunction fn = imageFunction();
+ fn.setVersion("7");
+ fn.setEnvironment(Map.of("AWS_LAMBDA_INITIALIZATION_TYPE", "on-demand",
+ "AWS_LAMBDA_FUNCTION_VERSION", "$LATEST"));
+ launcher.launchProvisioned(fn);
+ List<String> env = captureRealContainerSpec().env();
+ assertEquals(List.of("AWS_LAMBDA_FUNCTION_VERSION=7"),
+ env.stream().filter(value -> value.startsWith("AWS_LAMBDA_FUNCTION_VERSION=")).toList());
+ assertEquals(List.of("AWS_LAMBDA_INITIALIZATION_TYPE=provisioned-concurrency"),
+ env.stream().filter(value -> value.startsWith("AWS_LAMBDA_INITIALIZATION_TYPE=")).toList());
+ verify(runtimeApiServer).expectExtensions(1);
+ verify(runtimeApiServer, never()).awaitExtensionsReady(anyLong());
+ verify(runtimeApiServer, never()).enqueue(any());
+ }
+
+ @Test
+ void provisionedLaunchRefusesFailedExtensionDiscoveryAndCleansTheCreatedRuntime() {
+ LambdaFunction fn = imageFunction();
+ fn.setVersion("1");
+ CopyArchiveFromContainerCmd archive = mock(CopyArchiveFromContainerCmd.class);
+ when(dockerClient.copyArchiveFromContainerCmd("container-123", "/opt/extensions")).thenReturn(archive);
+ when(archive.exec()).thenThrow(new IllegalStateException("controlled archive failure"));
+ assertThrows(RuntimeException.class, () -> launcher.launchProvisioned(fn));
+ verify(runtimeApiServerFactory).release(runtimeApiServer);
+ verify(runtimeApiServer, never()).expectExtensions(0);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void provisionedLaunchCopiesTheStoredAccountsLayerWithoutAmbientLookup(boolean legacyAccount) throws Exception {
+ LambdaFunction fn = imageFunction();
+ fn.setAccountId(legacyAccount ? null : "123456789012");
+ fn.setFunctionArn("arn:aws:lambda:eu-west-1:123456789012:function:layer-function");
+ fn.setVersion("1");
+ String arn = "arn:aws:lambda:eu-west-1:123456789012:layer:owned:1";
+ fn.setLayers(List.of(arn));
+ Path layerPath = Files.createDirectory(tempDir.resolve("owned-layer"));
+ Files.writeString(layerPath.resolve("dependency.txt"), "owned");
+ LambdaLayerVersion layer = new LambdaLayerVersion();
+ layer.setCodeLocalPath(layerPath.toString());
+ when(layerService.resolveLayerByArnForAccount(arn, "123456789012", "eu-west-1")).thenReturn(layer);
+ stubExtensionDiscovery();
+
+ launcher.launchProvisioned(fn);
+
+ assertTrue(capturedRemotePaths.contains("/opt"));
+ verify(layerService, never()).resolveLayerByArn(anyString());
+ verify(lifecycleManager).startCreated(eq("container-123"), any());
+ verify(runtimeApiServer).expectExtensions(0);
+ }
+
+ @ParameterizedTest
+ @MethodSource("unavailableLayerPaths")
+ void provisionedLaunchRefusesMissingLayerInputsAndCleansBeforeStart(String pathKind) throws Exception {
+ LambdaFunction fn = imageFunction();
+ fn.setAccountId("123456789012");
+ fn.setFunctionArn("arn:aws:lambda:us-east-1:123456789012:function:missing-layer");
+ fn.setVersion("1");
+ String arn = "arn:aws:lambda:us-east-1:123456789012:layer:missing:1";
+ fn.setLayers(List.of(arn));
+ if (!"unresolved".equals(pathKind)) {
+ LambdaLayerVersion layer = new LambdaLayerVersion();
+ if ("absent".equals(pathKind)) {
+ layer.setCodeLocalPath(tempDir.resolve("absent").toString());
+ } else if ("regular-file".equals(pathKind)) {
+ layer.setCodeLocalPath(Files.writeString(tempDir.resolve("not-a-directory"), "data").toString());
+ }
+ when(layerService.resolveLayerByArnForAccount(eq(arn), eq("123456789012"), anyString()))
+ .thenReturn(layer);
+ }
+ IllegalStateException error = assertThrows(IllegalStateException.class,
+ () -> launcher.launchProvisioned(fn));
+ assertTrue(error.getMessage().startsWith("Configured layer is unavailable for provisioned initialization:"));
+ verify(lifecycleManager, never()).startCreated(anyString(), any());
+ verify(lifecycleManager).stopAndRemove("container-123", null);
+ verify(runtimeApiServerFactory).release(runtimeApiServer);
+ verify(runtimeApiServer, never()).expectExtensions(anyInt());
+ verify(runtimeApiServer, never()).enqueue(any());
+ }
+
+ private static Stream<String> unavailableLayerPaths() {
+ return Stream.of("unresolved", "null-path", "absent", "regular-file");
+ }
+
+ @Test
+ void ordinaryLaunchRetainsItsUnresolvedLayerBehavior() {
+ LambdaFunction fn = imageFunction();
+ String arn = "arn:aws:lambda:us-east-1:123456789012:layer:missing:1";
+ fn.setLayers(List.of(arn));
+ launcher.launch(fn);
+ verify(layerService).resolveLayerByArnForAccount(arn, "222233334444", "us-east-1");
+ verify(layerService, never()).resolveLayerByArn(anyString());
+ verify(lifecycleManager).startCreated(eq("container-123"), any());
+ }
+
@Test
void launchFunction_injectsOwningAccountAsAccessKeyAndFallsBackForTheRest() throws Exception {
// The access key identifies the container's owning account to AccountResolver, so it is
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeInitializationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeInitializationTest.java
new file mode 100644
index 0000000000..f25dad628c
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeInitializationTest.java
@@ -0,0 +1,140 @@
+package io.github.hectorvent.floci.services.lambda.runtime;
+
+import io.vertx.core.Vertx;
+import io.vertx.core.json.JsonObject;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import java.net.ServerSocket;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.time.Duration;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.*;
+
+@Timeout(15)
+class RuntimeInitializationTest {
+ private Vertx vertx;
+ private RuntimeApiServer server;
+ private HttpClient client;
+ private String base;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ vertx = Vertx.vertx();
+ int port;
+ try (ServerSocket socket = new ServerSocket(0)) {
+ port = socket.getLocalPort();
+ }
+ base = "http://127.0.0.1:" + port;
+ server = new RuntimeApiServer(vertx, port);
+ server.start().get(5, TimeUnit.SECONDS);
+ client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
+ }
+
+ @AfterEach
+ void tearDown() throws Exception {
+ server.stop().get(5, TimeUnit.SECONDS);
+ client.shutdownNow();
+ vertx.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
+ }
+
+ private CompletableFuture<HttpResponse<String>> next() {
+ return client.sendAsync(HttpRequest.newBuilder(URI.create(base + "/2018-06-01/runtime/invocation/next"))
+ .GET().build(), HttpResponse.BodyHandlers.ofString());
+ }
+
+ private String register(String name) throws Exception {
+ HttpResponse<String> response = client.send(
+ HttpRequest.newBuilder(URI.create(base + "/2020-01-01/extension/register"))
+ .header("Lambda-Extension-Name", name).header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString("{\"events\":[\"INVOKE\",\"SHUTDOWN\"]}")).build(),
+ HttpResponse.BodyHandlers.ofString());
+ assertEquals(200, response.statusCode());
+ return response.headers().firstValue("Lambda-Extension-Identifier").orElseThrow();
+ }
+
+ private CompletableFuture<HttpResponse<String>> extensionNext(String id) {
+ return client.sendAsync(HttpRequest.newBuilder(URI.create(base + "/2020-01-01/extension/event/next"))
+ .header("Lambda-Extension-Identifier", id).GET().build(), HttpResponse.BodyHandlers.ofString());
+ }
+
+ @Test
+ void initializationNeedsRuntimeNextAndDoesNotProduceAnInvocation() throws Exception {
+ server.expectExtensions(0);
+ assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
+ CompletableFuture<HttpResponse<String>> pending = next();
+ server.awaitInitialization(2000);
+ assertTrue(server.isInitialized());
+ assertFalse(pending.isDone(), "No handler event was enqueued by initialization");
+ }
+
+ @Test
+ void runtimeNextBeforeExtensionDiscoveryCannotCompleteInitialization() throws Exception {
+ CompletableFuture<HttpResponse<String>> pending = next();
+ await().atMost(Duration.ofSeconds(2)).until(() -> server.waitingContextsSize() == 1);
+ assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
+ server.expectExtensions(1);
+ String extension = register("example-extension");
+ assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
+ extensionNext(extension);
+ server.awaitInitialization(2000);
+ assertFalse(pending.isDone());
+ }
+
+ @Test
+ void everyExtensionAndTheRuntimeMustFinishInit() throws Exception {
+ server.expectExtensions(2);
+ String first = register("first-extension");
+ String second = register("second-extension");
+ extensionNext(first);
+ assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
+ CompletableFuture<HttpResponse<String>> pending = next();
+ assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
+ extensionNext(second);
+ server.awaitInitialization(2000);
+ assertFalse(pending.isDone());
+ }
+
+ @Test
+ void initErrorFailsTheBarrierWithoutAnInvocation() throws Exception {
+ server.expectExtensions(0);
+ HttpResponse<String> response = client.send(
+ HttpRequest.newBuilder(URI.create(base + "/2018-06-01/runtime/init/error"))
+ .header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(
+ new JsonObject().put("errorMessage", "controlled import failure").encode())).build(),
+ HttpResponse.BodyHandlers.ofString());
+ assertEquals(202, response.statusCode());
+ assertThrows(ExecutionException.class, () -> server.awaitInitialization(100));
+ assertFalse(server.isInitialized());
+ }
+
+ @Test
+ void processExitFailsTheBarrierAndCannotBeMadeReadyByALateNext() throws Exception {
+ server.expectExtensions(0);
+ server.handleRuntimeProcessExited(1);
+ assertThrows(ExecutionException.class, () -> server.awaitInitialization(100));
+ assertEquals(204, next().get(2, TimeUnit.SECONDS).statusCode());
+ assertFalse(server.isInitialized());
+ }
+
+ @Test
+ void stopInvalidatesCompletedReadiness() throws Exception {
+ server.expectExtensions(0);
+ next();
+ server.awaitInitialization(2000);
+ server.quiesce();
+ assertFalse(server.isInitialized());
+ assertThrows(IllegalStateException.class, () -> server.awaitInitialization(100));
+ }
+}