mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
@@ -36,6 +36,27 @@ class IamActionRegistryTest {
|
||||
|
||||
private final IamActionRegistry registry = new IamActionRegistry();
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"PUT,PutProvisionedConcurrencyConfig", "GET,GetProvisionedConcurrencyConfig",
|
||||
"DELETE,DeleteProvisionedConcurrencyConfig"})
|
||||
void provisionedConcurrencyRoutesResolveTheirActions(String method, String operation) {
|
||||
ContainerRequestContext ctx = mockCtx(method, "/2019-09-30/functions/example/provisioned-concurrency",
|
||||
new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}");
|
||||
assertEquals("lambda:" + operation, registry.resolveRoute("lambda", ctx));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"ALL,ListProvisionedConcurrencyConfigs", "all,GetProvisionedConcurrencyConfig",
|
||||
"OTHER,GetProvisionedConcurrencyConfig"})
|
||||
void provisionedConcurrencyListMarkerSelectsItsOwnAction(String marker, String operation) {
|
||||
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.add("List", marker);
|
||||
query.add("Qualifier", "live");
|
||||
ContainerRequestContext ctx = mockCtx("GET", "/2019-09-30/functions/example/provisioned-concurrency",
|
||||
query, null, "");
|
||||
assertEquals("lambda:" + operation, registry.resolveRoute("lambda", ctx));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"groups,CreateGroup", "get-group,GetGroup", "delete-group,DeleteGroup",
|
||||
"group-resources,GroupResources", "list-group-resources,ListGroupResources"})
|
||||
|
||||
@@ -1180,6 +1180,18 @@ class ResourceArnBuilderTest {
|
||||
builder.build("lambda", ctx, "us-east-1", "000000000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionedConcurrencyKeepsTheOwnerAndQualifierItConfigures() {
|
||||
when(uriInfo.getPath()).thenReturn(
|
||||
"/2019-09-30/functions/arn:aws:lambda:us-east-1:111122223333:function:example/provisioned-concurrency");
|
||||
queryParams.putSingle("Qualifier", "live");
|
||||
assertEquals("arn:aws:lambda:us-east-1:111122223333:function:example:live",
|
||||
builder.build("lambda", ctx, "us-east-1", "000000000000"));
|
||||
when(uriInfo.getPath()).thenReturn("/2019-09-30/functions/example/provisioned-concurrency");
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:example:live",
|
||||
builder.build("lambda", ctx, "us-east-1", "000000000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lambdaWebRoutesResolveTheFunctionRevisionOrEndpointTheyActOn() {
|
||||
String fn = "arn:aws:lambda:us-east-1:000000000000:web-function/app";
|
||||
|
||||
+60
@@ -238,6 +238,66 @@ class LambdaCrossAccountInvokeIntegrationTest {
|
||||
.then().statusCode(200).body("Configuration.FunctionArn", startsWith(foreignArn));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unpublishedCapacityValidationPrecedesMissingFunctionLookupAfterIamAuthorization() {
|
||||
String name = "absent-capacity-" + suffix();
|
||||
String user = createUser(OWNER, "capacity-admin-" + suffix(), """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"lambda:*","Resource":"*"}]}""");
|
||||
String path = "/2019-09-30/functions/{name}/provisioned-concurrency";
|
||||
lambda(user).queryParam("Qualifier", "$LATEST").body("{\"ProvisionedConcurrentExecutions\":1}")
|
||||
.put(path, name).then().statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterValueException"))
|
||||
.body("message", equalTo(
|
||||
"Provisioned Concurrency Configs cannot be applied to unpublished function versions."));
|
||||
String message = "The function resource provided must be an alias or a published version.";
|
||||
lambda(user).queryParam("Qualifier", "$LATEST").get(path, name).then().statusCode(400)
|
||||
.body("message", equalTo(message));
|
||||
lambda(user).queryParam("Qualifier", "$LATEST").delete(path, name).then().statusCode(400)
|
||||
.body("message", equalTo(message));
|
||||
lambda(user).queryParam("Qualifier", "1").get(path, name).then().statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
|
||||
String denied = createUser(OWNER, "capacity-denied-" + suffix(), INVOKE_ANYTHING);
|
||||
lambda(denied).queryParam("Qualifier", "$LATEST").get(path, name).then().statusCode(403)
|
||||
.body("__type", equalTo("AccessDeniedException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionedConcurrencyRequiresTheOwnersQualifiedGrant() {
|
||||
String name = "capacity-" + suffix();
|
||||
String arn = createFunction(OWNER, name);
|
||||
publishVersionAndAlias(OWNER, name, "live");
|
||||
String user = createUser(CALLER, "capacity-reader-" + suffix(), """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"lambda:*","Resource":"*"}]}""");
|
||||
String path = "/2019-09-30/functions/{name}/provisioned-concurrency";
|
||||
lambda(user).queryParam("Qualifier", "1").get(path, arn).then().statusCode(403);
|
||||
addPermission(OWNER, arn, "1", Map.of("Principal", CALLER,
|
||||
"Action", "lambda:GetProvisionedConcurrencyConfig"));
|
||||
lambda(user).queryParam("Qualifier", "1").get(path, arn).then().statusCode(404)
|
||||
.body("__type", equalTo("ProvisionedConcurrencyConfigNotFoundException"));
|
||||
lambda(user).queryParam("Qualifier", "live").get(path, arn).then().statusCode(403);
|
||||
lambda(user).queryParam("Qualifier", "1").delete(path, arn).then().statusCode(403);
|
||||
lambda(user).queryParam("Qualifier", "1").body("{\"ProvisionedConcurrentExecutions\":1}")
|
||||
.put(path, arn).then().statusCode(403);
|
||||
lambda(OWNER).queryParam("Qualifier", "1").get(path, name).then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionedConcurrencyGrantDoesNotReplaceTheCallersIdentityPolicy() {
|
||||
String name = "capacity-deny-" + suffix();
|
||||
String arn = createFunction(OWNER, name);
|
||||
publishVersionAndAlias(OWNER, name, "live");
|
||||
addPermission(OWNER, arn, "1", Map.of("Principal", CALLER,
|
||||
"Action", "lambda:GetProvisionedConcurrencyConfig"));
|
||||
String user = createUser(CALLER, "capacity-denied-" + suffix(), """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"lambda:InvokeFunction","Resource":"*"}]}""");
|
||||
lambda(user).queryParam("Qualifier", "1")
|
||||
.get("/2019-09-30/functions/{name}/provisioned-concurrency", arn).then().statusCode(403);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rotateSecretIsRefusedForAnotherAccountsFunctionThatGrantsNothing() {
|
||||
String name = "rotator-" + suffix();
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaAlias;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
|
||||
final class LambdaFunctionTestFixtures {
|
||||
|
||||
private LambdaFunctionTestFixtures() {
|
||||
}
|
||||
|
||||
static LambdaFunction function(String account, String region, String name, String version) {
|
||||
LambdaFunction function = new LambdaFunction();
|
||||
function.setFunctionName(name);
|
||||
function.setAccountId(account);
|
||||
String arn = AwsArnUtils.Arn.of("lambda", region, account, "function:" + name).toString();
|
||||
function.setFunctionArn(arn + ("$LATEST".equals(version) ? "" : ":" + version));
|
||||
function.setVersion(version);
|
||||
function.setRevisionId(account + region + version);
|
||||
return function;
|
||||
}
|
||||
|
||||
static LambdaAlias alias(String account, String region, String function, String name, String version) {
|
||||
LambdaAlias alias = new LambdaAlias();
|
||||
alias.setName(name);
|
||||
alias.setFunctionName(function);
|
||||
alias.setFunctionVersion(version);
|
||||
alias.setAliasArn(AwsArnUtils.Arn.of("lambda", region, account, "function:" + function + ":" + name).toString());
|
||||
return alias;
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@QuarkusTest
|
||||
class LambdaProvisionedConcurrencyIntegrationTest {
|
||||
private static final String PATH = "/2019-09-30/functions/example/provisioned-concurrency";
|
||||
@InjectMock
|
||||
ProvisionedConcurrencyPool pool;
|
||||
|
||||
@Test
|
||||
void putUsesTheDatedAwsRouteAndReturnsAcceptedAllocation() {
|
||||
when(pool.put(anyString(), eq("example"), eq("live"), eq(1), anyString()))
|
||||
.thenReturn(new ProvisionedConcurrencyPool.Status(1, 0, 0, "IN_PROGRESS", null,
|
||||
"2026-01-01T00:00:00Z"));
|
||||
given().contentType("application/json").queryParam("Qualifier", "live")
|
||||
.body("{\"ProvisionedConcurrentExecutions\":1}").put(PATH).then().statusCode(202)
|
||||
.body("Status", equalTo("IN_PROGRESS"))
|
||||
.body("RequestedProvisionedConcurrentExecutions", equalTo(1))
|
||||
.body("AllocatedProvisionedConcurrentExecutions", equalTo(0))
|
||||
.body("AvailableProvisionedConcurrentExecutions", equalTo(0))
|
||||
.body("LastModified", equalTo("2026-01-01T00:00:00Z"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getReportsAllocatedCapacityAndDeleteIsEmpty204() {
|
||||
when(pool.get(anyString(), eq("example"), eq("live"), anyString()))
|
||||
.thenReturn(new ProvisionedConcurrencyPool.Status(2, 2, 1, "READY", null,
|
||||
"2026-01-01T00:00:00Z"));
|
||||
given().queryParam("Qualifier", "live").get(PATH).then().statusCode(200)
|
||||
.body("Status", equalTo("READY"))
|
||||
.body("RequestedProvisionedConcurrentExecutions", equalTo(2))
|
||||
.body("AllocatedProvisionedConcurrentExecutions", equalTo(2))
|
||||
.body("AvailableProvisionedConcurrentExecutions", equalTo(1));
|
||||
given().queryParam("Qualifier", "live").delete(PATH).then().statusCode(204).body(equalTo(""));
|
||||
verify(pool).delete(anyString(), eq("example"), eq("live"), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingConfigurationUsesTheModeledAwsException() {
|
||||
when(pool.get(anyString(), eq("example"), eq("live"), anyString()))
|
||||
.thenThrow(new AwsException("ProvisionedConcurrencyConfigNotFoundException", "absent", 404));
|
||||
given().queryParam("Qualifier", "live").get(PATH).then().statusCode(404)
|
||||
.body("__type", equalTo("ProvisionedConcurrencyConfigNotFoundException"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"{}", "null", "[]", "{\"ProvisionedConcurrentExecutions\":true}",
|
||||
"{\"ProvisionedConcurrentExecutions\":\"1\"}",
|
||||
"{\"ProvisionedConcurrentExecutions\":0}", "{\"ProvisionedConcurrentExecutions\":-1}",
|
||||
"{\"ProvisionedConcurrentExecutions\":2147483648}"})
|
||||
void invalidCountsNeverReachTheAllocator(String body) {
|
||||
given().contentType("application/json").queryParam("Qualifier", "live").body(body)
|
||||
.put(PATH).then().statusCode(400);
|
||||
verify(pool, never()).put(any(), any(), any(), anyInt(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decimalCountUsesAwsIntegerCoercion() {
|
||||
when(pool.put(anyString(), eq("example"), eq("live"), eq(1), anyString()))
|
||||
.thenReturn(new ProvisionedConcurrencyPool.Status(1, 0, 0, "IN_PROGRESS", null,
|
||||
"2026-10-20T20:11:30+0000"));
|
||||
given().contentType("application/json").queryParam("Qualifier", "live")
|
||||
.body("{\"ProvisionedConcurrentExecutions\":1.5}").put(PATH).then().statusCode(202)
|
||||
.body("RequestedProvisionedConcurrentExecutions", equalTo(1))
|
||||
.body("LastModified", equalTo("2026-10-20T20:11:30+0000"));
|
||||
verify(pool).put(anyString(), eq("example"), eq("live"), eq(1), anyString());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"{}", "{\"ProvisionedConcurrentExecutions\":null}"})
|
||||
void omittedAndNullCountsUseAwsValidation(String body) {
|
||||
given().contentType("application/json").queryParam("Qualifier", "live").body(body)
|
||||
.put(PATH).then().statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", equalTo("1 validation error detected: Value null at 'provisionedConcurrentExecutions' "
|
||||
+ "failed to satisfy constraint: Member must not be null"));
|
||||
verify(pool, never()).put(any(), any(), any(), anyInt(), any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {0, -1})
|
||||
void nonpositiveCountsUseAwsValidation(int count) {
|
||||
given().contentType("application/json").queryParam("Qualifier", "live")
|
||||
.body("{\"ProvisionedConcurrentExecutions\":" + count + "}").put(PATH).then().statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
verify(pool, never()).put(any(), any(), any(), anyInt(), any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"true", "\"1\""})
|
||||
void incompatibleCountTypesUseAwsSerializationError(String value) {
|
||||
given().contentType("application/json").queryParam("Qualifier", "live")
|
||||
.body("{\"ProvisionedConcurrentExecutions\":" + value + "}").put(PATH).then().statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"));
|
||||
verify(pool, never()).put(any(), any(), any(), anyInt(), any());
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaAlias;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
@QuarkusTest
|
||||
class LambdaProvisionedConcurrencyNotFoundIntegrationTest {
|
||||
private static final String NAME = "pc-missing-target-control";
|
||||
@Inject
|
||||
LambdaFunctionStore functions;
|
||||
@Inject
|
||||
LambdaAliasStore aliases;
|
||||
@Inject
|
||||
RegionResolver resolver;
|
||||
|
||||
@BeforeEach
|
||||
void createTarget() {
|
||||
for (String version : List.of("$LATEST", "1")) {
|
||||
LambdaFunction function = LambdaFunctionTestFixtures.function(
|
||||
resolver.getAccountId(), resolver.getRegion(), NAME, version);
|
||||
function.setRevisionId("missing-target-control-" + version);
|
||||
functions.save(resolver.getRegion(), function);
|
||||
}
|
||||
LambdaAlias alias = LambdaFunctionTestFixtures.alias(
|
||||
resolver.getAccountId(), resolver.getRegion(), NAME, "live", "1");
|
||||
aliases.save(resolver.getRegion(), alias);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void deleteTarget() {
|
||||
aliases.delete(resolver.getRegion(), NAME, "live");
|
||||
functions.delete(resolver.getRegion(), NAME);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"pc-missing-target-control, missing, Cannot find alias arn: ",
|
||||
"pc-missing-target-control, 99, Function not found: ",
|
||||
"pc-absent-function-control, missing, Cannot find alias arn: ",
|
||||
"pc-absent-function-control, 99, Function not found: "
|
||||
})
|
||||
void everyOperationReturnsTheQualifiedTarget(String name, String qualifier, String prefix) {
|
||||
String message = prefix + " " + functionArn(name) + ":" + qualifier;
|
||||
for (String reference : List.of(name, functionArn(name))) {
|
||||
String path = "/2019-09-30/functions/{function}/provisioned-concurrency";
|
||||
for (String method : List.of("GET", "PUT", "DELETE")) {
|
||||
given().contentType("application/json").queryParam("Qualifier", qualifier)
|
||||
.pathParam("function", reference).body("{\"ProvisionedConcurrentExecutions\":1}")
|
||||
.request(method, path).then().statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"))
|
||||
.body("message", equalTo(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingAliasAndVersionRetainTheirConfigurationBehavior() {
|
||||
for (String qualifier : List.of("live", "1")) {
|
||||
String path = "/2019-09-30/functions/" + NAME + "/provisioned-concurrency";
|
||||
given().queryParam("Qualifier", qualifier).get(path).then().statusCode(404)
|
||||
.body("__type", equalTo("ProvisionedConcurrencyConfigNotFoundException"))
|
||||
.body("message", equalTo("No Provisioned Concurrency Config found for this function"));
|
||||
given().queryParam("Qualifier", qualifier).delete(path).then().statusCode(204).body(equalTo(""));
|
||||
}
|
||||
}
|
||||
|
||||
private String functionArn(String name) {
|
||||
return resolver.buildArn("lambda", resolver.getRegion(), "function:" + name);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaAlias;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFileSystemConfig;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaUrlConfig;
|
||||
@@ -19,6 +20,7 @@ import io.github.hectorvent.floci.services.s3.model.S3ObjectUpdatedEvent;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
@@ -1641,6 +1643,49 @@ class LambdaServiceTest {
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"false,false", "false,true", "true,false", "true,true"})
|
||||
void deletingQualifierWaitsForProvisionedConcurrencyLock(boolean alias, boolean qualifiedName) throws Exception {
|
||||
String name = "qualifier-deletion-lock";
|
||||
LambdaFunction latest = service.createFunction(REGION, baseRequest(name));
|
||||
LambdaFunction version = service.publishVersion(REGION, name, null);
|
||||
if (alias) {
|
||||
service.createAlias(REGION, name, "live", version.getVersion(), null, null);
|
||||
}
|
||||
String reference = qualifiedName ? latest.getFunctionArn() + ":" + version.getVersion() : name;
|
||||
AtomicReference<Thread> requester = new AtomicReference<>();
|
||||
try (ExecutorService tasks = Executors.newSingleThreadExecutor()) {
|
||||
Future<?> deletion;
|
||||
synchronized (service.lockForConcurrencyOp(latest.getFunctionArn())) {
|
||||
deletion = tasks.submit(() -> {
|
||||
requester.set(Thread.currentThread());
|
||||
if (alias) {
|
||||
service.deleteAlias(REGION, reference, "live");
|
||||
} else {
|
||||
service.deleteVersion(REGION, reference, version.getVersion());
|
||||
}
|
||||
});
|
||||
awaitBlockedOrDone(requester, deletion);
|
||||
assertFalse(deletion.isDone());
|
||||
if (alias) {
|
||||
assertEquals(version.getVersion(), service.getAlias(REGION, name, "live").getFunctionVersion());
|
||||
} else {
|
||||
assertEquals(version.getVersion(), service.getFunction(REGION, name, version.getVersion()).getVersion());
|
||||
}
|
||||
}
|
||||
deletion.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
AwsException missing = assertThrows(AwsException.class, () -> {
|
||||
if (alias) {
|
||||
service.getAlias(REGION, name, "live");
|
||||
} else {
|
||||
service.getFunction(REGION, name, version.getVersion());
|
||||
}
|
||||
});
|
||||
assertEquals("ResourceNotFoundException", missing.getErrorCode());
|
||||
assertEquals("$LATEST", service.getFunction(REGION, name).getVersion());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createFunctionUrlConfigRejectsUnknownAuthType() {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
@@ -2849,6 +2894,28 @@ class LambdaServiceTest {
|
||||
+ "Member must satisfy regular expression pattern: (\\$LATEST(\\.PUBLISHED)?|[0-9]+)", error.getMessage());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"$LATEST", "2"})
|
||||
void updateAliasValidatesProvisionedCapacityBeforeMutatingItsStoredFields(String targetVersion) {
|
||||
WarmPool warmPool = mock(WarmPool.class);
|
||||
LambdaService guarded = s3BackedService(null, warmPool, new ZipExtractor());
|
||||
LambdaFunction fn = guarded.createFunction(REGION, baseRequest("alias-capacity-fn"));
|
||||
LambdaAlias alias = guarded.createAlias(REGION, fn.getFunctionName(), "live", "1", "original", null);
|
||||
AwsException failure = new AwsException("InvalidParameterValueException",
|
||||
"Provisioned Concurrency Configs cannot be applied to unpublished function versions.", 400);
|
||||
doAnswer(invocation -> {
|
||||
assertTrue(Thread.holdsLock(guarded.lockForConcurrencyOp(fn.getFunctionArn())));
|
||||
throw failure;
|
||||
}).when(warmPool).validateProvisionedAliasUpdate(fn, "live", targetVersion);
|
||||
|
||||
assertSame(failure, assertThrows(AwsException.class, () -> guarded.updateAlias(REGION,
|
||||
fn.getFunctionName(), "live", targetVersion, "changed", Map.of("2", 0.1))));
|
||||
assertSame(alias, guarded.getAlias(REGION, fn.getFunctionName(), "live"));
|
||||
assertEquals("1", alias.getFunctionVersion());
|
||||
assertEquals("original", alias.getDescription());
|
||||
assertTrue(alias.getRoutingConfig() == null || alias.getRoutingConfig().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateAlias_descriptionLongerThan256_isRejectedAndLeavesTheAliasUnchanged() {
|
||||
// Catches: UpdateAlias accepting (or half-applying) a Description over the model's 256-character maximum
|
||||
|
||||
+381
@@ -0,0 +1,381 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
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.model.LambdaAlias;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class ProvisionedConcurrencyPoolTest {
|
||||
@TempDir
|
||||
Path storagePath;
|
||||
|
||||
private static final String ACCOUNT = "111111111111";
|
||||
private static final String REGION = "us-east-1";
|
||||
private final AccountAwareStorageBackend<LambdaFunction> functionStorage =
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
private final AccountAwareStorageBackend<LambdaAlias> aliasStorage =
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
private final AccountAwareStorageBackend<ProvisionedConcurrencyPool.Configuration> storage =
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
private final LambdaFunctionStore functions = new LambdaFunctionStore(functionStorage);
|
||||
private final LambdaAliasStore aliases = new LambdaAliasStore(aliasStorage);
|
||||
private ProvisionedConcurrencyPool pool;
|
||||
private LambdaFunction version;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
version = function(ACCOUNT, REGION, "1");
|
||||
function(ACCOUNT, REGION, "$LATEST");
|
||||
alias(ACCOUNT, REGION, "live", "1", Map.of());
|
||||
pool = newPool();
|
||||
}
|
||||
|
||||
private ProvisionedConcurrencyPool newPool() {
|
||||
return new ProvisionedConcurrencyPool(functions, aliases, storage, Clock.systemUTC(), 4, 8);
|
||||
}
|
||||
|
||||
private LambdaFunction function(String account, String region, String number) {
|
||||
LambdaFunction fn = LambdaFunctionTestFixtures.function(account, region, "example", number);
|
||||
fn.setTimeout(3);
|
||||
functions.saveForAccount(account, region, fn);
|
||||
return fn;
|
||||
}
|
||||
|
||||
private void alias(String account, String region, String name, String number, Map<String, Double> weights) {
|
||||
LambdaAlias alias = LambdaFunctionTestFixtures.alias(account, region, "example", name, number);
|
||||
alias.setRoutingConfig(weights);
|
||||
aliasStorage.putForAccount(account, "alias::" + region + "::example::" + name, alias);
|
||||
}
|
||||
|
||||
private ProvisionedConcurrencyPool.Status put(int count) {
|
||||
return pool.put(REGION, "example", "live", count, ACCOUNT);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"example", "absent"})
|
||||
void unpublishedVersionErrorsDependOnTheOperation(String name) {
|
||||
AwsException put = assertThrows(AwsException.class,
|
||||
() -> pool.put(REGION, name, "$LATEST", 1, ACCOUNT));
|
||||
assertEquals("InvalidParameterValueException", put.getErrorCode());
|
||||
assertEquals("Provisioned Concurrency Configs cannot be applied to unpublished function versions.",
|
||||
put.getMessage());
|
||||
for (Runnable operation : List.<Runnable>of(
|
||||
() -> pool.get(REGION, name, "$LATEST", ACCOUNT),
|
||||
() -> pool.delete(REGION, name, "$LATEST", ACCOUNT))) {
|
||||
AwsException error = assertThrows(AwsException.class, operation::run);
|
||||
assertEquals("InvalidParameterValueException", error.getErrorCode());
|
||||
assertEquals("The function resource provided must be an alias or a published version.",
|
||||
error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {0, -1})
|
||||
void invalidCountUsesAwsValidationBeforeAllocating(int count) {
|
||||
AwsException error = assertThrows(AwsException.class, () -> put(count));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals("1 validation error detected: Value '" + count
|
||||
+ "' at 'provisionedConcurrentExecutions' failed to satisfy constraint: "
|
||||
+ "Member must have value greater than or equal to 1", error.getMessage());
|
||||
assertTrue(storage.scanAllAccounts().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingConfigurationUsesAwsMessageAndDeleteIsIdempotent() {
|
||||
AwsException error = assertThrows(AwsException.class, this::get);
|
||||
assertEquals("ProvisionedConcurrencyConfigNotFoundException", error.getErrorCode());
|
||||
assertEquals("No Provisioned Concurrency Config found for this function", error.getMessage());
|
||||
assertDoesNotThrow(() -> pool.delete(REGION, "example", "live", ACCOUNT));
|
||||
assertTrue(storage.scanAllAccounts().isEmpty());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"example, missing, Cannot find alias arn: arn:aws:lambda:us-east-1:111111111111:function:example:missing",
|
||||
"example, 99, Function not found: arn:aws:lambda:us-east-1:111111111111:function:example:99",
|
||||
"absent, missing, Cannot find alias arn: arn:aws:lambda:us-east-1:111111111111:function:absent:missing",
|
||||
"absent, 99, Function not found: arn:aws:lambda:us-east-1:111111111111:function:absent:99"
|
||||
})
|
||||
void missingTargetsUseTheQualifiedAwsMessageForEveryOperation(String name, String qualifier, String message) {
|
||||
for (String reference : List.of(name, ACCOUNT + ":function:" + name,
|
||||
"arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:" + name,
|
||||
"arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:" + name + ":" + qualifier)) {
|
||||
for (Runnable operation : List.<Runnable>of(
|
||||
() -> pool.get(REGION, reference, qualifier, ACCOUNT),
|
||||
() -> pool.put(REGION, reference, qualifier, 1, ACCOUNT),
|
||||
() -> pool.delete(REGION, reference, qualifier, ACCOUNT))) {
|
||||
AwsException error = assertThrows(AwsException.class, operation::run);
|
||||
assertEquals("ResourceNotFoundException", error.getErrorCode());
|
||||
assertEquals(404, error.getHttpStatus());
|
||||
assertEquals(message, error.getMessage());
|
||||
}
|
||||
}
|
||||
assertTrue(storage.scanAllAccounts().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingTargetMessageUsesTheNamedAccountAndRegionalPartition() {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> pool.get("cn-north-1", "222222222222:function:absent", "live", ACCOUNT));
|
||||
assertEquals("Cannot find alias arn: arn:aws-cn:lambda:cn-north-1:222222222222:function:absent:live",
|
||||
error.getMessage());
|
||||
assertTrue(storage.scanAllAccounts().isEmpty());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"1", "peer"})
|
||||
void provisionedAliasRefusesAnotherQualifierOfTheSameVersion(String qualifier) {
|
||||
alias(ACCOUNT, REGION, "peer", "1", Map.of());
|
||||
put(1);
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> pool.put(REGION, "example", qualifier, 1, ACCOUNT));
|
||||
assertEquals("ResourceConflictException", error.getErrorCode());
|
||||
assertEquals(qualifier.equals("1") ? "Version is pointed by a Provisioned Concurrency alias"
|
||||
: "Alias can't be used for Provisioned Concurrency configuration on an already Provisioned version",
|
||||
error.getMessage());
|
||||
assertEquals(1, storage.scanAllAccounts().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionedVersionRefusesAliasButAllowsADifferentVersion() {
|
||||
pool.put(REGION, "example", "1", 1, ACCOUNT);
|
||||
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);
|
||||
assertEquals(2, storage.scanAllAccounts().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lastModifiedUsesLambdasUtcOffsetForm() {
|
||||
pool = new ProvisionedConcurrencyPool(functions, aliases, storage,
|
||||
Clock.fixed(Instant.parse("2026-10-20T20:11:30.987Z"), ZoneOffset.UTC), 4, 8);
|
||||
assertEquals("2026-10-20T20:11:30+0000", put(1).lastModified());
|
||||
}
|
||||
|
||||
private ProvisionedConcurrencyPool.Status get() {
|
||||
return pool.get(REGION, "example", "live", ACCOUNT);
|
||||
}
|
||||
|
||||
@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);
|
||||
} else {
|
||||
assertThrows(AwsException.class, this::get);
|
||||
}
|
||||
} finally {
|
||||
factory.shutdownAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedExecutorRejectsPutWithoutPersistingButExistingConfigurationCanBeRemoved() {
|
||||
put(1);
|
||||
pool = new ProvisionedConcurrencyPool(functions, aliases, storage, Clock.systemUTC(), 4, 8, false);
|
||||
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());
|
||||
assertEquals(1, get().requested());
|
||||
pool.delete(REGION, "example", "live", ACCOUNT);
|
||||
assertTrue(storage.scanAllAccounts().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacementAndRestoreKeepDesiredCapacityWithoutClaimingReadiness() {
|
||||
ProvisionedConcurrencyPool.Status initial = put(1);
|
||||
assertEquals(initial, put(1));
|
||||
assertEquals(2, put(2).requested());
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reservationsAndQualifiersShareTheFunctionCeiling() {
|
||||
LambdaFunction latest = functions.getForAccount(ACCOUNT, REGION, "example").orElseThrow();
|
||||
latest.setReservedConcurrentExecutions(2);
|
||||
assertThrows(AwsException.class, () -> put(3));
|
||||
put(1);
|
||||
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());
|
||||
}
|
||||
|
||||
@Test
|
||||
void quotaErrorPrecedesVersionConflictAndRejectedReplacementPreservesTheRequest() {
|
||||
put(4);
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> pool.put(REGION, "example", "1", 1, ACCOUNT));
|
||||
assertEquals("InvalidParameterValueException", failure.getErrorCode());
|
||||
assertThrows(AwsException.class, () -> put(5));
|
||||
assertEquals(4, get().requested());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionAndResetRespectAccountAndRegionOwnership() {
|
||||
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);
|
||||
}
|
||||
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());
|
||||
}
|
||||
pool.clear();
|
||||
assertTrue(storage.scanAllAccounts().isEmpty());
|
||||
pool.start();
|
||||
assertThrows(AwsException.class, () -> pool.get("eu-west-1", "example", "live", ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void weightedAliasLookupAndDeletionDoNotReapplyPutEligibility() {
|
||||
put(1);
|
||||
alias(ACCOUNT, REGION, "live", "1", Map.of("2", 0.1));
|
||||
assertEquals(1, get().requested());
|
||||
assertThrows(AwsException.class, () -> put(2));
|
||||
pool.delete(REGION, "example", "live", ACCOUNT);
|
||||
assertTrue(storage.scanAllAccounts().isEmpty());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void configuredAliasCannotRetargetToCapacityOwnedByAnotherQualifier(boolean otherAlias) {
|
||||
function(ACCOUNT, REGION, "2");
|
||||
alias(ACCOUNT, REGION, "peer", "2", Map.of());
|
||||
put(1);
|
||||
String destination = otherAlias ? "peer" : "2";
|
||||
pool.put(REGION, "example", destination, 1, ACCOUNT);
|
||||
AwsException conflict = assertThrows(AwsException.class,
|
||||
() -> pool.validateAliasUpdate(version, "live", "2"));
|
||||
assertEquals("ResourceConflictException", conflict.getErrorCode());
|
||||
assertEquals(409, conflict.getHttpStatus());
|
||||
assertEquals("Alias can't be used for Provisioned Concurrency configuration on an already Provisioned version",
|
||||
conflict.getMessage());
|
||||
assertEquals(1, get().requested());
|
||||
assertEquals(2, storage.scanAllAccounts().size());
|
||||
assertDoesNotThrow(() -> pool.validateAliasUpdate(version, "live", null));
|
||||
assertDoesNotThrow(() -> pool.validateAliasUpdate(version, "live", "1"));
|
||||
assertDoesNotThrow(() -> pool.validateAliasUpdate(version, "unconfigured", "2"));
|
||||
pool.delete(REGION, "example", destination, ACCOUNT);
|
||||
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"));
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
}
|
||||
put.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
assertTrue(storage.scanAllAccounts().isEmpty());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user