mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(lambda): add provisioned concurrency configuration APIs (#6317)
Add the requested control-plane stage: Put/Get/Delete validation, persistent desired configuration, qualified IAM resources, and cleanup on version, alias, and function deletion. Share the function concurrency lock with reservation changes. Runtime initialization and invocation routing remain separate. Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
1 parent
27338a62b7
commit
6bc598fbfd
16 files changed
+1485
-38
No files matched your search
@@ -754,10 +754,11 @@ public class ResourceArnBuilder {
|
||||
// path: /2015-03-31/functions/name or similar
|
||||
String name = extractSegmentAfter(path, "functions");
|
||||
if (name == null) return "*";
|
||||
boolean invoke = path.endsWith("/functions/" + name + "/invocations")
|
||||
|| path.endsWith("/functions/" + name + "/response-streaming-invocations");
|
||||
boolean qualifiedTarget = path.endsWith("/functions/" + name + "/invocations")
|
||||
|| path.endsWith("/functions/" + name + "/response-streaming-invocations")
|
||||
|| path.endsWith("/functions/" + name + "/provisioned-concurrency");
|
||||
try {
|
||||
if (!invoke) {
|
||||
if (!qualifiedTarget) {
|
||||
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(name);
|
||||
boolean namedAccount = readsInTheAccountItNames(path, name, ref, ctx);
|
||||
return AwsArnUtils.Arn.of("lambda",
|
||||
|
||||
@@ -25,6 +25,8 @@ public class LambdaFunctionStore implements Resettable {
|
||||
|
||||
private final StorageBackend<String, LambdaFunction> backend;
|
||||
private final ConcurrentHashMap<String, LambdaFunction> urlIdIndex = new ConcurrentHashMap<>();
|
||||
// Retain locks across deletion and reset so a queued operation cannot race a newly created lock.
|
||||
private final ConcurrentHashMap<String, Object> concurrencyOpLocks = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public LambdaFunctionStore(StorageFactory storageFactory) {
|
||||
@@ -39,6 +41,10 @@ public class LambdaFunctionStore implements Resettable {
|
||||
loadIndex();
|
||||
}
|
||||
|
||||
Object lockForConcurrencyOp(String functionArn) {
|
||||
return concurrencyOpLocks.computeIfAbsent(functionArn, key -> new Object());
|
||||
}
|
||||
|
||||
private void loadIndex() {
|
||||
List<LambdaFunction> all = backend instanceof AccountAwareStorageBackend<LambdaFunction> aware
|
||||
? aware.scanAllAccounts()
|
||||
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.DELETE;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.PUT;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
@Path("/2019-09-30/functions/{functionName}/provisioned-concurrency")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class LambdaProvisionedConcurrencyController {
|
||||
private final ProvisionedConcurrencyPool pool;
|
||||
private final RegionResolver regions;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
@Inject
|
||||
public LambdaProvisionedConcurrencyController(ProvisionedConcurrencyPool pool,
|
||||
RegionResolver regions, ObjectMapper mapper) {
|
||||
this.pool = pool;
|
||||
this.regions = regions;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@PUT
|
||||
public Response put(@Context HttpHeaders headers, @PathParam("functionName") String name,
|
||||
@QueryParam("Qualifier") String qualifier, String body) {
|
||||
int count;
|
||||
try {
|
||||
JsonNode request = mapper.readTree(body);
|
||||
JsonNode raw = request == null ? null : request.get("ProvisionedConcurrentExecutions");
|
||||
if (raw == null || raw.isNull()) {
|
||||
throw ProvisionedConcurrencyPool.invalidCount(null);
|
||||
}
|
||||
if (raw.isTextual() || raw.isBoolean()) {
|
||||
String type = raw.isTextual() ? "STRING_VALUE" : raw.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE";
|
||||
throw new AwsException("SerializationException", type + " can not be converted to an Integer", 400);
|
||||
}
|
||||
if (!raw.isNumber() || !raw.canConvertToInt()) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
count = raw.intValue();
|
||||
if (count < 1) {
|
||||
throw ProvisionedConcurrencyPool.invalidCount(count);
|
||||
}
|
||||
} catch (AwsException failure) {
|
||||
throw failure;
|
||||
} catch (Exception failure) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"ProvisionedConcurrentExecutions must be a positive integer", 400);
|
||||
}
|
||||
return Response.status(202).entity(wire(pool.put(regions.resolveRegion(headers), name,
|
||||
qualifier, count, regions.getAccountId()))).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
public Response get(@Context HttpHeaders headers, @PathParam("functionName") String name,
|
||||
@QueryParam("Qualifier") String qualifier) {
|
||||
return Response.ok(wire(pool.get(regions.resolveRegion(headers), name, qualifier,
|
||||
regions.getAccountId()))).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
public Response delete(@Context HttpHeaders headers, @PathParam("functionName") String name,
|
||||
@QueryParam("Qualifier") String qualifier) {
|
||||
pool.delete(regions.resolveRegion(headers), name, qualifier, regions.getAccountId());
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
private ObjectNode wire(ProvisionedConcurrencyPool.Status value) {
|
||||
ObjectNode result = mapper.createObjectNode();
|
||||
result.put("RequestedProvisionedConcurrentExecutions", value.requested());
|
||||
result.put("AllocatedProvisionedConcurrentExecutions", value.allocated());
|
||||
result.put("AvailableProvisionedConcurrentExecutions", value.available());
|
||||
result.put("Status", value.status());
|
||||
result.put("LastModified", value.lastModified());
|
||||
if (value.reason() != null) {
|
||||
result.put("StatusReason", value.reason());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -190,20 +190,6 @@ public class LambdaService implements ResourceProvider {
|
||||
private final ObjectMapper objectMapper;
|
||||
private Map<String, Integer> versionCounters = new ConcurrentHashMap<>();
|
||||
private Map<String, FunctionEventInvokeConfig> eventInvokeConfigs = new ConcurrentHashMap<>();
|
||||
/**
|
||||
* Per-function locks covering PutFunctionConcurrency,
|
||||
* DeleteFunctionConcurrency, and deleteFunction itself. Serializing the
|
||||
* limiter update + persistence pair against itself for a given function
|
||||
* prevents the limiter and store from diverging on interleaved concurrent
|
||||
* requests.
|
||||
*
|
||||
* <p>Entries are intentionally never removed — see {@code deleteFunction}
|
||||
* for the race this avoids. The map therefore grows by one {@code Object}
|
||||
* per distinct function ARN the emulator has ever seen (create/delete
|
||||
* cycles with fresh names included). Acceptable footprint for a local
|
||||
* emulator workload.
|
||||
*/
|
||||
private final ConcurrentHashMap<String, Object> concurrencyOpLocks = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Object> policyMutationLocks = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Object> versionCounterLocks = new ConcurrentHashMap<>();
|
||||
|
||||
@@ -1088,6 +1074,7 @@ public class LambdaService implements ResourceProvider {
|
||||
return;
|
||||
}
|
||||
synchronized (lockForConcurrencyOp(fn.getFunctionArn())) {
|
||||
warmPool.deleteProvisionedQualifier(fn, qualifier);
|
||||
warmPool.drainEnvironment(version.get());
|
||||
functionStore.deleteVersion(region, name, qualifier);
|
||||
reclaimVersionCodeDirectory(region, fn, qualifier, version.get());
|
||||
@@ -1116,6 +1103,7 @@ public class LambdaService implements ResourceProvider {
|
||||
// object, letting a follow-up request allocate a fresh lock and run
|
||||
// in parallel — the very serialization this map exists to prevent.
|
||||
synchronized (lockForConcurrencyOp(arn)) {
|
||||
warmPool.deleteProvisionedFunction(fn);
|
||||
if (concurrencyLimiter != null) {
|
||||
concurrencyLimiter.reset(arn);
|
||||
}
|
||||
@@ -2253,7 +2241,7 @@ public class LambdaService implements ResourceProvider {
|
||||
* Locked get-increment-put: StorageBackedMap has no atomic merge, so the
|
||||
* sequence must not interleave or concurrent PublishVersion calls could issue
|
||||
* duplicate version numbers. The lock is per counter key (same pattern as
|
||||
* {@code concurrencyOpLocks}) so publishes of unrelated functions do not
|
||||
* the per-function concurrency lock) so publishes of unrelated functions do not
|
||||
* serialize on the instance monitor for the storage round-trip.
|
||||
*/
|
||||
/**
|
||||
@@ -2993,7 +2981,10 @@ public class LambdaService implements ResourceProvider {
|
||||
"Version must be a published version number, got: " + version, 400);
|
||||
}
|
||||
LambdaFunction fn = getFunction(region, functionName); // throws 404 if not found
|
||||
functionStore.deleteVersion(region, fn.getFunctionName(), version);
|
||||
synchronized (lockForConcurrencyOp(fn.getFunctionArn())) {
|
||||
warmPool.deleteProvisionedQualifier(fn, version);
|
||||
functionStore.deleteVersion(region, fn.getFunctionName(), version);
|
||||
}
|
||||
LOG.infov("Deleted version {0} of function {1}", version, fn.getFunctionName());
|
||||
}
|
||||
|
||||
@@ -3046,14 +3037,18 @@ public class LambdaService implements ResourceProvider {
|
||||
java.util.Map<String, Double> routingConfig) {
|
||||
validateAliasName(aliasName);
|
||||
validateAliasMembers(functionVersion, description);
|
||||
LambdaAlias alias = getAlias(region, functionName, aliasName);
|
||||
if (functionVersion != null) alias.setFunctionVersion(functionVersion);
|
||||
if (description != null) alias.setDescription(description);
|
||||
if (routingConfig != null) alias.setRoutingConfig(routingConfig.isEmpty() ? null : routingConfig);
|
||||
alias.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
alias.setRevisionId(UUID.randomUUID().toString());
|
||||
if (aliasStore != null) aliasStore.save(region, alias);
|
||||
return alias;
|
||||
LambdaFunction fn = getFunction(region, functionName);
|
||||
synchronized (lockForConcurrencyOp(fn.getFunctionArn())) {
|
||||
LambdaAlias alias = getAlias(region, functionName, aliasName);
|
||||
warmPool.validateProvisionedAliasUpdate(fn, aliasName, functionVersion);
|
||||
if (functionVersion != null) alias.setFunctionVersion(functionVersion);
|
||||
if (description != null) alias.setDescription(description);
|
||||
if (routingConfig != null) alias.setRoutingConfig(routingConfig.isEmpty() ? null : routingConfig);
|
||||
alias.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
alias.setRevisionId(UUID.randomUUID().toString());
|
||||
if (aliasStore != null) aliasStore.save(region, alias);
|
||||
return alias;
|
||||
}
|
||||
}
|
||||
|
||||
/** FunctionUrlQualifier in botocore: 1-128 characters, not all digits. */
|
||||
@@ -3079,8 +3074,12 @@ public class LambdaService implements ResourceProvider {
|
||||
public void deleteAlias(String region, String functionName, String aliasName) {
|
||||
validatePattern(aliasName, "name", ALIAS_NAME_PATTERN);
|
||||
String canonical = canonicalFunctionName(region, functionName);
|
||||
getAlias(region, canonical, aliasName); // verify it exists
|
||||
if (aliasStore != null) aliasStore.delete(region, canonical, aliasName);
|
||||
LambdaFunction fn = getFunction(region, canonical);
|
||||
synchronized (lockForConcurrencyOp(fn.getFunctionArn())) {
|
||||
getAlias(region, canonical, aliasName); // verify it exists
|
||||
warmPool.deleteProvisionedQualifier(fn, aliasName);
|
||||
if (aliasStore != null) aliasStore.delete(region, canonical, aliasName);
|
||||
}
|
||||
LOG.infov("Deleted alias {0} for function {1}", aliasName, canonical);
|
||||
}
|
||||
|
||||
@@ -3283,6 +3282,7 @@ public class LambdaService implements ResourceProvider {
|
||||
// concurrent Puts cannot leave the limiter and persisted state out of
|
||||
// sync, regardless of which call acquires the reservedLock first.
|
||||
synchronized (lockForConcurrencyOp(arn)) {
|
||||
warmPool.validateProvisionedReservation(fn, reservedConcurrentExecutions);
|
||||
Integer previousReserved = null;
|
||||
boolean limiterUpdated = false;
|
||||
if (concurrencyLimiter != null) {
|
||||
@@ -3359,7 +3359,7 @@ public class LambdaService implements ResourceProvider {
|
||||
|
||||
/** Package-private (not private) so tests can hold this lock to prove a critical section waits for it. */
|
||||
Object lockForConcurrencyOp(String functionArn) {
|
||||
return concurrencyOpLocks.computeIfAbsent(functionArn, k -> new Object());
|
||||
return functionStore.lockForConcurrencyOp(functionArn);
|
||||
}
|
||||
|
||||
public LambdaFunction getFunctionByUrlId(String urlId) {
|
||||
|
||||
+352
@@ -0,0 +1,352 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
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.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.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 java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Stores desired capacity. Runtime allocation is introduced by the next stage. */
|
||||
@ApplicationScoped
|
||||
public class ProvisionedConcurrencyPool implements Resettable {
|
||||
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 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<>();
|
||||
|
||||
@RegisterForReflection
|
||||
public record Configuration(String account, String region, String name, String functionArn,
|
||||
String qualifier, String version, String revision,
|
||||
int requested, String lastModified) {
|
||||
String key() {
|
||||
return functionArn + ":" + qualifier;
|
||||
}
|
||||
}
|
||||
|
||||
public record Status(int requested, int allocated, int available, String status,
|
||||
String reason, String lastModified) {}
|
||||
|
||||
@Inject
|
||||
public ProvisionedConcurrencyPool(LambdaFunctionStore functions, LambdaAliasStore aliases,
|
||||
StorageFactory storageFactory, EmulatorConfig config, Clock clock) {
|
||||
this(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);
|
||||
}
|
||||
|
||||
ProvisionedConcurrencyPool(LambdaFunctionStore functions, LambdaAliasStore aliases,
|
||||
StorageBackend<String, Configuration> storage,
|
||||
Clock clock, int maxPerFunction, int maxTotal, boolean supported) {
|
||||
this.supported = supported;
|
||||
this.functions = functions;
|
||||
this.aliases = aliases;
|
||||
this.storage = storage;
|
||||
this.clock = clock;
|
||||
this.maxPerFunction = maxPerFunction;
|
||||
this.maxTotal = maxTotal;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void start() {
|
||||
synchronized (lock) {
|
||||
List<Configuration> stored = storage instanceof AccountAwareStorageBackend<Configuration> aware
|
||||
? aware.scanAllAccounts() : storage.scan(ignored -> true);
|
||||
for (Configuration configuration : stored) {
|
||||
configurations.put(configuration.key(), configuration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Status put(String region, String name, String qualifier, int count, String account) {
|
||||
if (count < 1) {
|
||||
throw invalidCount(count);
|
||||
}
|
||||
if ("$LATEST".equals(qualifier)) {
|
||||
throw invalid("Provisioned Concurrency Configs cannot be applied to unpublished function versions.");
|
||||
}
|
||||
Configuration target = resolve(region, name, qualifier, account, count);
|
||||
synchronized (functions.lockForConcurrencyOp(target.functionArn())) {
|
||||
return put(resolve(region, name, qualifier, account, count));
|
||||
}
|
||||
}
|
||||
|
||||
private Status put(Configuration target) {
|
||||
int count = target.requested();
|
||||
if (!supported) {
|
||||
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"));
|
||||
if (fn.isHotReload() || fn.isDurable()) {
|
||||
throw invalid("Provisioned concurrency is not supported for hot-reload or durable functions");
|
||||
}
|
||||
synchronized (lock) {
|
||||
Configuration previous = configurations.get(target.key());
|
||||
long otherFunction = 0;
|
||||
long otherTotal = 0;
|
||||
boolean versionConflict = false;
|
||||
for (Configuration entry : configurations.values()) {
|
||||
if (entry == previous) {
|
||||
continue;
|
||||
}
|
||||
otherTotal += entry.requested();
|
||||
if (target.functionArn().equals(entry.functionArn())) {
|
||||
versionConflict |= target.version().equals(pointedVersion(entry));
|
||||
otherFunction += entry.requested();
|
||||
}
|
||||
}
|
||||
if (otherFunction + count > maxPerFunction
|
||||
|| (maxTotal > 0 && otherTotal + count > maxTotal)) {
|
||||
throw invalid("Requested provisioned concurrency exceeds the configured local warm-pool capacity");
|
||||
}
|
||||
LambdaFunction latest = functions.getForAccount(target.account(), target.region(), target.name()).orElseThrow(
|
||||
() -> missing("Function no longer exists"));
|
||||
Integer reserved = latest.getReservedConcurrentExecutions();
|
||||
if (reserved != null && otherFunction + count > reserved) {
|
||||
throw invalid("Provisioned concurrency cannot exceed the function's reserved concurrency");
|
||||
}
|
||||
if (versionConflict) {
|
||||
throw new AwsException("ResourceConflictException",
|
||||
target.qualifier().equals(target.version())
|
||||
? "Version is pointed by a Provisioned Concurrency alias"
|
||||
: "Alias can't be used for Provisioned Concurrency configuration "
|
||||
+ "on an already Provisioned version", 409);
|
||||
}
|
||||
if (previous != null && sameTarget(previous, target) && previous.requested() == count) {
|
||||
return status(previous);
|
||||
}
|
||||
write(target);
|
||||
configurations.put(target.key(), target);
|
||||
return status(target);
|
||||
}
|
||||
}
|
||||
|
||||
public Status get(String region, String name, String qualifier, String account) {
|
||||
Target target = resolveTarget(region, name, qualifier, account);
|
||||
synchronized (lock) {
|
||||
Configuration configuration = configurations.get(target.key());
|
||||
if (configuration == null) {
|
||||
throw new AwsException("ProvisionedConcurrencyConfigNotFoundException",
|
||||
"No Provisioned Concurrency Config found for this function", 404);
|
||||
}
|
||||
return status(configuration);
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(String region, String name, String qualifier, String account) {
|
||||
Target target = resolveTarget(region, name, qualifier, account);
|
||||
synchronized (functions.lockForConcurrencyOp(target.functionArn())) {
|
||||
resolveTarget(region, name, qualifier, account);
|
||||
deleteMatching(target.functionArn(), qualifier);
|
||||
}
|
||||
}
|
||||
|
||||
void deleteFunction(LambdaFunction fn) {
|
||||
deleteMatching(baseArn(fn), null);
|
||||
}
|
||||
|
||||
void deleteQualifier(LambdaFunction fn, String qualifier) {
|
||||
deleteMatching(baseArn(fn), qualifier);
|
||||
}
|
||||
|
||||
void validateReservation(LambdaFunction fn, Integer reserved) {
|
||||
if (reserved == null) {
|
||||
return;
|
||||
}
|
||||
synchronized (lock) {
|
||||
long requested = configurations.values().stream()
|
||||
.filter(entry -> entry.functionArn().equals(baseArn(fn)))
|
||||
.mapToLong(entry -> entry.requested()).sum();
|
||||
if (requested > reserved) {
|
||||
throw invalid("Reserved concurrency cannot be lower than provisioned concurrency");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteMatching(String functionArn, String qualifier) {
|
||||
synchronized (lock) {
|
||||
for (Configuration value : new ArrayList<>(configurations.values())) {
|
||||
if (value.functionArn().equals(functionArn)
|
||||
&& (qualifier == null || qualifier.equals(value.qualifier()))) {
|
||||
erase(value);
|
||||
configurations.remove(value.key());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Status status(Configuration configuration) {
|
||||
return new Status(configuration.requested(), 0, 0, "IN_PROGRESS", null, configuration.lastModified());
|
||||
}
|
||||
|
||||
private String pointedVersion(Configuration configuration) {
|
||||
if (configuration.qualifier().matches("[0-9]+")) {
|
||||
return configuration.version();
|
||||
}
|
||||
return aliases.getForAccount(configuration.account(), configuration.region(),
|
||||
configuration.name(), configuration.qualifier())
|
||||
.map(LambdaAlias::getFunctionVersion).orElse(null);
|
||||
}
|
||||
|
||||
void validateAliasUpdate(LambdaFunction fn, String qualifier, String version) {
|
||||
synchronized (lock) {
|
||||
String functionArn = baseArn(fn);
|
||||
if (!configurations.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)))) {
|
||||
throw new AwsException("ResourceConflictException",
|
||||
"Alias can't be used for Provisioned Concurrency configuration on an already Provisioned version", 409);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private record Target(String account, String region, String name, String functionArn,
|
||||
String qualifier, LambdaAlias alias) {
|
||||
String key() {
|
||||
return functionArn + ":" + qualifier;
|
||||
}
|
||||
|
||||
String missingMessage() {
|
||||
return (alias == null ? "Function not found: " : "Cannot find alias arn: ") + key();
|
||||
}
|
||||
}
|
||||
|
||||
private Configuration resolve(String region, String name, String qualifier, String account, int count) {
|
||||
Target target = resolveTarget(region, name, qualifier, account);
|
||||
LambdaAlias alias = target.alias();
|
||||
if (alias != null && alias.getRoutingConfig() != null && !alias.getRoutingConfig().isEmpty()) {
|
||||
throw invalid("Weighted aliases are not supported for provisioned concurrency");
|
||||
}
|
||||
String version = alias == null ? qualifier : alias.getFunctionVersion();
|
||||
if (version == null || !version.matches("[0-9]+")) {
|
||||
throw invalid("Provisioned concurrency requires an immutable published version");
|
||||
}
|
||||
LambdaFunction fn = functions.getForAccount(target.account(), region, target.name(), version)
|
||||
.orElseThrow(() -> missing(target.missingMessage()));
|
||||
return new Configuration(target.account(), region, target.name(), target.functionArn(), qualifier,
|
||||
version, fn.getRevisionId(), count, LAST_MODIFIED.format(Instant.ofEpochMilli(clock.millis())));
|
||||
}
|
||||
|
||||
private Target resolveTarget(String region, String name, String qualifier, String account) {
|
||||
if (qualifier == null || qualifier.isBlank() || qualifier.length() > 128) {
|
||||
throw invalid("Qualifier is required and must contain 1 to 128 characters");
|
||||
}
|
||||
if ("$LATEST".equals(qualifier)) {
|
||||
throw invalid("The function resource provided must be an alias or a published version.");
|
||||
}
|
||||
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolveWithQualifier(name, qualifier);
|
||||
if (ref.region() != null && !region.equals(ref.region())) {
|
||||
throw invalid("Function ARN region must match the request region");
|
||||
}
|
||||
account = ref.account() != null ? ref.account() : account;
|
||||
boolean publishedVersion = qualifier.matches("[0-9]+");
|
||||
String qualifiedArn = AwsArnUtils.Arn.of("lambda", region, account,
|
||||
"function:" + ref.name() + ":" + qualifier).toString();
|
||||
String notFoundMessage = (publishedVersion ? "Function not found: " : "Cannot find alias arn: ")
|
||||
+ qualifiedArn;
|
||||
LambdaFunction latest = functions.getForAccount(account, region, ref.name())
|
||||
.orElseThrow(() -> missing(notFoundMessage));
|
||||
LambdaAlias alias = null;
|
||||
if (publishedVersion) {
|
||||
functions.getForAccount(account, region, ref.name(), qualifier)
|
||||
.orElseThrow(() -> missing(notFoundMessage));
|
||||
} else {
|
||||
alias = aliases.getForAccount(account, region, ref.name(), qualifier)
|
||||
.orElseThrow(() -> missing(notFoundMessage));
|
||||
}
|
||||
return new Target(account, region, ref.name(), baseArn(latest), qualifier, alias);
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
private static String baseArn(LambdaFunction fn) {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(fn.getFunctionArn());
|
||||
return new AwsArnUtils.Arn(arn.partition(), "lambda", arn.region(), arn.accountId(),
|
||||
"function:" + fn.getFunctionName()).toString();
|
||||
}
|
||||
|
||||
private void write(Configuration value) {
|
||||
if (storage instanceof AccountAwareStorageBackend<Configuration> aware) {
|
||||
aware.putForAccount(value.account(), value.key(), value);
|
||||
} else {
|
||||
storage.put(value.key(), value);
|
||||
}
|
||||
}
|
||||
|
||||
private void erase(Configuration value) {
|
||||
if (storage instanceof AccountAwareStorageBackend<Configuration> aware) {
|
||||
aware.deleteForAccount(value.account(), value.key());
|
||||
} else {
|
||||
storage.delete(value.key());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
synchronized (lock) {
|
||||
storage.clear();
|
||||
configurations.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("InvalidParameterValueException", message, 400);
|
||||
}
|
||||
|
||||
static AwsException invalidCount(Integer count) {
|
||||
String value = count == null ? "null" : "'" + count + "'";
|
||||
String constraint = count == null ? "Member must not be null"
|
||||
: "Member must have value greater than or equal to 1";
|
||||
return new AwsException("ValidationException", "1 validation error detected: Value "
|
||||
+ value + " at 'provisionedConcurrentExecutions' failed to satisfy constraint: "
|
||||
+ constraint, 400);
|
||||
}
|
||||
|
||||
private static AwsException missing(String message) {
|
||||
return new AwsException("ResourceNotFoundException", message, 404);
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,7 @@ public class WarmPool implements ContainerTeardown, Resettable {
|
||||
private static final int DEFAULT_MAX_POOL_SIZE = Math.max(4, Runtime.getRuntime().availableProcessors());
|
||||
|
||||
private final LambdaRuntimeLauncher lambdaRuntimeLauncher;
|
||||
private final ProvisionedConcurrencyPool provisioned;
|
||||
private final EmulatorConfig config;
|
||||
private final Clock clock;
|
||||
private final int maxPoolSizePerFunction;
|
||||
@@ -92,7 +93,9 @@ public class WarmPool implements ContainerTeardown, Resettable {
|
||||
}
|
||||
|
||||
@Inject
|
||||
public WarmPool(LambdaRuntimeLauncher lambdaRuntimeLauncher, EmulatorConfig config, Clock clock) {
|
||||
public WarmPool(LambdaRuntimeLauncher lambdaRuntimeLauncher, EmulatorConfig config, Clock clock,
|
||||
ProvisionedConcurrencyPool provisioned) {
|
||||
this.provisioned = provisioned;
|
||||
this.lambdaRuntimeLauncher = lambdaRuntimeLauncher;
|
||||
this.config = config;
|
||||
this.clock = clock;
|
||||
@@ -101,9 +104,14 @@ public class WarmPool implements ContainerTeardown, Resettable {
|
||||
this.drainTimeoutNanos = TimeUnit.SECONDS.toNanos(resolveDrainTimeout(config));
|
||||
}
|
||||
|
||||
public WarmPool(LambdaRuntimeLauncher launcher, EmulatorConfig config, Clock clock) {
|
||||
this(launcher, config, clock, null);
|
||||
}
|
||||
|
||||
/** Package-private constructor for testing (empty pool, no containers to drain). */
|
||||
WarmPool() {
|
||||
this.lambdaRuntimeLauncher = null;
|
||||
this.provisioned = null;
|
||||
this.config = null;
|
||||
this.clock = Clock.systemUTC();
|
||||
this.maxPoolSizePerFunction = DEFAULT_MAX_POOL_SIZE;
|
||||
@@ -447,6 +455,30 @@ public class WarmPool implements ContainerTeardown, Resettable {
|
||||
stopQuietly(handle);
|
||||
}
|
||||
|
||||
void deleteProvisionedFunction(LambdaFunction fn) {
|
||||
if (provisioned != null) {
|
||||
provisioned.deleteFunction(fn);
|
||||
}
|
||||
}
|
||||
|
||||
void deleteProvisionedQualifier(LambdaFunction fn, String qualifier) {
|
||||
if (provisioned != null) {
|
||||
provisioned.deleteQualifier(fn, qualifier);
|
||||
}
|
||||
}
|
||||
|
||||
void validateProvisionedAliasUpdate(LambdaFunction fn, String qualifier, String version) {
|
||||
if (provisioned != null) {
|
||||
provisioned.validateAliasUpdate(fn, qualifier, version);
|
||||
}
|
||||
}
|
||||
|
||||
void validateProvisionedReservation(LambdaFunction fn, Integer reserved) {
|
||||
if (provisioned != null) {
|
||||
provisioned.validateReservation(fn, reserved);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops and removes warm containers for one immutable execution environment, such as
|
||||
* {@code $LATEST}. Published versions keep their independently keyed warm containers.
|
||||
|
||||
Reference in new issue
Block a user