fix(elasticache): create single-node redis clusters and close provisioning races (#3634)

* feat(elasticache): support single-node redis clusters in CreateCacheCluster

CreateCacheCluster refused every engine but memcached, telling callers to use
CreateReplicationGroup instead. Real AWS accepts Engine=redis and Engine=valkey
there as long as the cluster has one node, and that is exactly the call
terraform's aws_elasticache_cluster with engine = "redis" emits, so every such
example failed against Floci.

A single-node redis or valkey cluster is now provisioned the way a
cluster-mode-disabled replication group is: the same Valkey container, fronted by
the same auth proxy on a port from the same range, so the endpoint a describe
reports actually answers RESP. It is stored apart from replication groups, since
one created this way has none and must not appear in DescribeReplicationGroups.

NumCacheNodes greater than 1 is refused with the message a live account gives.
Following AWS, the cluster carries no ConfigurationEndpoint (that is memcached's
node discovery endpoint) and reports its node under CacheNodes when the request
sets ShowCacheNodeInfo, which is where terraform-provider-aws reads the port.

The memcached path is unchanged. ElastiCacheMemcachedIntegrationTest asserted the
old refusal with Engine=redis; it now asserts it with an engine ElastiCache
really does not have.

* fix(elasticache): address review findings

Cross-type id collision closed both directions through one provisioningIds
claim set (the claimed thing is one namespace: container name + proxy key);
wire code corrected to CacheClusterAlreadyExists; create request grown to
round-trip the optional members Terraform reads back, guarded by a
compat-terraform bats config asserting plan -detailed-exitcode after apply;
ListTagsForResource cluster arm brought to parity with the replicationgroup
arm without regressing memcached/member fall-through; standalone clusters
join getResources; create/delete responses no longer leak CacheNodes.

* fix(elasticache): correct review-round test assertion, bats port pin, docs note

The cross-type guard test asserted never() on a tryStart its own setup
legitimately performs — times(1), matching the sibling test. The single-node
bats config pinned port 6379, which the parallel bats runner's sibling
replication-group config fills first from the range base (the allocator
refuses rather than substitutes) — pinned to 6395. AtRestEncryptionEnabled
noted in docs as output-only on real AWS's CreateCacheCluster.

* docs(elasticache): the output-only note belongs to the single-node prose, not the CreateReplicationGroup row

AtRestEncryptionEnabled is a legitimate input member of
CreateReplicationGroupMessage; it is absent only from CreateCacheClusterMessage.

* fix(elasticache): reserve persisted ports on restore, cross-store id uniqueness, validate subnet group

Three findings from the PR review, all on the single-node cache cluster path.

Ports of records that survive a restart are now reserved before Floci serves
anything. Standalone cache clusters and cluster-mode-disabled replication groups
are not re-provisioned, but they still advertise the port they were given, and
nothing put those ports back into the in-use set: a create after a restart was
handed a port a live record still published, and the two then contended over one
reservation, so the first delete freed it and the next create took it again. A
delete now releases only a port this process actually reserved for that record,
since a restored record whose port was already taken advertises one it does not
own.

The id check spans all three stores that answer DescribeCacheClusters. A
standalone redis cluster, a Memcached cluster and a replication group can no
longer share an id in either direction. Both services read the same backends:
StorageFactory keys them by file path and hands the second caller the first
caller's instance, so no new wiring is needed for the two services to agree on
one namespace.

CacheSubnetGroupName must now name a subnet group that exists, instead of being
stored as a reference a describe reports and a caller cannot look up.
CreateReplicationGroup still does not make that check; it is called out in the
service and in the docs rather than changed here.

* style(elasticache): drop em dash in transient-field comment

* fix(elasticache): close the id and port gaps the delta review found

CreateReplicationGroup's duplicate-id check read only the group and redis
cluster stores, so a group could take the id of a live memcached cluster
while CreateCacheCluster refused the same collision the other way round.
Check the third store too, which is what makes the documented "an id is
taken across all three at once" actually hold.

Two port-reservation fixes alongside it. The claim on a new cache
cluster's port was recorded after the synchronized block that stores the
record, so a delete landing in the gap found nothing to release and
stranded the reservation; it now happens under the same monitor as the
put. And deleteReplicationGroup freed the group's port unconditionally,
while the cluster path has guarded that since the restore work went in: a
record restored from disk whose port was already taken advertises a port
it does not own, and freeing it hands a live record's port to the next
create. The holder set now covers both kinds, keyed by id, which is safe
because an id is unique across the stores.

* docs(elasticache): say which engines the subnet-group check covers

CreateCacheCluster with Engine=memcached routes to a create that takes
only the cluster id, so CacheSubnetGroupName is dropped on that path: not
checked, not echoed. The page claimed the check unqualified. Also name
CreateReplicationGroup in the id-uniqueness paragraph, now that it makes
the same check.

* test(elasticache): cover the ordinary group delete that frees its port

The two port tests around it both step past the create path: one deletes a
group written straight into the store, the other one restored after a
restart. So the claim recorded when a group is created in process had
nothing behind it, and dropping it would leave the suite green while every
DeleteReplicationGroup leaked its proxy port for the life of the process.

* fix(elasticache): claim the id on the memcached create path too

CreateCacheCluster for memcached checked the three stores for a duplicate id
and went straight on to start its container, without joining the in-flight
claim set the redis cluster and replication group paths take. No create path
persists its record until after container startup, so a memcached create and
a redis create for one id could both read three empty stores and both write,
leaving the id in two stores with DescribeCacheClusters reporting it twice
and the two containers and proxy registrations colliding under one name.

Move that set out of ElastiCacheService into an ElastiCacheProvisioningIds
bean both services inject, so the claim covers every engine, and take it in
the memcached path before the store checks with the same try/finally release.
A collision with an in-flight create is refused with the fault the store-hit
path already produces, CacheClusterAlreadyExistsFault.

* fix(elasticache): complete the CacheNode shape and correct the memcached fault code

DescribeCacheClusters returned a CacheNode carrying only an id, a status and an
endpoint. terraform-provider-aws dereferences CacheNodeCreateTime and
ParameterGroupStatus while adopting the resource without a nil check, so the
compat-terraform job created floci-tf-redis-single successfully and then died on
the very next refresh with "Unexpected nil pointer" naming both fields. The
endpoint was never the problem; the node shape was incomplete.

Both are stable metadata AWS returns on every available node, and both were
already known here: a single-node cluster's node was created with the cluster,
and its parameter group carries the same in-sync status already reported for the
cluster. CustomerAvailabilityZone is emitted from the cluster's AZ for the same
reason -- a node whose AZ disagrees with its cluster is a permanent plan diff.
Memcached returns early well above this block, so its wire output is unchanged.

Separately, the id claim added on the memcached create path threw
CacheClusterAlreadyExistsFault. The wire code is CacheClusterAlreadyExists -- the
Fault suffix is the botocore shape name, not the code an SDK matches on -- which
this branch had already established on the redis side and then contradicted.
Both memcached throw sites now use the wire code, including the pre-existing one,
and the five test assertions that pinned the wrong spelling are corrected.

* test(elasticache): stop the single-node fixture pinning the shared suite's port

The compat-terraform job runs every stack against one Floci, and this branch's
new elasticache-single-node-tf pinned port 6395 -- the same port main.tf already
pins for the replication group the `terraform` suite creates. ElastiCache
refuses a pinned port that is already reserved, by design, so the two stacks can
only both succeed if the first is fully destroyed before the second applies.

That is what the last run showed: elasticache_single_node failed its apply, so
its destroy never ran, 6395 stayed held, and the `terraform` suite then failed
with "Port 6395 is already in use by another replication group" -- a second
failure that reads like an allocator bug and is really a fixture collision.
Fixing the node shape removes the trigger but not the collision, which would
remain a teardown-ordering dependency between two independent suites.

6396 is free and inside the 6379-6399 proxy range.

* test(elasticache): name the extracted XmlPath instead of inferring it with var

Review follow-up: this was the only `var` in the file, and the type it hides
(io.restassured.path.xml.XmlPath) is the one a reader needs in order to follow
the getString/getInt calls immediately below it.

No behaviour change.

* style(test): import ArrayList and LinkedHashMap instead of naming them inline

AGENTS.md asks for imports rather than inline fully-qualified names.
ElastiCacheQueryHandlerTest had three: new java.util.ArrayList<>(...) and
two new java.util.LinkedHashMap<>(...). LinkedHashMap was already imported;
ArrayList is added.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-22 22:26:15 -04:00
1 parent 208e36abe5
commit 684239b0ef
14 files changed
+2320 -66

No files matched your search

@@ -97,10 +97,13 @@ class ElastiCacheMemcachedIntegrationTest {
@Test
@Order(3)
void createCacheClusterWithInvalidEngineReturnsError() {
// Engine=redis used to be refused here. It is a valid single-node cache cluster on AWS and
// is now accepted (see ElastiCacheRedisClusterIntegrationTest), so the refusal is asserted
// with an engine ElastiCache really does not have.
given()
.formParam("Action", "CreateCacheCluster")
.formParam("CacheClusterId", "redis-attempt")
.formParam("Engine", "redis")
.formParam("CacheClusterId", "mongodb-attempt")
.formParam("Engine", "mongodb")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
@@ -17,8 +17,10 @@ import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
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.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -31,10 +33,12 @@ class ElastiCacheMemcachedServiceTest {
private ElastiCacheMemcachedService service;
private ElastiCacheMemcachedContainerManager containerManager;
private ElastiCacheProvisioningIds provisioningIds;
@BeforeEach
void setUp() {
containerManager = mock(ElastiCacheMemcachedContainerManager.class);
provisioningIds = new ElastiCacheProvisioningIds();
StorageFactory storageFactory = mock(StorageFactory.class);
EmulatorConfig config = mock(EmulatorConfig.class);
@@ -49,7 +53,7 @@ class ElastiCacheMemcachedServiceTest {
when(containerManager.tryStart(anyString(), anyString()))
.thenReturn(new ElastiCacheContainerHandle("cid", "cluster", "localhost", 11211));
service = new ElastiCacheMemcachedService(containerManager, storageFactory, config);
service = new ElastiCacheMemcachedService(containerManager, storageFactory, config, provisioningIds);
}
@Test
@@ -67,7 +71,29 @@ class ElastiCacheMemcachedServiceTest {
service.createCacheCluster("my-cluster");
AwsException ex = assertThrows(AwsException.class, () -> service.createCacheCluster("my-cluster"));
assertEquals("CacheClusterAlreadyExistsFault", ex.getErrorCode());
assertEquals("CacheClusterAlreadyExists", ex.getErrorCode());
}
@Test
void createIsRefusedWhileARedisCreateHoldsTheSameIdInFlight() {
// What a concurrent CreateReplicationGroup or redis CreateCacheCluster leaves in the
// shared set between claiming the id and persisting its record. The three stores are
// still empty in that window, so the store checks alone would let this create through
// and both would write the same id.
assertTrue(provisioningIds.claim("racing-cluster"));
AwsException ex = assertThrows(AwsException.class,
() -> service.createCacheCluster("racing-cluster"));
assertEquals("CacheClusterAlreadyExists", ex.getErrorCode());
verify(containerManager, never()).tryStart(eq("racing-cluster"), anyString());
// The refusal must not have released the claim the other create still holds.
assertFalse(provisioningIds.claim("racing-cluster"));
// Once that create finishes and releases, the id is free again.
provisioningIds.release("racing-cluster");
assertEquals("racing-cluster",
service.createCacheCluster("racing-cluster").getCacheClusterId());
}
@Test
@@ -122,7 +148,8 @@ class ElastiCacheMemcachedServiceTest {
.thenReturn(new ElastiCacheContainerHandle("cid", "cluster", "172.20.0.10", 11211));
ElastiCacheMemcachedService containerModeService =
new ElastiCacheMemcachedService(containerManager, storageFactory, config);
new ElastiCacheMemcachedService(containerManager, storageFactory, config,
new ElastiCacheProvisioningIds());
CacheCluster cluster = containerModeService.createCacheCluster("container-cluster");
@@ -236,6 +263,7 @@ class ElastiCacheMemcachedServiceTest {
when(servicesConfig.elasticache()).thenReturn(ecConfig);
when(ecConfig.defaultMemcachedImage()).thenReturn("memcached:1.6");
when(config.hostname()).thenReturn(Optional.of("localhost"));
return new ElastiCacheMemcachedService(containerManager, storageFactory, config);
return new ElastiCacheMemcachedService(containerManager, storageFactory, config,
new ElastiCacheProvisioningIds());
}
}
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.elasticache;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import io.github.hectorvent.floci.services.elasticache.model.CacheCluster;
import io.github.hectorvent.floci.services.elasticache.model.CacheClusterStatus;
import io.github.hectorvent.floci.services.elasticache.model.ClusterNode;
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
@@ -17,6 +19,7 @@ import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
@@ -34,12 +37,13 @@ class ElastiCacheQueryHandlerTest {
private ElastiCacheQueryHandler handler;
private ElastiCacheService service;
private ElastiCacheMemcachedService memcachedService;
@BeforeEach
void setUp() {
SigV4Validator sigV4Validator = mock(SigV4Validator.class);
service = mock(ElastiCacheService.class);
ElastiCacheMemcachedService memcachedService = mock(ElastiCacheMemcachedService.class);
memcachedService = mock(ElastiCacheMemcachedService.class);
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getRegion()).thenReturn("us-east-1");
when(regionResolver.getAccountId()).thenReturn("000000000000");
@@ -415,4 +419,274 @@ class ElastiCacheQueryHandlerTest {
assertEquals(200, handler.handle("ModifyReplicationGroup", p, "us-east-1").getStatus());
verify(service).modifyReplicationGroup("g1", null, null, new ReplicationGroupSettings(null, null, 3, "01:00-02:00"));
}
// ── CreateCacheCluster / DescribeCacheClusters: single-node redis ─────────
private static CacheCluster redisCacheCluster(String id) {
CacheCluster cluster = new CacheCluster(id, CacheClusterStatus.AVAILABLE, "redis", "7.1",
new Endpoint("localhost", 6379), Instant.now());
cluster.setNumCacheNodes(1);
cluster.setCacheNodeType("cache.t4g.micro");
cluster.setAuthMode(AuthMode.NO_AUTH);
cluster.setArn("arn:aws:elasticache:us-east-1:000000000000:cluster:" + id);
cluster.setSnapshotRetentionLimit(5);
cluster.setSnapshotWindow("03:00-05:00");
cluster.setPreferredMaintenanceWindow("tue:04:00-tue:05:00");
cluster.setPreferredAvailabilityZone("us-east-1b");
cluster.setNetworkType("ipv4");
cluster.setIpDiscovery("ipv4");
cluster.setSecurityGroupIds(new ArrayList<>(List.of("sg-123")));
return cluster;
}
@Test
void createCacheCluster_redisIsAcceptedAndProvisionedAsASingleNodeCluster() {
// Real AWS accepts CreateCacheCluster with Engine=redis, and terraform's
// aws_elasticache_cluster with engine "redis" emits exactly this call.
ArgumentCaptor<ElastiCacheService.CreateCacheClusterRequest> captor =
ArgumentCaptor.forClass(ElastiCacheService.CreateCacheClusterRequest.class);
when(service.createCacheCluster(captor.capture())).thenReturn(redisCacheCluster("tf-redis"));
MultivaluedMap<String, String> p = params();
p.add("CacheClusterId", "tf-redis");
p.add("Engine", "redis");
p.add("NumCacheNodes", "1");
p.add("CacheNodeType", "cache.t4g.micro");
p.add("Port", "6379");
Response response = handler.handle("CreateCacheCluster", p, "us-east-1");
assertEquals(200, response.getStatus(), (String) response.getEntity());
assertEquals("redis", captor.getValue().engine());
assertEquals(1, captor.getValue().numCacheNodes());
assertEquals(6379, captor.getValue().port());
assertEquals("us-east-1", captor.getValue().region());
verify(memcachedService, never()).createCacheCluster(anyString());
String body = (String) response.getEntity();
assertTrue(body.contains("<Engine>redis</Engine>"), body);
assertTrue(body.contains("<NumCacheNodes>1</NumCacheNodes>"), body);
assertTrue(body.contains("<CacheNodeType>cache.t4g.micro</CacheNodeType>"), body);
// AWS reports CacheNodes only on a describe that asked for node info
assertFalse(body.contains("<CacheNodes>"), body);
}
@Test
void createCacheCluster_passesEveryOptionalMemberTheRequestCarries() {
// Each of these is an optional aws_elasticache_cluster argument: one dropped here reads
// back as unset on the next plan and terraform can never settle the diff.
ArgumentCaptor<ElastiCacheService.CreateCacheClusterRequest> captor =
ArgumentCaptor.forClass(ElastiCacheService.CreateCacheClusterRequest.class);
when(service.createCacheCluster(captor.capture())).thenReturn(redisCacheCluster("tf-redis"));
MultivaluedMap<String, String> p = params();
p.add("CacheClusterId", "tf-redis");
p.add("Engine", "redis");
p.add("SnapshotRetentionLimit", "5");
p.add("SnapshotWindow", "03:00-05:00");
p.add("PreferredMaintenanceWindow", "tue:04:00-tue:05:00");
p.add("PreferredAvailabilityZone", "us-east-1b");
p.add("SecurityGroupIds.member.1", "sg-123");
p.add("NetworkType", "ipv4");
p.add("IpDiscovery", "ipv4");
p.add("AtRestEncryptionEnabled", "true");
assertEquals(200, handler.handle("CreateCacheCluster", p, "us-east-1").getStatus());
ElastiCacheService.CreateCacheClusterRequest request = captor.getValue();
assertEquals(5, request.snapshotRetentionLimit());
assertEquals("03:00-05:00", request.snapshotWindow());
assertEquals("tue:04:00-tue:05:00", request.preferredMaintenanceWindow());
assertEquals("us-east-1b", request.preferredAvailabilityZone());
assertEquals(List.of("sg-123"), request.securityGroupIds());
assertEquals("ipv4", request.networkType());
assertEquals("ipv4", request.ipDiscovery());
assertEquals(Boolean.TRUE, request.atRestEncryptionEnabled());
}
@Test
void createCacheCluster_unknownEngineIsStillRefused() {
MultivaluedMap<String, String> p = params();
p.add("CacheClusterId", "mystery");
p.add("Engine", "mongodb");
Response response = handler.handle("CreateCacheCluster", p, "us-east-1");
assertEquals(400, response.getStatus());
assertTrue(((String) response.getEntity()).contains("InvalidParameterValue"));
verifyNoInteractions(memcachedService);
}
@Test
void createCacheCluster_memcachedStillGoesToTheMemcachedService() {
when(memcachedService.createCacheCluster("mc")).thenReturn(new CacheCluster(
"mc", CacheClusterStatus.AVAILABLE, "memcached", "1.6.22",
new Endpoint("localhost", 11211), Instant.now()));
MultivaluedMap<String, String> p = params();
p.add("CacheClusterId", "mc");
p.add("Engine", "memcached");
String body = (String) handler.handle("CreateCacheCluster", p, "us-east-1").getEntity();
verify(memcachedService).createCacheCluster("mc");
verify(service, never()).createCacheCluster(any());
assertTrue(body.contains(
"<ConfigurationEndpoint><Address>localhost</Address><Port>11211</Port></ConfigurationEndpoint>"), body);
}
@Test
void describeCacheClusters_reportsASingleNodeRedisClusterByItsNodeEndpoint() {
// AWS gives a redis cache cluster no ConfigurationEndpoint (that is Memcached's node
// discovery endpoint); terraform-provider-aws reads the port off CacheNodes instead.
when(service.findCacheClusters("tf-redis")).thenReturn(List.of(redisCacheCluster("tf-redis")));
MultivaluedMap<String, String> p = params();
p.add("CacheClusterId", "tf-redis");
p.add("ShowCacheNodeInfo", "true");
Response response = handler.handle("DescribeCacheClusters", p, "us-east-1");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("<CacheClusterId>tf-redis</CacheClusterId>"), body);
assertTrue(body.contains("<CacheClusterStatus>available</CacheClusterStatus>"), body);
assertTrue(body.contains("<Engine>redis</Engine>"), body);
assertTrue(body.contains("<EngineVersion>7.1</EngineVersion>"), body);
assertTrue(body.contains("<ARN>arn:aws:elasticache:us-east-1:000000000000:cluster:tf-redis</ARN>"), body);
assertTrue(body.contains("<CacheNodeId>0001</CacheNodeId>"), body);
assertTrue(body.contains("<Endpoint><Address>localhost</Address><Port>6379</Port></Endpoint>"), body);
assertFalse(body.contains("<ConfigurationEndpoint>"), body);
// the optional members are echoed, so a terraform re-plan has nothing to change
assertTrue(body.contains("<SnapshotRetentionLimit>5</SnapshotRetentionLimit>"), body);
assertTrue(body.contains("<SnapshotWindow>03:00-05:00</SnapshotWindow>"), body);
assertTrue(body.contains("<PreferredMaintenanceWindow>tue:04:00-tue:05:00</PreferredMaintenanceWindow>"), body);
assertTrue(body.contains("<PreferredAvailabilityZone>us-east-1b</PreferredAvailabilityZone>"), body);
assertTrue(body.contains("<SecurityGroupId>sg-123</SecurityGroupId>"), body);
assertTrue(body.contains("<NetworkType>ipv4</NetworkType>"), body);
assertTrue(body.contains("<IpDiscovery>ipv4</IpDiscovery>"), body);
assertTrue(body.contains("<CacheClusterCreateTime>"), body);
// the Memcached store is not consulted for an id another source answered for, so its
// not-found fault cannot turn a hit into a 404
verify(memcachedService, never()).listCacheClusters(anyString());
}
@Test
void describeCacheClusters_singleNodeCarriesTheNodeMetadataTerraformDereferences() {
// The node shape, not the endpoint, is what broke adoption: a create succeeded and the
// very next refresh died with "Unexpected nil pointer" showing CacheNodeCreateTime:<nil>
// and ParameterGroupStatus:<nil>. terraform-provider-aws reads both without a nil check,
// and AWS returns both on every available node.
when(service.findCacheClusters("tf-redis")).thenReturn(List.of(redisCacheCluster("tf-redis")));
MultivaluedMap<String, String> p = params();
p.add("CacheClusterId", "tf-redis");
p.add("ShowCacheNodeInfo", "true");
Response response = handler.handle("DescribeCacheClusters", p, "us-east-1");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("<CacheNodeCreateTime>"), body);
assertTrue(body.contains("<ParameterGroupStatus>in-sync</ParameterGroupStatus>"), body);
// AWS reports the node's AZ as the cluster's; a mismatch is a permanent terraform diff
assertTrue(body.contains("<CustomerAvailabilityZone>us-east-1b</CustomerAvailabilityZone>"), body);
// the node was created with its cluster, so the two timestamps agree
String nodeTime = between(body, "<CacheNodeCreateTime>", "</CacheNodeCreateTime>");
String clusterTime = between(body, "<CacheClusterCreateTime>", "</CacheClusterCreateTime>");
assertEquals(clusterTime, nodeTime, body);
}
private static String between(String body, String open, String close) {
int from = body.indexOf(open);
assertTrue(from >= 0, "missing " + open + " in " + body);
return body.substring(from + open.length(), body.indexOf(close, from));
}
@Test
void describeCacheClusters_stillRaisesNotFoundWhenNoSourceKnowsTheId() {
when(service.findCacheClusters("absent")).thenReturn(List.of());
when(memcachedService.listCacheClusters("absent")).thenThrow(
new AwsException("CacheClusterNotFound", "Cache cluster absent not found.", 404));
MultivaluedMap<String, String> p = params();
p.add("CacheClusterId", "absent");
assertEquals(404, handler.handle("DescribeCacheClusters", p, "us-east-1").getStatus());
}
@Test
void deleteCacheCluster_routesToTheServiceThatHoldsTheCluster() {
CacheCluster cluster = redisCacheCluster("tf-redis");
when(service.findCacheClusters("tf-redis")).thenReturn(List.of(cluster));
when(service.deleteCacheCluster("tf-redis")).thenReturn(cluster);
MultivaluedMap<String, String> p = params();
p.add("CacheClusterId", "tf-redis");
assertEquals(200, handler.handle("DeleteCacheCluster", p, "us-east-1").getStatus());
verify(service).deleteCacheCluster("tf-redis");
verify(memcachedService, never()).deleteCacheCluster(anyString());
}
@Test
void listTagsForResource_readsTagsOffACacheClusterArn() {
CacheCluster cluster = redisCacheCluster("tf-redis");
cluster.setTags(new LinkedHashMap<>(Map.of("Name", "cache")));
when(service.findCacheClusters("tf-redis")).thenReturn(List.of(cluster));
MultivaluedMap<String, String> p = params();
p.add("ResourceName", "arn:aws:elasticache:us-east-1:000000000000:cluster:tf-redis");
String body = (String) handler.handle("ListTagsForResource", p, "us-east-1").getEntity();
assertTrue(body.contains("<Key>Name</Key>"), body);
assertTrue(body.contains("<Value>cache</Value>"), body);
}
@Test
void listTagsForResource_clusterArnOfAnUnknownIdIsNotFound() {
when(service.findCacheClusters("absent")).thenReturn(List.of());
when(memcachedService.getCacheCluster("absent")).thenThrow(
new AwsException("CacheClusterNotFound", "Cache cluster absent not found.", 404));
MultivaluedMap<String, String> p = params();
p.add("ResourceName", "arn:aws:elasticache:us-east-1:000000000000:cluster:absent");
Response response = handler.handle("ListTagsForResource", p, "us-east-1");
assertEquals(404, response.getStatus());
assertTrue(((String) response.getEntity()).contains("CacheClusterNotFound"));
}
@Test
void listTagsForResource_clusterArnFromAnotherRegionIsNotThisCluster() {
// the store keys clusters by id alone, so a same-named cluster created under another
// region is not the one this ARN names
CacheCluster elsewhere = redisCacheCluster("tf-redis");
elsewhere.setArn("arn:aws:elasticache:eu-west-1:000000000000:cluster:tf-redis");
elsewhere.setTags(new LinkedHashMap<>(Map.of("Name", "west")));
when(service.findCacheClusters("tf-redis")).thenReturn(List.of(elsewhere));
MultivaluedMap<String, String> p = params();
p.add("ResourceName", "arn:aws:elasticache:us-east-1:000000000000:cluster:tf-redis");
Response response = handler.handle("ListTagsForResource", p, "us-east-1");
assertEquals(404, response.getStatus(), (String) response.getEntity());
assertFalse(((String) response.getEntity()).contains("west"));
}
@Test
void listTagsForResource_memcachedClusterArnStillAnswersWithNoTags() {
// Memcached clusters carry no tags but they do exist: this must not become a 404.
when(service.findCacheClusters("mc")).thenReturn(List.of());
when(service.listMemberCacheClusters("mc")).thenReturn(List.of());
when(memcachedService.getCacheCluster("mc")).thenReturn(new CacheCluster(
"mc", CacheClusterStatus.AVAILABLE, "memcached", "1.6.22",
new Endpoint("localhost", 11211), Instant.now()));
MultivaluedMap<String, String> p = params();
p.add("ResourceName", "arn:aws:elasticache:us-east-1:000000000000:cluster:mc");
Response response = handler.handle("ListTagsForResource", p, "us-east-1");
assertEquals(200, response.getStatus());
assertTrue(((String) response.getEntity()).contains("<TagList></TagList>"),
(String) response.getEntity());
}
}
@@ -0,0 +1,242 @@
package io.github.hectorvent.floci.services.elasticache;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* End-to-end coverage for a single-node redis cache cluster: the shape
* {@code aws_elasticache_cluster} with {@code engine = "redis"} creates, which AWS serves through
* CreateCacheCluster rather than CreateReplicationGroup. The node endpoint the describe reports
* has to speak RESP, which is what tells this apart from a metadata-only record.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ElastiCacheRedisClusterIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260412/us-east-1/elasticache/aws4_request";
private static final String CLUSTER_ID = "it-redis-single";
private static final int SOCKET_TIMEOUT_MS = 10_000;
private static String nodeHost;
private static int nodePort;
@BeforeAll
static void requireDocker() {
Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for ElastiCache integration tests");
}
@AfterAll
static void cleanup() {
try {
given()
.formParam("Action", "DeleteCacheCluster")
.formParam("CacheClusterId", CLUSTER_ID)
.header("Authorization", AUTH_HEADER)
.post("/");
} catch (Exception e) {
System.err.println("Cleanup of " + CLUSTER_ID + " failed: " + e.getMessage());
}
}
@Test
@Order(1)
void createSingleNodeRedisCacheCluster() {
given()
.formParam("Action", "CreateCacheCluster")
.formParam("CacheClusterId", CLUSTER_ID)
.formParam("Engine", "redis")
.formParam("EngineVersion", "7.1")
.formParam("NumCacheNodes", "1")
.formParam("CacheNodeType", "cache.t4g.micro")
.formParam("SnapshotRetentionLimit", "5")
.formParam("SnapshotWindow", "03:00-05:00")
.formParam("PreferredMaintenanceWindow", "tue:04:00-tue:05:00")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body("CreateCacheClusterResponse.CreateCacheClusterResult.CacheCluster.CacheClusterId", equalTo(CLUSTER_ID))
.body("CreateCacheClusterResponse.CreateCacheClusterResult.CacheCluster.CacheClusterStatus", equalTo("available"))
.body("CreateCacheClusterResponse.CreateCacheClusterResult.CacheCluster.Engine", equalTo("redis"))
.body("CreateCacheClusterResponse.CreateCacheClusterResult.CacheCluster.NumCacheNodes", equalTo("1"));
}
@Test
@Order(2)
void describeReportsTheClusterWithItsNodeEndpoint() {
XmlPath describe =
given()
.formParam("Action", "DescribeCacheClusters")
.formParam("CacheClusterId", CLUSTER_ID)
.formParam("ShowCacheNodeInfo", "true")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.Engine",
equalTo("redis"))
.body("DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.EngineVersion",
equalTo("7.1"))
.body("DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.CacheNodeType",
equalTo("cache.t4g.micro"))
.body("DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.CacheNodes.CacheNode.Endpoint.Address",
notNullValue())
// read back exactly as sent: an optional argument that comes back unset is a
// terraform diff that never settles
.body("DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.SnapshotRetentionLimit",
equalTo("5"))
.body("DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.SnapshotWindow",
equalTo("03:00-05:00"))
.body("DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.PreferredMaintenanceWindow",
equalTo("tue:04:00-tue:05:00"))
.extract()
.xmlPath();
nodeHost = describe.getString(
"DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.CacheNodes.CacheNode.Endpoint.Address");
nodePort = describe.getInt(
"DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.CacheNodes.CacheNode.Endpoint.Port");
}
@Test
@Order(3)
void theReportedNodeEndpointSpeaksResp() throws Exception {
try (Socket socket = openSocket(nodeHost, nodePort)) {
write(socket, respArray("PING"));
assertEquals("+PONG\r\n", readLine(socket));
write(socket, respArray("SET", "single-node-key", "a-value"));
assertEquals("+OK\r\n", readLine(socket));
write(socket, respArray("GET", "single-node-key"));
assertEquals("a-value", readBulk(socket));
}
}
@Test
@Order(4)
void moreThanOneNodeIsRefused() {
given()
.formParam("Action", "CreateCacheCluster")
.formParam("CacheClusterId", "it-redis-two-nodes")
.formParam("Engine", "redis")
.formParam("NumCacheNodes", "2")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
.body("ErrorResponse.Error.Message", equalTo("NumCacheNodes should be 1 if engine is redis"));
}
@Test
@Order(5)
void deleteCacheClusterRemovesItAndFreesTheEndpoint() {
given()
.formParam("Action", "DeleteCacheCluster")
.formParam("CacheClusterId", CLUSTER_ID)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DeleteCacheClusterResponse.DeleteCacheClusterResult.CacheCluster.CacheClusterId", equalTo(CLUSTER_ID));
given()
.formParam("Action", "DescribeCacheClusters")
.formParam("CacheClusterId", CLUSTER_ID)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.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);
socket.setSoTimeout(SOCKET_TIMEOUT_MS);
return socket;
}
private static void write(Socket socket, byte[] data) throws IOException {
OutputStream out = socket.getOutputStream();
out.write(data);
out.flush();
}
private static byte[] respArray(String... args) {
StringBuilder sb = new StringBuilder();
sb.append('*').append(args.length).append("\r\n");
for (String arg : args) {
byte[] bytes = arg.getBytes(StandardCharsets.UTF_8);
sb.append('$').append(bytes.length).append("\r\n").append(arg).append("\r\n");
}
return sb.toString().getBytes(StandardCharsets.UTF_8);
}
private static String readLine(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
StringBuilder sb = new StringBuilder();
int b;
while ((b = in.read()) != -1) {
sb.append((char) b);
if (sb.length() >= 2 && sb.charAt(sb.length() - 2) == '\r' && sb.charAt(sb.length() - 1) == '\n') {
return sb.toString();
}
}
throw new IOException("Connection closed before line terminator; read so far: " + sb);
}
private static String readBulk(Socket socket) throws IOException {
String header = readLine(socket);
if (!header.startsWith("$")) {
throw new IOException("Expected bulk reply but got: " + header);
}
int length = Integer.parseInt(header.substring(1).trim());
if (length < 0) {
return null;
}
InputStream in = socket.getInputStream();
byte[] data = in.readNBytes(length);
if (data.length != length) {
throw new IOException("Truncated bulk reply");
}
if (in.read() != '\r' || in.read() != '\n') {
throw new IOException("Missing CRLF after bulk reply");
}
return new String(data, StandardCharsets.UTF_8);
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.elasticache;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -10,9 +11,13 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerHandle;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheMemcachedContainerManager;
import io.github.hectorvent.floci.services.elasticache.container.ValkeyClusterFormation;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import io.github.hectorvent.floci.services.elasticache.model.CacheCluster;
import io.github.hectorvent.floci.services.elasticache.model.CacheClusterStatus;
import io.github.hectorvent.floci.services.elasticache.model.ClusterNode;
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupSettings;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupStatus;
@@ -24,6 +29,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -60,12 +66,17 @@ class ElastiCacheServiceTest {
private ElastiCacheProxyManager proxyManager;
private EmulatorConfig config;
private ValkeyClusterFormation clusterFormation;
private StorageFactory storageFactory;
private ElastiCacheMemcachedContainerManager memcachedContainerManager;
private Ec2Service ec2Service;
private ElastiCacheProvisioningIds provisioningIds;
@BeforeEach
void setUp() {
containerManager = mock(ElastiCacheContainerManager.class);
proxyManager = mock(ElastiCacheProxyManager.class);
StorageFactory storageFactory = mock(StorageFactory.class);
provisioningIds = new ElastiCacheProvisioningIds();
storageFactory = mock(StorageFactory.class);
config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class);
@@ -75,20 +86,28 @@ class ElastiCacheServiceTest {
when(ecConfig.proxyBasePort()).thenReturn(16379);
when(ecConfig.proxyMaxPort()).thenReturn(16399);
when(ecConfig.defaultImage()).thenReturn("valkey/valkey:8");
when(ecConfig.defaultMemcachedImage()).thenReturn("memcached:1.6");
when(config.hostname()).thenReturn(Optional.of("localhost"));
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
// Keyed by file name, as the real StorageFactory is: it hands the second caller of a path
// the first caller's backend, which is what lets the two services share one id namespace.
Map<String, AccountAwareStorageBackend<?>> backendsByFile = new ConcurrentHashMap<>();
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv ->
backendsByFile.computeIfAbsent(inv.getArgument(1),
file -> AccountAwareStorageBackend.inMemory("000000000000")));
memcachedContainerManager = mock(ElastiCacheMemcachedContainerManager.class);
when(memcachedContainerManager.tryStart(anyString(), anyString())).thenReturn(null);
when(containerManager.tryStart(anyString(), anyString()))
.thenReturn(new ElastiCacheContainerHandle("cid", "grp", "localhost", 6379));
doNothing().when(proxyManager).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
Ec2Service ec2Service = mock(Ec2Service.class);
ec2Service = mock(Ec2Service.class);
kmsService = mock(KmsService.class);
when(kmsService.describeKey(any(), any())).thenThrow(
new AwsException("NotFoundException", "Key not found", 404));
clusterFormation = mock(ValkeyClusterFormation.class);
service = new ElastiCacheService(containerManager, proxyManager, clusterFormation,
storageFactory, config, ec2Service, new RegionResolver("us-east-1", "000000000000"),
kmsService);
kmsService, provisioningIds);
}
@Test
@@ -116,7 +135,7 @@ class ElastiCacheServiceTest {
ElastiCacheService svc = new ElastiCacheService(cm, pm, mock(ValkeyClusterFormation.class),
sf, cfg, mock(Ec2Service.class),
new RegionResolver("us-east-1", "000000000000"),
mock(KmsService.class));
mock(KmsService.class), provisioningIds);
svc.createReplicationGroup("g1", "d", AuthMode.PASSWORD, null, "us-east-1");
@@ -474,7 +493,7 @@ class ElastiCacheServiceTest {
when(config.hostname()).thenReturn(Optional.of("localhost"));
return new ElastiCacheService(containerManager, proxyManager, clusterFormation,
storageFactory, config, mock(Ec2Service.class),
new RegionResolver("us-east-1", "000000000000"), mock(KmsService.class));
new RegionResolver("us-east-1", "000000000000"), mock(KmsService.class), new ElastiCacheProvisioningIds());
}
private static void stubPerNodeContainers(ElastiCacheContainerManager containerManager) {
@@ -874,7 +893,7 @@ class ElastiCacheServiceTest {
.thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
ElastiCacheService svc = new ElastiCacheService(containerManager, proxyManager, clusterFormation,
factory, config, mock(Ec2Service.class),
new RegionResolver("us-east-1", "000000000000"), kmsService);
new RegionResolver("us-east-1", "000000000000"), kmsService, provisioningIds);
svc.createReplicationGroup("g1", "d", AuthMode.NO_AUTH, null, "us-east-1");
pausing.pauseOn(PausingStorageBackend.Call.PUT, "g1");
@@ -993,7 +1012,7 @@ class ElastiCacheServiceTest {
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), requestContextInstance, "000000000000"));
ElastiCacheService svc = new ElastiCacheService(containerManager, proxyManager, clusterFormation,
factory, config, mock(Ec2Service.class),
new RegionResolver("us-east-1", "000000000000"), kmsService);
new RegionResolver("us-east-1", "000000000000"), kmsService, provisioningIds);
CountDownLatch startedLatch = new CountDownLatch(1);
CountDownLatch releaseLatch = new CountDownLatch(1);
@@ -1054,4 +1073,638 @@ class ElastiCacheServiceTest {
service.deleteCacheParameterGroup("custom-pg");
assertTrue(service.findParameterGroup("custom-pg").isEmpty());
}
// ── CreateCacheCluster: single-node redis/valkey ──────────────────────────
private static ElastiCacheService.CreateCacheClusterRequest cacheClusterRequest(
String clusterId, String engine, Integer numCacheNodes) {
return cacheClusterRequest(clusterId, engine, numCacheNodes, AuthMode.NO_AUTH, null, null);
}
private static ElastiCacheService.CreateCacheClusterRequest cacheClusterRequest(
String clusterId, String engine, Integer numCacheNodes, AuthMode authMode,
String authToken, String parameterGroupName) {
return new ElastiCacheService.CreateCacheClusterRequest(clusterId, engine, null, null,
numCacheNodes, null, authMode, authToken, parameterGroupName, null,
null, null, null, null, null, null, null, null, "us-east-1", Map.of());
}
@Test
void singleNodeRedisClusterIsBackedByAValkeyContainerBehindAProxy() {
// The point of the path: terraform's aws_elasticache_cluster with engine "redis" sends
// this call, and the endpoint it reads back has to answer. That means a container and a
// proxy on the port the describe reports, not a metadata-only record.
CacheCluster cluster = service.createCacheCluster(cacheClusterRequest("tf-redis", "redis", 1));
assertEquals("redis", cluster.getEngine());
assertEquals("7.1", cluster.getEngineVersion());
assertEquals("cache.t4g.micro", cluster.getCacheNodeType());
assertEquals(1, cluster.getNumCacheNodes());
assertEquals(CacheClusterStatus.AVAILABLE, cluster.getCacheClusterStatus());
assertEquals("localhost", cluster.getConfigurationEndpoint().address());
assertEquals(16379, cluster.getConfigurationEndpoint().port());
assertEquals("arn:aws:elasticache:us-east-1:000000000000:cluster:tf-redis", cluster.getArn());
verify(containerManager).tryStart(eq("tf-redis"), eq("valkey/valkey:8"));
verify(proxyManager).startProxy(eq("tf-redis"), eq(AuthMode.NO_AUTH), eq(16379),
eq("localhost"), eq(6379), any());
// read back through a separate call, not the create's own return value
assertEquals("tf-redis", service.findCacheClusters("tf-redis").getFirst().getCacheClusterId());
}
@Test
void valkeyCacheClusterTakesTheValkeyEngineVersionDefault() {
assertEquals("8.1", service.createCacheCluster(cacheClusterRequest("tf-valkey", "valkey", null))
.getEngineVersion());
}
@Test
void redisCacheClusterWithMoreThanOneNodeIsRefusedAsOnAws() {
AwsException ex = assertThrows(AwsException.class,
() -> service.createCacheCluster(cacheClusterRequest("too-big", "redis", 2)));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals("NumCacheNodes should be 1 if engine is redis", ex.getMessage());
verify(containerManager, never()).tryStart(eq("too-big"), anyString());
assertTrue(service.findCacheClusters("too-big").isEmpty());
}
@Test
void duplicateCacheClusterIdIsRefused() {
service.createCacheCluster(cacheClusterRequest("dupe", "redis", 1));
AwsException ex = assertThrows(AwsException.class,
() -> service.createCacheCluster(cacheClusterRequest("dupe", "redis", 1)));
// botocore elasticache/2015-02-02 codes this CacheClusterAlreadyExists: the Fault suffix
// is the shape name, not the wire code, and an SDK matches on the code.
assertEquals("CacheClusterAlreadyExists", ex.getErrorCode());
}
@Test
void deletingACacheClusterStopsItsProxyAndContainerAndFreesThePort() {
service.createCacheCluster(cacheClusterRequest("cc", "redis", 1));
service.deleteCacheCluster("cc");
verify(proxyManager).stopProxy("cc");
verify(containerManager).stop(any());
assertTrue(service.findCacheClusters("cc").isEmpty());
assertEquals("CacheClusterNotFound",
assertThrows(AwsException.class, () -> service.deleteCacheCluster("cc")).getErrorCode());
// the freed proxy port goes to the next cluster rather than being leaked
assertEquals(16379, service.createCacheCluster(cacheClusterRequest("cc2", "redis", 1))
.getConfigurationEndpoint().port());
}
@Test
void aCacheClusterAndAReplicationGroupNeverShareAProxyPort() {
service.createReplicationGroup("grp", "d", AuthMode.NO_AUTH, null, "us-east-1");
assertEquals(16380, service.createCacheCluster(cacheClusterRequest("cc", "redis", 1))
.getConfigurationEndpoint().port());
}
@Test
void aCacheClusterHoldsItsParameterGroupAgainstDeletion() {
service.createCacheParameterGroup("cc-pg", "redis7", "in use", Map.of());
service.createCacheCluster(
cacheClusterRequest("cc", "redis", 1, AuthMode.NO_AUTH, null, "cc-pg"));
assertEquals("InvalidCacheParameterGroupState",
assertThrows(AwsException.class, () -> service.deleteCacheParameterGroup("cc-pg"))
.getErrorCode());
}
@Test
void anAuthTokenOnACacheClusterIsValidatedAgainstThatClusterAlone() {
service.createCacheCluster(
cacheClusterRequest("auth-cc", "redis", 1, AuthMode.PASSWORD, "s3cret-token", null));
assertTrue(service.validateCacheClusterPassword("auth-cc", null, "s3cret-token"));
assertFalse(service.validateCacheClusterPassword("auth-cc", null, "wrong"));
assertFalse(service.validateCacheClusterPassword("other-cc", null, "s3cret-token"));
}
@Test
void aCacheClusterCannotTakeTheIdOfALiveReplicationGroup() {
// Not a cosmetic clash. Both name their container valkey-<id> and register their proxy
// under the id, so letting this through would have ElastiCacheContainerManager.start
// removeIfExists the group's running container and the proxy registry overwrite its
// entry, leaving a listener bound that nothing can stop.
service.createReplicationGroup("shared", "d", AuthMode.NO_AUTH, null, "us-east-1");
AwsException ex = assertThrows(AwsException.class,
() -> service.createCacheCluster(cacheClusterRequest("shared", "redis", 1)));
assertEquals("CacheClusterAlreadyExists", ex.getErrorCode());
// the live group kept its container and its proxy: nothing was started or removed for the
// refused request
verify(containerManager, times(1)).tryStart(eq("shared"), anyString());
verify(containerManager, never()).stopByGroupId("shared");
verify(proxyManager, times(1)).startProxy(eq("shared"), any(), anyInt(), anyString(), anyInt(), any());
assertEquals("shared", service.getReplicationGroup("shared").getReplicationGroupId());
}
@Test
void aReplicationGroupCannotTakeTheIdOfALiveCacheCluster() {
service.createCacheCluster(cacheClusterRequest("shared", "redis", 1));
AwsException ex = assertThrows(AwsException.class,
() -> service.createReplicationGroup("shared", "d", AuthMode.NO_AUTH, null, "us-east-1"));
assertEquals("ReplicationGroupAlreadyExistsFault", ex.getErrorCode());
verify(containerManager, times(1)).tryStart(eq("shared"), anyString());
verify(containerManager, never()).stopByGroupId("shared");
assertEquals("shared", service.findCacheClusters("shared").getFirst().getCacheClusterId());
}
@Test
void twoConcurrentCreatesOfOneIdCannotBothProvisionIt() throws Exception {
// The stored-record check alone cannot separate them: neither create has stored anything
// while the other is inside tryStart, so both would pass it, and the loser's rollback
// would stopByGroupId the winner's container out from under it.
CountDownLatch startedLatch = new CountDownLatch(1);
CountDownLatch releaseLatch = new CountDownLatch(1);
when(containerManager.tryStart(eq("raced"), anyString())).thenAnswer(inv -> {
startedLatch.countDown();
assertTrue(releaseLatch.await(5, TimeUnit.SECONDS), "test timed out waiting for release");
return new ElastiCacheContainerHandle("cid", "raced", "localhost", 6379);
});
Thread winner = new Thread(() -> service.createCacheCluster(cacheClusterRequest("raced", "redis", 1)));
winner.start();
assertTrue(startedLatch.await(5, TimeUnit.SECONDS), "create never reached container start");
AwsException ex = assertThrows(AwsException.class,
() -> service.createCacheCluster(cacheClusterRequest("raced", "redis", 1)));
assertEquals("CacheClusterAlreadyExists", ex.getErrorCode());
// the loser must not have reached for the container the winner is still starting
verify(containerManager, never()).stopByGroupId("raced");
releaseLatch.countDown();
winner.join(5000);
assertEquals("raced", service.findCacheClusters("raced").getFirst().getCacheClusterId());
verify(containerManager, times(1)).tryStart(eq("raced"), anyString());
}
@Test
void aReplicationGroupCreateIsBlockedByAnInFlightCacheClusterCreateOfThatId() throws Exception {
CountDownLatch startedLatch = new CountDownLatch(1);
CountDownLatch releaseLatch = new CountDownLatch(1);
when(containerManager.tryStart(eq("raced"), anyString())).thenAnswer(inv -> {
startedLatch.countDown();
assertTrue(releaseLatch.await(5, TimeUnit.SECONDS), "test timed out waiting for release");
return new ElastiCacheContainerHandle("cid", "raced", "localhost", 6379);
});
Thread cacheCluster = new Thread(() -> service.createCacheCluster(cacheClusterRequest("raced", "redis", 1)));
cacheCluster.start();
assertTrue(startedLatch.await(5, TimeUnit.SECONDS), "create never reached container start");
assertEquals("ReplicationGroupAlreadyExistsFault",
assertThrows(AwsException.class, () -> service.createReplicationGroup(
"raced", "d", AuthMode.NO_AUTH, null, "us-east-1")).getErrorCode());
verify(containerManager, never()).stopByGroupId("raced");
releaseLatch.countDown();
cacheCluster.join(5000);
}
@Test
void theOptionalMembersARequestCarriesAreStoredAndTheRestDefaulted() {
// Every one of these is an optional aws_elasticache_cluster argument. Dropping any of them
// reads back as unset on the next plan, which is a diff terraform can never settle.
CacheCluster cluster = service.createCacheCluster(new ElastiCacheService.CreateCacheClusterRequest(
"settings-cc", "redis", null, null, 1, null, AuthMode.NO_AUTH, null, null, null,
5, "03:00-05:00", "Tue:04:00-Tue:05:00", "us-east-1b", List.of("sg-123"),
"ipv4", "ipv4", true, "us-east-1", Map.of()));
assertEquals(5, cluster.getSnapshotRetentionLimit());
assertEquals("03:00-05:00", cluster.getSnapshotWindow());
assertEquals("tue:04:00-tue:05:00", cluster.getPreferredMaintenanceWindow());
assertEquals("us-east-1b", cluster.getPreferredAvailabilityZone());
assertEquals(List.of("sg-123"), cluster.getSecurityGroupIds());
assertTrue(cluster.isAtRestEncryptionEnabled());
// and a request that carries none of them still reads back concrete values, not zeroes
CacheCluster bare = service.createCacheCluster(cacheClusterRequest("bare-cc", "redis", 1));
assertEquals(0, bare.getSnapshotRetentionLimit());
assertEquals("00:00-01:00", bare.getSnapshotWindow());
assertEquals("mon:00:00-mon:03:00", bare.getPreferredMaintenanceWindow());
assertEquals("us-east-1a", bare.getPreferredAvailabilityZone());
assertEquals("ipv4", bare.getNetworkType());
assertEquals("ipv4", bare.getIpDiscovery());
assertFalse(bare.isAtRestEncryptionEnabled());
}
@Test
void theSnapshotMembersTakeTheReplicationGroupsChecks() {
AwsException ex = assertThrows(AwsException.class,
() -> service.createCacheCluster(new ElastiCacheService.CreateCacheClusterRequest(
"bad-cc", "redis", null, null, 1, null, AuthMode.NO_AUTH, null, null, null,
99, null, null, null, null, null, null, null, "us-east-1", Map.of())));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertTrue(ex.getMessage().contains("Retention limit must be between 0 and 35"), ex.getMessage());
assertEquals("InvalidParameterValue",
assertThrows(AwsException.class,
() -> service.createCacheCluster(new ElastiCacheService.CreateCacheClusterRequest(
"bad-cc", "redis", null, null, 1, null, AuthMode.NO_AUTH, null, null, null,
null, null, "notaday:04:00-notaday:05:00", null, null, null, null, null,
"us-east-1", Map.of()))).getErrorCode());
// a refused request provisions nothing
verify(containerManager, never()).tryStart(eq("bad-cc"), anyString());
assertTrue(service.findCacheClusters("bad-cc").isEmpty());
}
@Test
void aStandaloneClusterIsListedAsAnExplorerResource() {
service.createCacheCluster(cacheClusterRequest("explorer-cc", "redis", 1));
assertTrue(service.getResources().stream().anyMatch(r ->
"arn:aws:elasticache:us-east-1:000000000000:cluster:explorer-cc".equals(r.arn())),
"the standalone cluster must appear in the resource explorer alongside groups");
}
/** A second service over the same stores: what a restart leaves behind, minus the runtime. */
private ElastiCacheService serviceAfterRestart() {
return new ElastiCacheService(containerManager, proxyManager, clusterFormation,
storageFactory, config, ec2Service, new RegionResolver("us-east-1", "000000000000"),
kmsService, provisioningIds);
}
private ElastiCacheMemcachedService memcachedService() {
return new ElastiCacheMemcachedService(memcachedContainerManager, storageFactory, config, provisioningIds);
}
@Test
void aPersistedClusterKeepsItsPortAcrossARestart() {
// Before this, nothing re-added the port to usedPorts on startup: the restored cluster
// went on advertising 16379 while the next create was handed the same 16379, and the
// first delete then freed the second cluster's reservation.
assertEquals(16379, service.createCacheCluster(cacheClusterRequest("persisted", "redis", 1))
.getConfigurationEndpoint().port());
ElastiCacheService restarted = serviceAfterRestart();
restarted.restorePersistedRuntime().join();
assertEquals(16380, restarted.createCacheCluster(cacheClusterRequest("after", "redis", 1))
.getConfigurationEndpoint().port());
assertEquals(16379, restarted.findCacheClusters("persisted").getFirst()
.getConfigurationEndpoint().port());
}
private static StorageFactory storageWithStandaloneCluster(String clusterId) {
StorageFactory storageFactory = sharedStorageFactory();
ElastiCacheContainerManager beforeRestart = mock(ElastiCacheContainerManager.class);
stubSingleNodeContainer(beforeRestart);
serviceWith(storageFactory, beforeRestart, mock(ElastiCacheProxyManager.class),
mock(ValkeyClusterFormation.class))
.createCacheCluster(cacheClusterRequest(clusterId, "redis", 1, AuthMode.PASSWORD,
"a-long-enough-auth-token", null));
return storageFactory;
}
@Test
void restorePersistedRuntimeReprovisionsStandaloneCacheClusters() {
// The shape aws_elasticache_cluster actually creates. Left unrestored it is the exact
// state #4094 fixed for every other shape: available with nothing behind the endpoint.
StorageFactory storageFactory = storageWithStandaloneCluster("tf-redis");
ElastiCacheContainerManager restartedContainers = mock(ElastiCacheContainerManager.class);
stubSingleNodeContainer(restartedContainers);
ElastiCacheProxyManager restartedProxies = mock(ElastiCacheProxyManager.class);
ElastiCacheService restarted = serviceWith(storageFactory, restartedContainers,
restartedProxies, mock(ValkeyClusterFormation.class));
restarted.restorePersistedRuntime().join();
verify(restartedContainers).tryStart(eq("tf-redis"), anyString());
verify(restartedProxies).startProxy(eq("tf-redis"), eq(AuthMode.PASSWORD), eq(16379),
eq("localhost"), eq(6379), any());
CacheCluster restored = restarted.findCacheClusters("tf-redis").getFirst();
assertEquals(CacheClusterStatus.AVAILABLE, restored.getCacheClusterStatus());
assertEquals(16379, restored.getConfigurationEndpoint().port());
assertEquals("cid-tf-redis", restored.getContainerId(),
"A restored cluster must track the container it actually has");
}
@Test
void standaloneClusterRestoreFailureReportsRestoreFailedAndReleasesThePort() {
StorageFactory storageFactory = storageWithStandaloneCluster("tf-redis");
ElastiCacheContainerManager restartedContainers = mock(ElastiCacheContainerManager.class);
// Only the restore fails: the create that checks the port was freed must still get through.
when(restartedContainers.tryStart(eq("tf-redis"), anyString()))
.thenThrow(new RuntimeException("container failed"));
ElastiCacheProxyManager restartedProxies = mock(ElastiCacheProxyManager.class);
ElastiCacheService restarted = serviceWith(storageFactory, restartedContainers,
restartedProxies, mock(ValkeyClusterFormation.class));
restarted.restorePersistedRuntime().join();
CacheCluster failed = restarted.findCacheClusters("tf-redis").getFirst();
assertEquals(CacheClusterStatus.RESTORE_FAILED, failed.getCacheClusterStatus(),
"restore-failed is the value CacheClusterStatus models; create-failed is not");
assertNull(failed.getConfigurationEndpoint(),
"A cluster whose data plane is gone must not advertise an endpoint");
verify(restartedProxies, never()).startProxy(anyString(), any(), anyInt(), anyString(),
anyInt(), any());
CacheCluster next = restarted.createCacheCluster(cacheClusterRequest("next", "redis", 1));
assertEquals(16379, next.getConfigurationEndpoint().port(),
"The failed restore's port must be released for the next cluster");
}
@Test
void standaloneClusterRestoreWithoutADockerDaemonKeepsTheClusterAvailable() {
StorageFactory storageFactory = storageWithStandaloneCluster("tf-redis");
ElastiCacheContainerManager restartedContainers = mock(ElastiCacheContainerManager.class);
when(restartedContainers.tryStart(anyString(), anyString())).thenReturn(null);
ElastiCacheProxyManager restartedProxies = mock(ElastiCacheProxyManager.class);
ElastiCacheService restarted = serviceWith(storageFactory, restartedContainers,
restartedProxies, mock(ValkeyClusterFormation.class));
restarted.restorePersistedRuntime().join();
CacheCluster restored = restarted.findCacheClusters("tf-redis").getFirst();
assertEquals(CacheClusterStatus.AVAILABLE, restored.getCacheClusterStatus(),
"No reachable daemon is the create path's documented degraded mode, not a failure");
assertNull(restored.getContainerId());
verify(restartedProxies, never()).startProxy(anyString(), any(), anyInt(), anyString(),
anyInt(), any());
}
@Test
void restorePersistedRuntimeSkipsStandaloneClustersBeingDeleted() {
StorageFactory storageFactory = storageWithStandaloneCluster("tf-redis");
ElastiCacheContainerManager beforeRestart = mock(ElastiCacheContainerManager.class);
stubSingleNodeContainer(beforeRestart);
ElastiCacheService before = serviceWith(storageFactory, beforeRestart,
mock(ElastiCacheProxyManager.class), mock(ValkeyClusterFormation.class));
// The in-memory backend hands back the stored instance, so this is the persisted record.
before.findCacheClusters("tf-redis").getFirst()
.setCacheClusterStatus(CacheClusterStatus.DELETING);
ElastiCacheContainerManager restartedContainers = mock(ElastiCacheContainerManager.class);
stubSingleNodeContainer(restartedContainers);
ElastiCacheService restarted = serviceWith(storageFactory, restartedContainers,
mock(ElastiCacheProxyManager.class), mock(ValkeyClusterFormation.class));
restarted.restorePersistedRuntime().join();
verify(restartedContainers, never()).tryStart(anyString(), anyString());
assertEquals(CacheClusterStatus.DELETING,
restarted.findCacheClusters("tf-redis").getFirst().getCacheClusterStatus());
}
@Test
void restoreDoesNotResurrectAStandaloneClusterDeletedWhileItWasRestoring() {
StorageFactory storageFactory = storageWithStandaloneCluster("tf-redis");
ElastiCacheContainerManager restartedContainers = mock(ElastiCacheContainerManager.class);
ElastiCacheProxyManager restartedProxies = mock(ElastiCacheProxyManager.class);
ElastiCacheService restarted = serviceWith(storageFactory, restartedContainers,
restartedProxies, mock(ValkeyClusterFormation.class));
ElastiCacheContainerHandle restoredHandle =
new ElastiCacheContainerHandle("cid-restored", "tf-redis", "localhost", 6379);
// The delete lands in the window the cluster's monitor closes: the container is up, the
// record has not been written back yet.
when(restartedContainers.tryStart(eq("tf-redis"), anyString())).thenAnswer(inv -> {
restarted.deleteCacheCluster("tf-redis");
// Takes the port that delete just freed, so a restore that released it a second
// time would hand the same port out twice.
restarted.createCacheCluster(cacheClusterRequest("after", "redis", 1));
return restoredHandle;
});
restarted.restorePersistedRuntime().join();
assertTrue(restarted.findCacheClusters("tf-redis").isEmpty(),
"A cluster deleted while it was restoring must stay deleted");
verify(restartedProxies, never()).startProxy(eq("tf-redis"), any(), anyInt(), anyString(),
anyInt(), any());
verify(restartedContainers).stop(restoredHandle);
CacheCluster next = restarted.createCacheCluster(cacheClusterRequest("third", "redis", 1));
assertEquals(16380, next.getConfigurationEndpoint().port(),
"The abandoned restore must leave 'after' holding the port the delete released");
}
@Test
void deletingARestoredClusterFreesThePortItActuallyHolds() {
service.createCacheCluster(cacheClusterRequest("persisted", "redis", 1));
ElastiCacheService restarted = serviceAfterRestart();
restarted.restorePersistedRuntime().join();
restarted.createCacheCluster(cacheClusterRequest("after", "redis", 1));
restarted.deleteCacheCluster("persisted");
// 16379 is free again because that record owned it; 16380 is still the other cluster's
assertEquals(16379, restarted.createCacheCluster(cacheClusterRequest("third", "redis", 1))
.getConfigurationEndpoint().port());
assertEquals(16380, restarted.findCacheClusters("after").getFirst()
.getConfigurationEndpoint().port());
}
@Test
void deletingARecordThatNeverHeldItsPortDoesNotFreeTheHoldersPort() {
// Two records advertising one port: only one can hold it. Here the holder is the created
// cluster and the other record never reserved anything, so its delete must leave the
// reservation alone rather than hand a live cluster's port to the next create.
service.createCacheCluster(cacheClusterRequest("holder", "redis", 1));
AccountAwareStorageBackend<CacheCluster> store = storageFactory.create("elasticache",
"elasticache-redis-clusters.json", new TypeReference<Map<String, CacheCluster>>() {});
store.put("squatter", new CacheCluster("squatter", CacheClusterStatus.AVAILABLE, "redis",
"7.1", new Endpoint("localhost", 16379), Instant.now()));
service.deleteCacheCluster("squatter");
assertEquals(16380, service.createCacheCluster(cacheClusterRequest("next", "redis", 1))
.getConfigurationEndpoint().port(),
"16379 is still held by the cluster that actually reserved it");
}
@Test
void deletingAGroupThatNeverHeldItsPortDoesNotFreeTheHoldersPort() {
// The same asymmetry on the replication-group side: a group written straight into the
// store advertises 16379 without ever reserving it, so its delete must not free the
// reservation the cluster is holding.
service.createCacheCluster(cacheClusterRequest("holder", "redis", 1));
AccountAwareStorageBackend<ReplicationGroup> store = storageFactory.create("elasticache",
"elasticache-groups.json", new TypeReference<Map<String, ReplicationGroup>>() {});
store.put("squatter", new ReplicationGroup("squatter", "d", ReplicationGroupStatus.AVAILABLE,
AuthMode.NO_AUTH, new Endpoint("localhost", 16379), Instant.now(), 16379));
service.deleteReplicationGroup("squatter");
assertEquals(16380, service.createCacheCluster(cacheClusterRequest("next", "redis", 1))
.getConfigurationEndpoint().port(),
"16379 is still held by the cluster that actually reserved it");
}
@Test
void deletingAGroupCreatedInProcessFreesItsPort() {
// The ordinary path, which the squatter and restored-group tests both step around: a
// group created here holds its port, so its delete has to give it back.
service.createReplicationGroup("grp", "d", AuthMode.NO_AUTH, null, "us-east-1");
service.deleteReplicationGroup("grp");
assertEquals(16379, service.createCacheCluster(cacheClusterRequest("next", "redis", 1))
.getConfigurationEndpoint().port());
}
@Test
void deletingARestoredGroupFreesThePortItActuallyHolds() {
service.createReplicationGroup("persisted", "d", AuthMode.NO_AUTH, null, "us-east-1");
ElastiCacheService restarted = serviceAfterRestart();
restarted.restorePersistedRuntime().join();
restarted.createCacheCluster(cacheClusterRequest("after", "redis", 1));
restarted.deleteReplicationGroup("persisted");
// 16379 is free again because that group owned it; 16380 is still the cluster's.
assertEquals(16379, restarted.createCacheCluster(cacheClusterRequest("third", "redis", 1))
.getConfigurationEndpoint().port());
}
@Test
void aReplicationGroupCannotTakeTheIdOfAMemcachedCluster() {
// The third store counts too: CreateReplicationGroup would otherwise name a group after
// a live memcached cluster and take over its container and proxy registration.
memcachedService().createCacheCluster("shared-id");
AwsException ex = assertThrows(AwsException.class, () -> service.createReplicationGroup(
"shared-id", "d", AuthMode.NO_AUTH, null, "us-east-1"));
assertEquals("ReplicationGroupAlreadyExistsFault", ex.getErrorCode());
verify(containerManager, never()).tryStart(eq("shared-id"), anyString());
}
@Test
void aPersistedReplicationGroupAlsoKeepsItsPortAcrossARestart() {
service.createReplicationGroup("grp", "d", AuthMode.NO_AUTH, null, "us-east-1");
ElastiCacheService restarted = serviceAfterRestart();
restarted.restorePersistedRuntime().join();
assertEquals(16380, restarted.createCacheCluster(cacheClusterRequest("after", "redis", 1))
.getConfigurationEndpoint().port());
}
@Test
void aCacheClusterCannotTakeTheIdOfAMemcachedCluster() {
// One namespace: DescribeCacheClusters answers from every store, so two records sharing
// an id would have it reported twice, each with a different engine.
memcachedService().createCacheCluster("shared-id");
AwsException ex = assertThrows(AwsException.class,
() -> service.createCacheCluster(cacheClusterRequest("shared-id", "redis", 1)));
assertEquals("CacheClusterAlreadyExists", ex.getErrorCode());
verify(containerManager, never()).tryStart(eq("shared-id"), anyString());
}
@Test
void aMemcachedClusterCannotTakeTheIdOfARedisClusterOrAGroup() {
ElastiCacheMemcachedService memcached = memcachedService();
service.createCacheCluster(cacheClusterRequest("redis-id", "redis", 1));
service.createReplicationGroup("group-id", "d", AuthMode.NO_AUTH, null, "us-east-1");
assertEquals("CacheClusterAlreadyExists",
assertThrows(AwsException.class, () -> memcached.createCacheCluster("redis-id"))
.getErrorCode());
assertEquals("CacheClusterAlreadyExists",
assertThrows(AwsException.class, () -> memcached.createCacheCluster("group-id"))
.getErrorCode());
verify(memcachedContainerManager, never()).tryStart(eq("redis-id"), anyString());
verify(memcachedContainerManager, never()).tryStart(eq("group-id"), anyString());
}
@Test
void aMemcachedCreateIsRefusedWhileAReplicationGroupCreateHoldsTheSameIdInFlight()
throws InterruptedException {
// The stores were the only thing the memcached path consulted, and neither path writes
// its record until its container has started. Held in that window, a group create and a
// memcached create for one id both saw three empty stores and both went on to write,
// leaving the id in two stores with one describe reporting it twice.
ElastiCacheMemcachedService memcached = memcachedService();
CountDownLatch startedLatch = new CountDownLatch(1);
CountDownLatch releaseLatch = new CountDownLatch(1);
when(containerManager.tryStart(anyString(), anyString())).thenAnswer(inv -> {
startedLatch.countDown();
assertTrue(releaseLatch.await(5, TimeUnit.SECONDS), "test timed out waiting for release");
return new ElastiCacheContainerHandle("cid", "grp", "localhost", 6379);
});
Thread groupCreate = new Thread(() ->
service.createReplicationGroup("shared-id", "d", AuthMode.NO_AUTH, null, "us-east-1"));
groupCreate.start();
assertTrue(startedLatch.await(5, TimeUnit.SECONDS), "create never reached container start");
AwsException ex = assertThrows(AwsException.class,
() -> memcached.createCacheCluster("shared-id"));
assertEquals("CacheClusterAlreadyExists", ex.getErrorCode());
verify(memcachedContainerManager, never()).tryStart(eq("shared-id"), anyString());
releaseLatch.countDown();
groupCreate.join(5000);
// One record for the id, in the store the winning create writes.
assertEquals("shared-id", service.getReplicationGroup("shared-id").getReplicationGroupId());
assertTrue(memcached.listCacheClusters(null).isEmpty(),
"the refused memcached create must not have written a second record for the id");
}
@Test
void anUnknownCacheSubnetGroupIsRefused() {
AwsException ex = assertThrows(AwsException.class,
() -> service.createCacheCluster(new ElastiCacheService.CreateCacheClusterRequest(
"sng-cc", "redis", null, null, 1, null, AuthMode.NO_AUTH, null, null,
"no-such-group", null, null, null, null, null, null, null, null,
"us-east-1", Map.of())));
assertEquals("CacheSubnetGroupNotFoundFault", ex.getErrorCode());
// and nothing was provisioned against the name that does not resolve
verify(containerManager, never()).tryStart(eq("sng-cc"), anyString());
assertTrue(service.findCacheClusters("sng-cc").isEmpty());
}
@Test
void aKnownCacheSubnetGroupIsAcceptedAndReported() {
io.github.hectorvent.floci.services.ec2.model.Subnet subnet =
new io.github.hectorvent.floci.services.ec2.model.Subnet();
subnet.setSubnetId("subnet-1");
subnet.setVpcId("vpc-1");
subnet.setAvailabilityZone("us-east-1a");
when(ec2Service.describeSubnets(anyString(), any(), any())).thenReturn(List.of(subnet));
service.createCacheSubnetGroup("real-group", "d", List.of("subnet-1"), Map.of());
CacheCluster cluster = service.createCacheCluster(new ElastiCacheService.CreateCacheClusterRequest(
"sng-cc", "redis", null, null, 1, null, AuthMode.NO_AUTH, null, null,
"real-group", null, null, null, null, null, null, null, null,
"us-east-1", Map.of()));
assertEquals("real-group", cluster.getCacheSubnetGroupName());
}
@Test
void aCacheClusterCreatedWithoutDockerStillReachesAvailable() {
when(containerManager.tryStart(anyString(), anyString())).thenReturn(null);
CacheCluster cluster = service.createCacheCluster(cacheClusterRequest("no-docker", "redis", 1));
assertEquals(CacheClusterStatus.AVAILABLE, cluster.getCacheClusterStatus());
verify(proxyManager, never()).startProxy(eq("no-docker"), any(), anyInt(), anyString(), anyInt(), any());
// delete must not reach for a container that was never created
service.deleteCacheCluster("no-docker");
verify(containerManager, never()).stop(any());
verify(containerManager).stopByGroupId("no-docker");
}
}