feat(cloudformation): provision ElastiCache serverless caches (#5423)

* feat(cloudformation): provision ElastiCache serverless caches

Add the AWS::ElastiCache::ServerlessCache provisioner on top of the serverless cache API, with dotted Endpoint.* and ReaderEndpoint.* Fn::GetAtt attributes, in-place modification, rejected immutable changes and replacement on rename.

* fix(cloudformation): reject a malformed NoPasswordRequired on ElastiCache users

* fix(cloudformation): restore serverless cache settings on a failed update and reset removed ones

* refactor(elasticache): inject ElastiCacheService once into the serverless service

* fix(cloudformation): replace a serverless cache on its create-only properties

Register AWS::ElastiCache::ServerlessCache in create-only-properties.json so a
change to ServerlessCacheName, SubnetIds, KmsKeyId or SnapshotArnsToRestore is
reported as a replacement instead of being applied in place or ignored.

Share one Docker availability probe across the ElastiCache integration tests and
validate the tag count in one place in ElastiCacheServerlessService.

* fix(cloudformation): reject custom-named serverless cache replacement on create-only properties

* fix(cloudformation): simplify serverless create-only update check and share replacement error
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-13 13:00:16 -04:00
1 parent 367ae0b2db
commit b8e628356c
21 files changed
+1065 -89

No files matched your search

@@ -37,6 +37,20 @@ class CfnCreateOnlyPropertiesTest {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGatewayV2::VpcLink", "Tags"));
}
@Test
void isCreateOnly_serverlessCacheReplacesOnItsSchemaProperties() {
String type = "AWS::ElastiCache::ServerlessCache";
assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "ServerlessCacheName"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "SubnetIds"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "KmsKeyId"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "SnapshotArnsToRestore"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "ConnectionType"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "NetworkType"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "SecurityGroupIds"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "Description"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "Tags"));
}
@Test
void isCreateOnly_treatsEmptySchemaListAsAuthoritative() {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::RestApi", "Name"));
@@ -64,6 +64,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.EcsCapaci
import io.github.hectorvent.floci.services.cloudformation.provisioners.EcsCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EksCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ElastiCacheCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ElastiCacheServerlessCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ElbV2CfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsArchiveCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsCfnProvisioner;
@@ -123,6 +124,7 @@ import io.github.hectorvent.floci.services.ecr.EcrService;
import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.eks.EksService;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheMemcachedService;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheServerlessService;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheService;
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
@@ -236,6 +238,7 @@ final class CfnProvisionerFixture {
private BackupService backupService;
private ElastiCacheService elastiCacheService;
private ElastiCacheMemcachedService elastiCacheMemcachedService;
private ElastiCacheServerlessService elastiCacheServerlessService;
private RedshiftService redshiftService;
private RedshiftServerlessService redshiftServerlessService;
private CloudMapService cloudMapService;
@@ -464,6 +467,9 @@ final class CfnProvisionerFixture {
if (elastiCacheService != null && elastiCacheMemcachedService != null) {
discovered.add(new ElastiCacheCfnProvisioner(elastiCacheService, elastiCacheMemcachedService));
}
if (elastiCacheServerlessService != null) {
discovered.add(new ElastiCacheServerlessCfnProvisioner(elastiCacheServerlessService));
}
if (redshiftService != null) {
discovered.add(new RedshiftClusterCfnProvisioner(redshiftService));
}
@@ -746,6 +752,11 @@ final class CfnProvisionerFixture {
return this;
}
public Builder elastiCacheServerless(ElastiCacheServerlessService s) {
this.elastiCacheServerlessService = s;
return this;
}
public Builder redshiftService(RedshiftService s) {
this.redshiftService = s;
return this;
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.DockerAvailability;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
@@ -17,9 +18,7 @@ import software.amazon.awssdk.services.elasticache.model.CacheSubnetGroupNotFoun
import software.amazon.awssdk.services.elasticache.model.ElastiCacheException;
import software.amazon.awssdk.services.elasticache.model.UserGroupNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
@@ -191,7 +190,7 @@ class ElastiCacheCfnIntegrationTest {
@Test
void cacheClusterExposesEndpoints() throws Exception {
Assumptions.assumeTrue(dockerAvailable(), "Docker is required for the cache data plane");
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for the cache data plane");
cloudFormation(DATA_STACK, "CreateStack", DATA_TEMPLATE);
String stacks = describeStacks(DATA_STACK, "CREATE_COMPLETE");
@@ -210,21 +209,6 @@ class ElastiCacheCfnIntegrationTest {
CfnStackWaits.awaitStackDeleted(DATA_STACK);
}
private static boolean dockerAvailable() throws Exception {
Process process;
try {
process = new ProcessBuilder("docker", "info").redirectOutput(ProcessBuilder.Redirect.DISCARD)
.redirectError(ProcessBuilder.Redirect.DISCARD).start();
} catch (IOException expected) {
// Docker CLI is optional on development machines.
return false;
}
if (!process.waitFor(10, TimeUnit.SECONDS)) {
process.destroyForcibly();
return false;
}
return process.exitValue() == 0;
}
private static void cloudFormation(String stack, String action, String templateBody) {
RequestSpecification request = given()
@@ -0,0 +1,142 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.elasticache.ServerlessTestProfile;
import io.github.hectorvent.floci.testing.DockerAvailability;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.elasticache.ElastiCacheClient;
import software.amazon.awssdk.services.elasticache.model.ServerlessCache;
import software.amazon.awssdk.services.elasticache.model.ServerlessCacheNotFoundException;
import software.amazon.awssdk.services.elasticache.model.UserGroupNotFoundException;
import java.net.URI;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Provisions AWS::ElastiCache::ServerlessCache through CloudFormation. Output values are asserted,
* not only the stack status: an unmapped type is stubbed as CREATE_COMPLETE, and its Fn::GetAtt
* resolves to the literal "LogicalId.Attr".
*/
@QuarkusTest
@TestProfile(ServerlessTestProfile.class)
class ElastiCacheServerlessCfnIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260903/us-east-1/cloudformation/aws4_request";
private static final String STACK = "elasticache-cfn-serverless-it";
private static final String TEMPLATE = """
{
"Resources": {
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.74.0.0/16"}},
"Subnet": {"Type": "AWS::EC2::Subnet",
"Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.74.0.0/24"}},
"DefaultUser": {"Type": "AWS::ElastiCache::User",
"Properties": {"UserId": "cfn-it-sl-default", "UserName": "default",
"Engine": "redis", "AccessString": "off -@all",
"NoPasswordRequired": true}},
"UserGroup": {"Type": "AWS::ElastiCache::UserGroup",
"Properties": {"UserGroupId": "cfn-it-sl-users", "Engine": "redis",
"UserIds": [{"Ref": "DefaultUser"}]}},
"Serverless": {"Type": "AWS::ElastiCache::ServerlessCache",
"Properties": {"ServerlessCacheName": "cfn-it-serverless", "Engine": "valkey",
"SubnetIds": [{"Ref": "Subnet"}],
"UserGroupId": {"Ref": "UserGroup"}}}
},
"Outputs": {
"ServerlessRef": {"Value": {"Ref": "Serverless"}},
"ServerlessArn": {"Value": {"Fn::GetAtt": ["Serverless", "ARN"]}},
"ServerlessAddress": {"Value": {"Fn::GetAtt": ["Serverless", "Endpoint.Address"]}},
"ServerlessPort": {"Value": {"Fn::GetAtt": ["Serverless", "Endpoint.Port"]}}
}
}
""";
@TestHTTPResource
URI endpoint;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private ElastiCacheClient client() {
return ElastiCacheClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
.build();
}
@Test
void serverlessCacheExposesEndpointsAndIsRemovedWithTheStack() throws Exception {
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for the cache data plane");
cloudFormation(STACK, "CreateStack", TEMPLATE);
String stacks = describeStacks(STACK, "CREATE_COMPLETE");
assertEquals("cfn-it-serverless", outputValue(stacks, "ServerlessRef"));
assertFalse(outputValue(stacks, "ServerlessAddress").contains("Serverless.Endpoint"),
"an unset attribute resolves to the literal LogicalId.Attr");
assertTrue(outputValue(stacks, "ServerlessArn").endsWith(":serverlesscache:cfn-it-serverless"));
try (ElastiCacheClient client = client()) {
ServerlessCache serverless = client.describeServerlessCaches(r -> r.serverlessCacheName("cfn-it-serverless"))
.serverlessCaches().getFirst();
assertNotNull(serverless.endpoint());
assertEquals(outputValue(stacks, "ServerlessPort"), String.valueOf(serverless.endpoint().port()));
assertEquals("cfn-it-sl-users", serverless.userGroupId());
}
cloudFormation(STACK, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(STACK);
try (ElastiCacheClient client = client()) {
assertThrows(ServerlessCacheNotFoundException.class,
() -> client.describeServerlessCaches(r -> r.serverlessCacheName("cfn-it-serverless")));
assertThrows(UserGroupNotFoundException.class,
() -> client.describeUserGroups(r -> r.userGroupId("cfn-it-sl-users")));
}
}
private static void cloudFormation(String stack, String action, String templateBody) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stack);
if (templateBody != null) {
request.formParam("TemplateBody", templateBody);
}
request.when().post("/").then().statusCode(200);
}
private static String describeStacks(String stack, String expectedStatus) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
.extract().asString();
}
private static String outputValue(String xml, String key) {
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
}
}
@@ -333,6 +333,16 @@ class ElastiCacheCfnProvisionerTest {
verify(cache, never()).createUser(any(), any(), any(), any(), any(), any());
}
@Test
void userRejectsMalformedNoPasswordRequiredFlag() {
StackResource r = resource("AWS::ElastiCache::User", "Bad");
AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{"UserId":"u","UserName":"u","Engine":"redis","NoPasswordRequired":"yes"}
"""), ctx(null)));
assertEquals("ValidationException", ex.getErrorCode());
verify(cache, never()).createUser(any(), any(), any(), any(), any(), any());
}
@Test
void userRejectsConflictingNoPasswordRequiredAndPasswords() {
StackResource r = resource("AWS::ElastiCache::User", "Bad");
@@ -0,0 +1,399 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
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.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheServerlessService;
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
import io.github.hectorvent.floci.services.elasticache.model.ServerlessCache;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ElastiCacheServerlessCfnProvisionerTest {
private final ObjectMapper mapper = new ObjectMapper();
private final ElastiCacheServerlessService serverless = mock(ElastiCacheServerlessService.class);
private final ElastiCacheServerlessCfnProvisioner serverlessProvisioner =
new ElastiCacheServerlessCfnProvisioner(serverless);
private ProvisionContext ctx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
when(engine.resolveStringList(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
List<String> values = new ArrayList<>();
if (node != null && node.isArray()) {
node.forEach(item -> values.add(item.asText()));
}
return values;
});
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
}
private StackResource resource(String type, String logicalId) {
StackResource r = new StackResource();
r.setLogicalId(logicalId);
r.setResourceType(type);
r.setAttributes(new HashMap<>());
return r;
}
private ObjectNode props(String json) throws Exception {
return (ObjectNode) mapper.readTree(json);
}
@Test
void serverlessCacheExposesEndpointAndArnAttributes() throws Exception {
ServerlessCache created = new ServerlessCache();
created.setServerlessCacheName("sl");
created.setArn("arn:aws:elasticache:us-east-1:000000000000:serverlesscache:sl");
created.setStatus("available");
created.setFullEngineVersion("8.0");
created.setEndpoint(new Endpoint("localhost", 6420));
created.setReaderEndpoint(new Endpoint("localhost", 6421));
when(serverless.createServerlessCache(any())).thenReturn(created);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
serverlessProvisioner.provision(r, props("""
{"ServerlessCacheName":"sl","Engine":"valkey","SubnetIds":["subnet-1"],"UserGroupId":"team",
"CacheUsageLimits":{"DataStorage":{"Maximum":10,"Unit":"GB"},"ECPUPerSecond":{"Maximum":5000}}}
"""), ctx(null));
assertEquals("sl", r.getPhysicalId());
assertEquals("arn:aws:elasticache:us-east-1:000000000000:serverlesscache:sl", r.getAttributes().get("ARN"));
assertEquals("6420", r.getAttributes().get("Endpoint.Port"));
assertEquals("localhost", r.getAttributes().get("ReaderEndpoint.Address"));
ArgumentCaptor<ElastiCacheServerlessService.CreateServerlessCacheRequest> request =
ArgumentCaptor.forClass(ElastiCacheServerlessService.CreateServerlessCacheRequest.class);
verify(serverless).createServerlessCache(request.capture());
assertEquals("team", request.getValue().userGroupId());
assertEquals(10, request.getValue().cacheUsageLimits().dataStorage().maximum());
assertEquals(5000, request.getValue().cacheUsageLimits().ecpuPerSecond().maximum());
}
@Test
void mixedCaseServerlessNameIsReusedOnUpdateThroughItsLowercaseForm() throws Exception {
ServerlessCache existing = new ServerlessCache();
existing.setServerlessCacheName("mycache");
existing.setArn("arn");
existing.setStatus("available");
when(serverless.getServerlessCache("mycache")).thenReturn(existing);
when(serverless.modifyServerlessCache(any())).thenReturn(existing);
when(serverless.replaceTags(eq("mycache"), any())).thenReturn(existing);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
serverlessProvisioner.provision(r, props("{\"ServerlessCacheName\":\"MyCache\",\"Engine\":\"valkey\"}"),
ctx("mycache"));
verify(serverless, never()).createServerlessCache(any());
assertEquals("mycache", r.getPhysicalId());
}
@Test
void serverlessSubnetChangeIsRejectedInsteadOfIgnored() throws Exception {
ServerlessCache existing = new ServerlessCache();
existing.setServerlessCacheName("sl");
existing.setSubnetIds(List.of("subnet-1"));
when(serverless.getServerlessCache("sl")).thenReturn(existing);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
r.getAttributes().put("__FlociCreateOnly", "{\"SubnetIds\":[\"subnet-1\"]}");
AwsException error = assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r,
props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\",\"SubnetIds\":[\"subnet-2\"]}"), ctx("sl")));
assertEquals("ValidationError", error.getErrorCode());
assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. "
+ "Rename sl and update the stack again.", error.getMessage());
verify(serverless, never()).modifyServerlessCache(any());
}
@Test
void serverlessKmsKeyChangeIsRejectedInsteadOfIgnored() throws Exception {
ServerlessCache existing = new ServerlessCache();
existing.setServerlessCacheName("sl");
existing.setKmsKeyId("key-1");
when(serverless.getServerlessCache("sl")).thenReturn(existing);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
r.getAttributes().put("__FlociCreateOnly", "{\"KmsKeyId\":\"key-1\"}");
AwsException error = assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r,
props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\"}"), ctx("sl")));
assertEquals("ValidationError", error.getErrorCode());
assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. "
+ "Rename sl and update the stack again.", error.getMessage());
verify(serverless, never()).modifyServerlessCache(any());
}
@Test
void serverlessSnapshotArnsToRestoreChangeIsRejectedInsteadOfIgnored() throws Exception {
ServerlessCache existing = new ServerlessCache();
existing.setServerlessCacheName("sl");
when(serverless.getServerlessCache("sl")).thenReturn(existing);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
r.getAttributes().put("__FlociCreateOnly", "{}");
AwsException error = assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r,
props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\",\"SnapshotArnsToRestore\":[\"arn:aws:snapshot:1\"]}"),
ctx("sl")));
assertEquals("ValidationError", error.getErrorCode());
assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. "
+ "Rename sl and update the stack again.", error.getMessage());
verify(serverless, never()).modifyServerlessCache(any());
}
@Test
void serverlessConnectionTypeChangeIsRejectedInsteadOfIgnored() throws Exception {
ServerlessCache existing = new ServerlessCache();
existing.setServerlessCacheName("sl");
when(serverless.getServerlessCache("sl")).thenReturn(existing);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
r.getAttributes().put("__FlociCreateOnly", "{\"ConnectionType\":\"vpc\"}");
AwsException error = assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r,
props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\",\"ConnectionType\":\"public\"}"),
ctx("sl")));
assertEquals("ValidationError", error.getErrorCode());
assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. "
+ "Rename sl and update the stack again.", error.getMessage());
verify(serverless, never()).modifyServerlessCache(any());
}
@Test
void serverlessNetworkTypeChangeIsRejectedInsteadOfIgnored() throws Exception {
ServerlessCache existing = new ServerlessCache();
existing.setServerlessCacheName("sl");
when(serverless.getServerlessCache("sl")).thenReturn(existing);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
r.getAttributes().put("__FlociCreateOnly", "{\"NetworkType\":\"ipv4\"}");
AwsException error = assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r,
props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\",\"NetworkType\":\"ipv6\"}"),
ctx("sl")));
assertEquals("ValidationError", error.getErrorCode());
assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. "
+ "Rename sl and update the stack again.", error.getMessage());
verify(serverless, never()).modifyServerlessCache(any());
}
@Test
void serverlessUpdatePreservingCreateOnlySucceedsWhileChangingCreateOnlyIsRejected() throws Exception {
ServerlessCache cache = new ServerlessCache();
cache.setServerlessCacheName("sl");
cache.setArn("arn:aws:elasticache:us-east-1:000000000000:serverlesscache:sl");
cache.setStatus("available");
cache.setDescription("initial");
when(serverless.createServerlessCache(any())).thenReturn(cache);
when(serverless.getServerlessCache("sl")).thenReturn(cache);
when(serverless.modifyServerlessCache(any())).thenReturn(cache);
when(serverless.replaceTags(eq("sl"), any())).thenReturn(cache);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
serverlessProvisioner.provision(r, props("""
{"ServerlessCacheName":"sl","Engine":"valkey","ConnectionType":"vpc","Description":"initial"}
"""), ctx(null));
assertEquals("sl", r.getPhysicalId());
assertEquals("{\"ConnectionType\":\"vpc\"}", r.getAttributes().get("__FlociCreateOnly"));
serverlessProvisioner.provision(r, props("""
{"ServerlessCacheName":"sl","Engine":"valkey","ConnectionType":"vpc","Description":"updated"}
"""), ctx("sl"));
verify(serverless).modifyServerlessCache(any());
AwsException error = assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r, props("""
{"ServerlessCacheName":"sl","Engine":"valkey","ConnectionType":"public","Description":"updated"}
"""), ctx("sl")));
assertEquals("ValidationError", error.getErrorCode());
assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. "
+ "Rename sl and update the stack again.", error.getMessage());
}
@Test
void serverlessRecordedCreateOnlyPropertyChangeIsRejected() throws Exception {
ServerlessCache existing = new ServerlessCache();
existing.setServerlessCacheName("sl");
when(serverless.getServerlessCache("sl")).thenReturn(existing);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
r.getAttributes().put("__FlociCreateOnly",
"{\"ConnectionType\":\"vpc\",\"NetworkType\":\"ipv4\",\"SnapshotArnsToRestore\":[\"arn:aws:snap-1\"]}");
AwsException error = assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r,
props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\",\"ConnectionType\":\"vpc\",\"NetworkType\":\"ipv4\"}"),
ctx("sl")));
assertEquals("ValidationError", error.getErrorCode());
assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. "
+ "Rename sl and update the stack again.", error.getMessage());
verify(serverless, never()).modifyServerlessCache(any());
}
@Test
void serverlessUpdateClearsSecurityGroupsAndDescriptionRemovedFromTheTemplate() throws Exception {
ServerlessCache existing = new ServerlessCache();
existing.setServerlessCacheName("sl");
existing.setSecurityGroupIds(List.of("sg-1"));
existing.setDescription("old");
existing.setArn("arn");
existing.setStatus("available");
when(serverless.getServerlessCache("sl")).thenReturn(existing);
when(serverless.modifyServerlessCache(any())).thenReturn(existing);
when(serverless.replaceTags(eq("sl"), any())).thenReturn(existing);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
serverlessProvisioner.provision(r, props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\"}"), ctx("sl"));
ArgumentCaptor<ElastiCacheServerlessService.ModifyServerlessCacheRequest> request =
ArgumentCaptor.forClass(ElastiCacheServerlessService.ModifyServerlessCacheRequest.class);
verify(serverless).modifyServerlessCache(request.capture());
assertEquals(List.of(), request.getValue().securityGroupIds());
assertEquals("", request.getValue().description());
}
@Test
void renamedServerlessCacheReplacesAndDeletesTheOldOne() throws Exception {
ServerlessCache created = new ServerlessCache();
created.setServerlessCacheName("new-sl");
created.setArn("arn");
created.setStatus("available");
when(serverless.createServerlessCache(any())).thenReturn(created);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
serverlessProvisioner.provision(r, props("{\"ServerlessCacheName\":\"new-sl\",\"Engine\":\"valkey\"}"), ctx("old-sl"));
assertTrue(serverlessProvisioner.hasReplacementUpdate(r));
serverlessProvisioner.completeUpdate(r);
verify(serverless).deleteServerlessCache("old-sl");
}
@Test
void serverlessUpdateModifiesInPlaceDropsUserGroupAndReplacesTags() throws Exception {
ServerlessCache existing = new ServerlessCache();
existing.setServerlessCacheName("sl");
existing.setUserGroupId("team");
existing.setArn("arn");
existing.setStatus("available");
when(serverless.getServerlessCache("sl")).thenReturn(existing);
when(serverless.modifyServerlessCache(any())).thenReturn(existing);
when(serverless.replaceTags(eq("sl"), any())).thenReturn(existing);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
serverlessProvisioner.provision(r, props("""
{"ServerlessCacheName":"sl","Engine":"valkey","Description":"updated",
"CacheUsageLimits":{"ECPUPerSecond":{"Maximum":4000}},
"Tags":[{"Key":"team","Value":"x"}]}
"""), ctx("sl"));
ArgumentCaptor<ElastiCacheServerlessService.ModifyServerlessCacheRequest> request =
ArgumentCaptor.forClass(ElastiCacheServerlessService.ModifyServerlessCacheRequest.class);
verify(serverless).modifyServerlessCache(request.capture());
assertEquals(Boolean.TRUE, request.getValue().removeUserGroup());
assertEquals("updated", request.getValue().description());
assertEquals(4000, request.getValue().cacheUsageLimits().ecpuPerSecond().maximum());
verify(serverless).replaceTags(eq("sl"), any());
verify(serverless, never()).createServerlessCache(any());
}
private ServerlessCache existingWithSettings() {
ServerlessCache existing = new ServerlessCache();
existing.setServerlessCacheName("sl");
existing.setArn("arn");
existing.setStatus("available");
existing.setDescription("old");
existing.setSecurityGroupIds(List.of("sg-1"));
existing.setUserGroupId("team");
existing.setSnapshotRetentionLimit(7);
existing.setDailySnapshotTime("05:00");
existing.setCacheUsageLimits(new ServerlessCache.CacheUsageLimits(null,
new ServerlessCache.EcpuPerSecond(null, 4000)));
existing.setTags(new HashMap<>(Map.of("env", "dev")));
return existing;
}
@Test
void serverlessUpdateResetsLimitsAndSnapshotSettingsRemovedFromTheTemplate() throws Exception {
ServerlessCache existing = existingWithSettings();
when(serverless.getServerlessCache("sl")).thenReturn(existing);
when(serverless.modifyServerlessCache(any())).thenReturn(existing);
when(serverless.replaceTags(eq("sl"), any())).thenReturn(existing);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
serverlessProvisioner.provision(r, props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\"}"), ctx("sl"));
ArgumentCaptor<ElastiCacheServerlessService.ModifyServerlessCacheRequest> request =
ArgumentCaptor.forClass(ElastiCacheServerlessService.ModifyServerlessCacheRequest.class);
verify(serverless).modifyServerlessCache(request.capture());
assertTrue(request.getValue().resetUnset());
assertEquals(null, request.getValue().cacheUsageLimits());
assertEquals(null, request.getValue().snapshotRetentionLimit());
assertEquals(null, request.getValue().dailySnapshotTime());
}
@Test
void failedTagUpdatePutsTheSettingsBack() throws Exception {
ServerlessCache existing = existingWithSettings();
when(serverless.getServerlessCache("sl")).thenReturn(existing);
when(serverless.modifyServerlessCache(any())).thenReturn(existing);
when(serverless.replaceTags(eq("sl"), any()))
.thenThrow(new AwsException("TagQuotaPerResourceExceeded", "too many", 400))
.thenReturn(existing);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r, props("""
{"ServerlessCacheName":"sl","Engine":"valkey","Description":"new"}
"""), ctx("sl")));
ArgumentCaptor<ElastiCacheServerlessService.ModifyServerlessCacheRequest> request =
ArgumentCaptor.forClass(ElastiCacheServerlessService.ModifyServerlessCacheRequest.class);
verify(serverless, times(2)).modifyServerlessCache(request.capture());
ElastiCacheServerlessService.ModifyServerlessCacheRequest restore = request.getAllValues().get(1);
assertEquals("old", restore.description());
assertEquals(List.of("sg-1"), restore.securityGroupIds());
assertEquals("team", restore.userGroupId());
assertEquals(7, restore.snapshotRetentionLimit());
assertEquals("05:00", restore.dailySnapshotTime());
assertEquals(4000, restore.cacheUsageLimits().ecpuPerSecond().maximum());
verify(serverless).replaceTags("sl", Map.of("env", "dev"));
}
@Test
void rollbackOfAnInPlaceServerlessUpdateRestoresThePriorSettings() throws Exception {
ServerlessCache existing = existingWithSettings();
when(serverless.getServerlessCache("sl")).thenReturn(existing);
when(serverless.modifyServerlessCache(any())).thenReturn(existing);
when(serverless.replaceTags(eq("sl"), any())).thenReturn(existing);
StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl");
serverlessProvisioner.provision(r, props("""
{"ServerlessCacheName":"sl","Engine":"valkey","Description":"new"}
"""), ctx("sl"));
assertTrue(serverlessProvisioner.rollbackUpdate(r));
ArgumentCaptor<ElastiCacheServerlessService.ModifyServerlessCacheRequest> request =
ArgumentCaptor.forClass(ElastiCacheServerlessService.ModifyServerlessCacheRequest.class);
verify(serverless, times(2)).modifyServerlessCache(request.capture());
assertEquals("old", request.getAllValues().get(1).description());
serverlessProvisioner.clearUpdate(r);
assertTrue(r.getAttributes().keySet().stream().noneMatch(k -> k.contains("ServerlessCacheUpdateSnapshot")));
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.elasticache;
import io.github.hectorvent.floci.testing.DockerAvailability;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import org.junit.jupiter.api.AfterAll;
@@ -44,8 +45,8 @@ class ElastiCacheClusterIntegrationTest {
private static int secondShardPort;
@BeforeAll
static void requireDocker() {
Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for ElastiCache integration tests");
static void requireDocker() throws InterruptedException {
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for ElastiCache integration tests");
}
@AfterAll
@@ -214,15 +215,6 @@ class ElastiCacheClusterIntegrationTest {
.statusCode(404);
}
private static boolean isDockerAvailable() {
try {
Process process = new ProcessBuilder("docker", "info").start();
return process.waitFor() == 0;
} catch (Exception e) {
return false;
}
}
private static Socket openSocket(int port) throws IOException {
Socket socket = new Socket("localhost", port);
socket.setTcpNoDelay(true);
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.elasticache;
import io.github.hectorvent.floci.testing.DockerAvailability;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import org.junit.jupiter.api.AfterAll;
@@ -40,8 +41,8 @@ class ElastiCacheRedisClusterIntegrationTest {
private static int nodePort;
@BeforeAll
static void requireDocker() {
Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for ElastiCache integration tests");
static void requireDocker() throws InterruptedException {
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for ElastiCache integration tests");
}
@AfterAll
@@ -175,15 +176,6 @@ class ElastiCacheRedisClusterIntegrationTest {
.statusCode(404);
}
private static boolean isDockerAvailable() {
try {
Process process = new ProcessBuilder("docker", "info").start();
return process.waitFor() == 0;
} catch (Exception e) {
return false;
}
}
private static Socket openSocket(String host, int port) throws IOException {
Socket socket = new Socket(host, port);
socket.setTcpNoDelay(true);
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.elasticache;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.testing.DockerAvailability;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
@@ -20,7 +21,6 @@ import java.net.Socket;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
@@ -100,7 +100,7 @@ class ElastiCacheServerlessIntegrationTest {
@Test
void dockerValkeyPreservesDataAndAuthenticatesCurrentGroupMembers() throws Exception {
Assumptions.assumeTrue(dockerAvailable(), "Docker is required for the serverless data plane");
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for the serverless data plane");
try (ElastiCacheClient client = client()) {
client.createUser(request -> request.userId("serverless-alice").userName("alice").engine("valkey")
.accessString("on ~* +@all").passwords("alice-password-123"));
@@ -164,7 +164,7 @@ class ElastiCacheServerlessIntegrationTest {
@Test
void dockerMemcachedPreservesValuesAcrossMetadataChanges() throws Exception {
Assumptions.assumeTrue(dockerAvailable(), "Docker is required for the serverless Memcached data plane");
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for the serverless Memcached data plane");
try (ElastiCacheClient client = client()) {
try {
ServerlessCache cache = client.createServerlessCache(request -> request.serverlessCacheName("serverless-memcached")
@@ -196,22 +196,6 @@ class ElastiCacheServerlessIntegrationTest {
}
}
private static boolean dockerAvailable() throws IOException, InterruptedException {
Process process;
try {
process = new ProcessBuilder("docker", "info").redirectOutput(ProcessBuilder.Redirect.DISCARD)
.redirectError(ProcessBuilder.Redirect.DISCARD).start();
} catch (IOException expected) {
// Docker CLI is optional on development machines.
return false;
}
if (!process.waitFor(10, TimeUnit.SECONDS)) {
process.destroyForcibly();
return false;
}
return process.exitValue() == 0;
}
private static Socket socket(ServerlessCache cache) throws IOException {
Socket socket = new Socket(cache.endpoint().address(), cache.endpoint().port());
socket.setSoTimeout(10_000);
@@ -28,6 +28,7 @@ import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -108,7 +109,7 @@ class ElastiCacheServerlessServiceTest {
config, ec2, resolver, kms, new ElastiCacheProvisioningIds());
memcached = new ElastiCacheMemcachedService(mock(ElastiCacheMemcachedContainerManager.class), factory,
config, new ElastiCacheProvisioningIds(), resolver);
service = new ElastiCacheServerlessService(factory, resolver, runtime, memcached, runtime);
service = new ElastiCacheServerlessService(factory, resolver, runtime, memcached);
runtime.createUser("alice", "alice", AuthMode.PASSWORD, List.of("password-a"), "on ~* +@all", "valkey");
runtime.createUser("bob", "bob", AuthMode.PASSWORD, List.of("password-b"), "on ~* +@all", "valkey");
runtime.createUserGroup("team", "valkey", List.of("alice"), "us-east-1");
@@ -242,7 +243,7 @@ class ElastiCacheServerlessServiceTest {
@Test
void rehydratedServiceRetainsRuntimeIdentityAndAssociation() {
ServerlessCache original = service.createServerlessCache(create("cache", "valkey", "team"));
ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(factory, resolver, runtime, memcached, runtime);
ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(factory, resolver, runtime, memcached);
assertEquals(original.getBackingCacheClusterId(), reloaded.getServerlessCache("cache").getBackingCacheClusterId());
error("InvalidUserGroupState", () -> runtime.deleteUserGroup("team"));
reloaded.deleteServerlessCache("cache");
@@ -306,14 +307,14 @@ class ElastiCacheServerlessServiceTest {
void persistentRestartRestoresHiddenRuntimeCredentialsAndPortOwnership() {
StorageFactory persistent = persistentFactory();
ElastiCacheService persistedRuntime = newRuntime(persistent);
ElastiCacheServerlessService persisted = new ElastiCacheServerlessService(persistent, resolver, persistedRuntime, memcached, persistedRuntime);
ElastiCacheServerlessService persisted = new ElastiCacheServerlessService(persistent, resolver, persistedRuntime, memcached);
persistedRuntime.createUser("member", "member", AuthMode.PASSWORD, List.of("secret"), "on ~* +@all", "valkey");
persistedRuntime.createUserGroup("persisted-team", "valkey", List.of("member"), "us-east-1");
ServerlessCache original = persisted.createServerlessCache(create("persistent", "valkey", "persisted-team"));
persistent.shutdownAll();
StorageFactory reloadedFactory = persistentFactory();
ElastiCacheService reloadedRuntime = newRuntime(reloadedFactory);
ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(reloadedFactory, resolver, reloadedRuntime, memcached, reloadedRuntime);
ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(reloadedFactory, resolver, reloadedRuntime, memcached);
reloadedFactory.loadAll();
clearInvocations(proxies);
reloadedRuntime.restorePersistedRuntime().join();
@@ -361,7 +362,7 @@ class ElastiCacheServerlessServiceTest {
assertTrue(backing.getForAccount("111111111111", original.getBackingCacheClusterId()).isPresent());
context.setAccountId("111111111111");
context.setRegion("cn-north-1");
ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(factory, resolver, reloadedRuntime, memcached, reloadedRuntime);
ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(factory, resolver, reloadedRuntime, memcached);
assertEquals(original.getEndpoint(), reloaded.getServerlessCache("account-cache").getEndpoint());
reloaded.deleteServerlessCache("account-cache");
runtime.deleteUserGroup("team");
@@ -431,4 +432,39 @@ class ElastiCacheServerlessServiceTest {
assertNotNull(runtime.deleteUserGroup("team"));
}
@Test
void modifyWithResetUnsetClearsLimitsAndSnapshotSettingsButOmittedFieldsStayOtherwise() {
service.createServerlessCache(new ElastiCacheServerlessService.CreateServerlessCacheRequest("reset-cache",
"valkey", null, "description", List.of("subnet-local"), List.of("sg-local"), null, null,
new ServerlessCache.CacheUsageLimits(null, new ServerlessCache.EcpuPerSecond(null, 4000)), 7, "05:00",
List.of(), Map.of()));
ServerlessCache kept = service.modifyServerlessCache(new ElastiCacheServerlessService.ModifyServerlessCacheRequest(
"reset-cache", "d", null, null, null, null, null, null, null, null));
assertEquals(7, kept.getSnapshotRetentionLimit());
assertEquals("05:00", kept.getDailySnapshotTime());
assertNotNull(kept.getCacheUsageLimits());
ServerlessCache reset = service.modifyServerlessCache(new ElastiCacheServerlessService.ModifyServerlessCacheRequest(
"reset-cache", "d", null, null, null, null, null, null, null, null, true));
assertEquals(0, reset.getSnapshotRetentionLimit());
assertNull(reset.getDailySnapshotTime());
assertNull(reset.getCacheUsageLimits());
}
@Test
void replaceTagsDrivesTheTagsToTheGivenSetAndRejectsMoreThanFifty() {
service.createServerlessCache(create("tag-cache", "valkey", null));
assertEquals(Map.of("env", "dev"), service.replaceTags("tag-cache", Map.of("env", "dev")).getTags());
assertEquals(Map.of("env", "dev"), service.getServerlessCache("tag-cache").getTags());
Map<String, String> tooMany = new HashMap<>();
for (int i = 0; i < 51; i++) {
tooMany.put("k" + i, "v");
}
error("TagQuotaPerResourceExceeded", () -> service.replaceTags("tag-cache", tooMany));
assertEquals(Map.of("env", "dev"), service.getServerlessCache("tag-cache").getTags());
}
}
@@ -0,0 +1,32 @@
package io.github.hectorvent.floci.testing;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/** Probe that lets Docker-backed integration tests skip themselves when no daemon answers. */
public final class DockerAvailability {
private static final long PROBE_TIMEOUT_SECONDS = 10;
private DockerAvailability() {
}
/** True when {@code docker info} succeeds within the probe timeout. */
public static boolean isAvailable() throws InterruptedException {
Process process;
try {
process = new ProcessBuilder("docker", "info")
.redirectOutput(ProcessBuilder.Redirect.DISCARD)
.redirectError(ProcessBuilder.Redirect.DISCARD)
.start();
} catch (IOException expected) {
// The Docker CLI is optional on development machines.
return false;
}
if (!process.waitFor(PROBE_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
process.destroyForcibly();
return false;
}
return process.exitValue() == 0;
}
}