feat(elasticache): support cluster-mode replication groups (#2633)

* feat(elasticache): support cluster-mode replication groups

CreateReplicationGroup now provisions a real sharded Valkey cluster when
the request asks for one (NumNodeGroups > 1, a cluster.on parameter
group, or ClusterMode=enabled): one cluster-enabled container per node,
formed via config epochs, MEET, slot assignment and replica attachment,
each fronted by its own auth-proxy port announced to clients via
cluster-announce-client-ipv4/cluster-announce-port so CLUSTER SLOTS and
MOVED redirects point at reachable addresses.

DescribeReplicationGroups reports the topology honestly (ClusterEnabled,
NodeGroups with Slots, MemberClusters, Engine, ARN, AutomaticFailover),
and replication-group members answer DescribeCacheClusters, which is
where terraform-provider-aws reads node type, engine version and port
from.

Adds a terraform compatibility test that applies an
aws_elasticache_replication_group with num_node_groups and
replicas_per_node_group, asserts the data plane is a formed cluster
running in cluster mode (INFO cluster / CLUSTER INFO over RESP through
the proxy), and that a re-plan straight after apply is clean.

* fix(elasticache): address cluster-mode review feedback and compat CI failure

- bump compat-terraform aws-cli image to 2.34.32 so botocore models
  include ReplicationGroup.Engine (old pin silently dropped the field)
- restore cluster-mode runtime state (ports, containers, proxies,
  cluster formation) after restart; mark groups create-failed on error
- announce configured hostname to Valkey nodes so MOVED redirects and
  CLUSTER SLOTS return client-reachable endpoints
- log swallowed socket-close failures in cluster formation

* fix(elasticache): report restore-failed members and modeled node-group quota fault

Review follow-up for cluster-mode support:

- Member cache clusters mirror their group's status instead of a
  hardcoded "available", so a group marked create-failed by a failed
  restore no longer contradicts its own members in
  DescribeCacheClusters. CacheClusterStatus has no create-failed value,
  so failed members report the documented restore-failed.
- NumNodeGroups above the 500 ceiling surfaces the modeled
  NodeGroupsPerReplicationGroupQuotaExceeded fault instead of a generic
  InvalidParameterValue.
- Javadoc names ClusterMode=compatible handling and the
  cluster-mode-only restore scope as deliberate.

* fix(elasticache): announce a client-resolvable hostname for cluster mode

Cluster-mode nodes announced FLOCI_HOSTNAME verbatim, so the shipped
Docker Compose deployment baked the Compose-only name 'floci' into
MOVED/ASK redirects and topology responses, breaking cluster-aware
clients connecting from outside the Compose network.

Add FLOCI_SERVICES_ELASTICACHE_CLUSTER_ANNOUNCE_HOSTNAME (default:
FLOCI_HOSTNAME) used for the announced name and the reported
ConfigurationEndpoint, and set it to localhost.floci.io in
docker-compose.yml — public DNS resolves it to 127.0.0.1 on the host
while the network alias and Floci's embedded DNS resolve it to the
Floci container from inside Docker.

* fix(elasticache): restore cluster-mode groups without blocking startup

Restoring persisted cluster-mode groups ran serially in the synchronous
startup path, so a slow or unavailable Docker daemon could hold up
emulator readiness by a container-readiness plus cluster-formation
timeout per group, timing out readiness-dependent clients such as
Testcontainers.

restorePersistedRuntime now reserves each node's proxy port and marks
groups creating synchronously - so no request can claim a persisted
port or see a stale available status - then brings containers, cluster
formation and proxies back in the background, flipping each group to
available or create-failed as its restore finishes.

---------

Co-authored-by: kurtmc <2661907+kurtmc@users.noreply.github.com>
This commit is contained in:
Kurt McAlpineandkurtmc authored and GitHub committed 2026-08-28 16:00:33 -04:00
1 parent eb5134da2d
commit 97ff0bc3e9
22 files changed
+2170 -69

No files matched your search

@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.lifecycle.InitLifecycleState;
import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook;
import io.github.hectorvent.floci.lifecycle.inithook.InitializationHooksRunner;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheService;
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.proxy.ElastiCacheProxyManager;
@@ -60,6 +61,8 @@ class EmulatorLifecycleTest {
@Mock private EmulatorConfig.Ec2ServiceConfig ec2ServiceConfig;
@Mock private EmulatorConfig.ElbV2ServiceConfig elbv2ServiceConfig;
@Mock private IamService iamService;
@Mock private EmulatorConfig.ElastiCacheServiceConfig elastiCacheServiceConfig;
@Mock private ElastiCacheService elastiCacheService;
@Mock private ElastiCacheContainerManager elastiCacheContainerManager;
@Mock private ElastiCacheMemcachedContainerManager elastiCacheMemcachedContainerManager;
@Mock private ElastiCacheProxyManager elastiCacheProxyManager;
@@ -97,13 +100,15 @@ class EmulatorLifecycleTest {
Mockito.lenient().when(ec2ServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(servicesConfig.elbv2()).thenReturn(elbv2ServiceConfig);
Mockito.lenient().when(elbv2ServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(servicesConfig.elasticache()).thenReturn(elastiCacheServiceConfig);
Mockito.lenient().when(elastiCacheServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(config.tls()).thenReturn(tlsConfig);
Mockito.lenient().when(tlsConfig.enabled()).thenReturn(false);
Mockito.lenient().when(config.port()).thenReturn(4566);
emulatorLifecycle = new EmulatorLifecycle(
storageFactory, serviceRegistry, config,
iamService,
iamService, elastiCacheService,
elastiCacheContainerManager, elastiCacheMemcachedContainerManager,
elastiCacheProxyManager, rdsContainerManager, rdsProxyManager,
memoryDbContainerManager, memoryDbProxyManager,
@@ -170,6 +175,35 @@ class EmulatorLifecycleTest {
Mockito.verify(elbV2Service, Mockito.never()).restorePersistedRuntime();
}
@Test
@DisplayName("Should restore ElastiCache persisted runtime after loading storage when elasticache is enabled")
void shouldRestoreElastiCachePersistedRuntimeAfterStorageLoad() {
stubStorageConfig();
when(elastiCacheServiceConfig.enabled()).thenReturn(true);
when(elastiCacheService.restorePersistedRuntime())
.thenReturn(java.util.concurrent.CompletableFuture.completedFuture(null));
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
var inOrder = Mockito.inOrder(storageFactory, elastiCacheService);
inOrder.verify(storageFactory).loadAll();
inOrder.verify(elastiCacheService).restorePersistedRuntime();
}
@Test
@DisplayName("Should not restore ElastiCache persisted runtime when elasticache is disabled")
void shouldNotRestoreElastiCachePersistedRuntimeWhenDisabled() {
stubStorageConfig();
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
Mockito.verify(elastiCacheService, Mockito.never()).restorePersistedRuntime();
}
@Test
@DisplayName("Should rehydrate AppSync schemas after orphan recovery on startup")
void shouldRehydrateAppSyncSchemasAfterOrphanRecovery() {
@@ -0,0 +1,266 @@
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 java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* End-to-end coverage for cluster-mode replication groups: real sharded Valkey
* topology behind per-node auth proxies, honest describe output, and MOVED
* redirects that point clients at the proxy ports.
*
* <p>Key slots used below are the well-known CRC16 values: {@code bar} → 5061
* (first shard of two) and {@code foo} → 12182 (second shard of two).
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ElastiCacheClusterIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260412/us-east-1/elasticache/aws4_request";
private static final String GROUP_ID = "it-ec-cluster";
private static final int SOCKET_TIMEOUT_MS = 10_000;
private static int configurationEndpointPort;
private static int secondShardPort;
@BeforeAll
static void requireDocker() {
Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for ElastiCache integration tests");
}
@AfterAll
static void cleanup() {
try {
given()
.formParam("Action", "DeleteReplicationGroup")
.formParam("ReplicationGroupId", GROUP_ID)
.header("Authorization", AUTH_HEADER)
.post("/");
} catch (Exception e) {
System.err.println("Cleanup of " + GROUP_ID + " failed: " + e.getMessage());
}
}
@Test
@Order(1)
void createClusterModeReplicationGroup() {
configurationEndpointPort =
given()
.formParam("Action", "CreateReplicationGroup")
.formParam("ReplicationGroupId", GROUP_ID)
.formParam("ReplicationGroupDescription", "Cluster mode integration test")
.formParam("Engine", "valkey")
.formParam("EngineVersion", "8.2")
.formParam("CacheNodeType", "cache.t4g.micro")
.formParam("CacheParameterGroupName", "default.valkey8.cluster.on")
.formParam("NumNodeGroups", "2")
.formParam("ReplicasPerNodeGroup", "1")
.formParam("AutomaticFailoverEnabled", "true")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.ReplicationGroupId", equalTo(GROUP_ID))
.body("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.Status", equalTo("available"))
.body("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.ClusterEnabled", equalTo("true"))
.body("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.AutomaticFailover", equalTo("enabled"))
.body("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.Engine", equalTo("valkey"))
.extract()
.xmlPath()
.getInt("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.ConfigurationEndpoint.Port");
}
@Test
@Order(2)
void describeReportsClusterTopology() {
XmlPath xml = given()
.formParam("Action", "DescribeReplicationGroups")
.formParam("ReplicationGroupId", GROUP_ID)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract()
.xmlPath();
String prefix = "DescribeReplicationGroupsResponse.DescribeReplicationGroupsResult.ReplicationGroups.ReplicationGroup.";
assertEquals("true", xml.getString(prefix + "ClusterEnabled"));
List<String> memberClusters = xml.getList(prefix + "MemberClusters.ClusterId");
assertEquals(List.of(GROUP_ID + "-0001-001", GROUP_ID + "-0001-002",
GROUP_ID + "-0002-001", GROUP_ID + "-0002-002"), memberClusters);
assertEquals(List.of("0001", "0002"), xml.getList(prefix + "NodeGroups.NodeGroup.NodeGroupId"));
assertEquals(List.of("0-8191", "8192-16383"), xml.getList(prefix + "NodeGroups.NodeGroup.Slots"));
}
@Test
@Order(3)
void describeCacheClustersAnswersForMembers() {
secondShardPort = given()
.formParam("Action", "DescribeCacheClusters")
.formParam("CacheClusterId", GROUP_ID + "-0002-001")
.formParam("ShowCacheNodeInfo", "true")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.CacheClusterId",
equalTo(GROUP_ID + "-0002-001"))
.body("DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.ReplicationGroupId",
equalTo(GROUP_ID))
.body("DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.Engine",
equalTo("valkey"))
.body("DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.EngineVersion",
equalTo("8.2"))
.extract()
.xmlPath()
.getInt("DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.CacheNodes.CacheNode.Endpoint.Port");
}
@Test
@Order(4)
void clusterStateIsOkThroughTheProxy() throws Exception {
try (Socket socket = openSocket(configurationEndpointPort)) {
write(socket, respArray("PING"));
assertEquals("+PONG\r\n", readLine(socket));
write(socket, respArray("CLUSTER", "INFO"));
String info = readBulk(socket);
assertTrue(info.contains("cluster_state:ok"), "Expected cluster_state:ok but got: " + info);
assertTrue(info.contains("cluster_known_nodes:4"), "Expected 4 known nodes but got: " + info);
}
}
@Test
@Order(5)
void movedRedirectPointsAtTheOtherShardsProxyPort() throws Exception {
try (Socket socket = openSocket(configurationEndpointPort)) {
write(socket, respArray("SET", "bar", "first-shard-value"));
assertEquals("+OK\r\n", readLine(socket));
write(socket, respArray("SET", "foo", "second-shard-value"));
String reply = readLine(socket);
assertTrue(reply.startsWith("-MOVED 12182 "), "Expected MOVED redirect but got: " + reply);
String target = reply.trim().substring("-MOVED 12182 ".length());
assertEquals("localhost:" + secondShardPort, target,
"MOVED must point at the announced hostname and the second shard primary's proxy port");
}
try (Socket socket = openSocket(secondShardPort)) {
write(socket, respArray("SET", "foo", "second-shard-value"));
assertEquals("+OK\r\n", readLine(socket));
write(socket, respArray("GET", "foo"));
assertEquals("second-shard-value", readBulk(socket));
}
}
@Test
@Order(6)
void deleteClusterModeReplicationGroup() {
given()
.formParam("Action", "DeleteReplicationGroup")
.formParam("ReplicationGroupId", GROUP_ID)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "DescribeReplicationGroups")
.formParam("ReplicationGroupId", GROUP_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(int port) throws IOException {
Socket socket = new Socket("localhost", 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,6 +1,11 @@
package io.github.hectorvent.floci.services.elasticache;
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.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.ReplicationGroupStatus;
import io.github.hectorvent.floci.services.elasticache.proxy.SigV4Validator;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
@@ -19,8 +24,12 @@ import static org.mockito.Mockito.*;
import org.mockito.ArgumentCaptor;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Verifies the empty-list read responses for the subnet/parameter group describes, so
@@ -64,6 +73,124 @@ class ElastiCacheQueryHandlerTest {
assertFalse(body.contains("<Marker>"), "Empty list must omit Marker");
}
@Test
void describeReplicationGroups_reportsClusterModeTopology() {
ReplicationGroup group = new ReplicationGroup("grp", "d", ReplicationGroupStatus.AVAILABLE,
AuthMode.NO_AUTH, new Endpoint("localhost", 6379), Instant.now(), 6379);
group.setClusterEnabled(true);
group.setEngine("valkey");
group.setAutomaticFailoverEnabled(true);
group.setClusterNodes(List.of(
new ClusterNode("grp-0001-001", "0001", true, 6379, "0-8191"),
new ClusterNode("grp-0002-001", "0002", true, 6380, "8192-16383")));
when(service.listReplicationGroups("grp")).thenReturn(List.of(group));
when(service.memberCacheClusters(group)).thenReturn(List.of(
new ElastiCacheService.MemberCacheCluster(group, "grp-0001-001", 6379, true),
new ElastiCacheService.MemberCacheCluster(group, "grp-0002-001", 6380, true)));
MultivaluedMap<String, String> params = params();
params.putSingle("ReplicationGroupId", "grp");
Response response = handler.handle("DescribeReplicationGroups", params, "us-east-1");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("<ClusterEnabled>true</ClusterEnabled>"));
assertTrue(body.contains("<ClusterMode>enabled</ClusterMode>"));
assertTrue(body.contains("<AutomaticFailover>enabled</AutomaticFailover>"));
assertTrue(body.contains("<Engine>valkey</Engine>"));
assertTrue(body.contains("<ClusterId>grp-0001-001</ClusterId>"));
assertTrue(body.contains("<ClusterId>grp-0002-001</ClusterId>"));
assertTrue(body.contains("<NodeGroupId>0002</NodeGroupId>"));
assertTrue(body.contains("<Slots>8192-16383</Slots>"));
assertTrue(body.contains("<CacheClusterId>grp-0002-001</CacheClusterId>"));
assertFalse(body.contains("<PrimaryEndpoint>"),
"Cluster-mode node groups carry Slots, not a PrimaryEndpoint");
}
@Test
void describeReplicationGroups_reportsSingleNodeGroupWithPrimaryEndpoint() {
ReplicationGroup group = new ReplicationGroup("grp", "d", ReplicationGroupStatus.AVAILABLE,
AuthMode.NO_AUTH, new Endpoint("localhost", 6379), Instant.now(), 6379);
group.setEngine("valkey");
when(service.listReplicationGroups("grp")).thenReturn(List.of(group));
when(service.memberCacheClusters(group)).thenReturn(List.of(
new ElastiCacheService.MemberCacheCluster(group, "grp-001", 6379, true)));
MultivaluedMap<String, String> params = params();
params.putSingle("ReplicationGroupId", "grp");
Response response = handler.handle("DescribeReplicationGroups", params, "us-east-1");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("<ClusterEnabled>false</ClusterEnabled>"));
assertTrue(body.contains("<ClusterId>grp-001</ClusterId>"));
assertTrue(body.contains("<PrimaryEndpoint><Address>localhost</Address><Port>6379</Port></PrimaryEndpoint>"));
assertTrue(body.contains("<CurrentRole>primary</CurrentRole>"));
}
@Test
void describeCacheClusters_answersForReplicationGroupMembers() {
ReplicationGroup group = new ReplicationGroup("grp", "d", ReplicationGroupStatus.AVAILABLE,
AuthMode.NO_AUTH, new Endpoint("localhost", 6379), Instant.now(), 6379);
group.setEngine("valkey");
group.setEngineVersion("8.2");
group.setCacheNodeType("cache.t4g.micro");
when(service.listMemberCacheClusters("grp-0001-001")).thenReturn(List.of(
new ElastiCacheService.MemberCacheCluster(group, "grp-0001-001", 6379, true)));
MultivaluedMap<String, String> params = params();
params.putSingle("CacheClusterId", "grp-0001-001");
params.putSingle("ShowCacheNodeInfo", "true");
Response response = handler.handle("DescribeCacheClusters", params, "us-east-1");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("<CacheClusterId>grp-0001-001</CacheClusterId>"));
assertTrue(body.contains("<CacheClusterStatus>available</CacheClusterStatus>"));
assertTrue(body.contains("<ReplicationGroupId>grp</ReplicationGroupId>"));
assertTrue(body.contains("<Engine>valkey</Engine>"));
assertTrue(body.contains("<EngineVersion>8.2</EngineVersion>"));
assertTrue(body.contains("<CacheNodeType>cache.t4g.micro</CacheNodeType>"));
assertTrue(body.contains("<Endpoint><Address>localhost</Address><Port>6379</Port></Endpoint>"));
}
@Test
void describeCacheClusters_membersOfFailedGroupReportRestoreFailed() {
ReplicationGroup group = new ReplicationGroup("grp", "d", ReplicationGroupStatus.CREATE_FAILED,
AuthMode.NO_AUTH, null, Instant.now(), 6379);
when(service.listMemberCacheClusters("grp-0001-001")).thenReturn(List.of(
new ElastiCacheService.MemberCacheCluster(group, "grp-0001-001", 6379, true)));
MultivaluedMap<String, String> params = params();
params.putSingle("CacheClusterId", "grp-0001-001");
params.putSingle("ShowCacheNodeInfo", "true");
Response response = handler.handle("DescribeCacheClusters", params, "us-east-1");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("<CacheClusterStatus>restore-failed</CacheClusterStatus>"),
"CacheClusterStatus has no create-failed; the documented failure value is restore-failed: " + body);
assertFalse(body.contains("<CacheNodes>"),
"A failed group has no endpoint, so members must not hand out node endpoints");
}
@Test
void describeReplicationGroups_reportsCreateFailedStatusInAwsWireForm() {
ReplicationGroup group = new ReplicationGroup("grp", "d", ReplicationGroupStatus.CREATE_FAILED,
AuthMode.NO_AUTH, null, Instant.now(), 6379);
when(service.listReplicationGroups("grp")).thenReturn(List.of(group));
when(service.memberCacheClusters(group)).thenReturn(List.of());
MultivaluedMap<String, String> params = params();
params.putSingle("ReplicationGroupId", "grp");
Response response = handler.handle("DescribeReplicationGroups", params, "us-east-1");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("<Status>create-failed</Status>"),
"AWS reports this status hyphenated, not as the enum constant");
}
@Test
void unsupportedOperationStillReturnsQueryError() {
Response response = handler.handle("NoSuchAction", params(), "us-east-1");
@@ -85,7 +212,7 @@ class ElastiCacheQueryHandlerTest {
@Test
void createReplicationGroup_passesSettingsAndTagsToService() {
when(service.createReplicationGroup(any(), any(), any(), any(), any(), any(), any()))
when(service.createReplicationGroup(any(ElastiCacheService.CreateReplicationGroupRequest.class)))
.thenReturn(group("g1"));
MultivaluedMap<String, String> p = params();
p.add("ReplicationGroupId", "g1");
@@ -99,15 +226,24 @@ class ElastiCacheQueryHandlerTest {
assertEquals(200, handler.handle("CreateReplicationGroup", p, "us-east-1").getStatus());
verify(service).createReplicationGroup(eq("g1"), eq("d"), eq(AuthMode.NO_AUTH), isNull(), eq("us-east-1"),
eq(new ReplicationGroupSettings(true, "alias/cache", 7, "06:30-07:30")), eq(Map.of("Name", "g1")));
ArgumentCaptor<ElastiCacheService.CreateReplicationGroupRequest> captor =
ArgumentCaptor.forClass(ElastiCacheService.CreateReplicationGroupRequest.class);
verify(service).createReplicationGroup(captor.capture());
ElastiCacheService.CreateReplicationGroupRequest request = captor.getValue();
assertEquals("g1", request.replicationGroupId());
assertEquals("d", request.description());
assertEquals(AuthMode.NO_AUTH, request.authMode());
assertEquals("us-east-1", request.region());
assertEquals(new ReplicationGroupSettings(true, "alias/cache", 7, "06:30-07:30"), request.settings());
assertEquals(Map.of("Name", "g1"), request.tags());
}
@Test
void createReplicationGroup_readsTheEncryptionFlagAsAwsDoes() {
when(service.createReplicationGroup(any(), any(), any(), any(), any(), any(), any()))
when(service.createReplicationGroup(any(ElastiCacheService.CreateReplicationGroupRequest.class)))
.thenReturn(group("g1"));
ArgumentCaptor<ReplicationGroupSettings> captor = ArgumentCaptor.forClass(ReplicationGroupSettings.class);
ArgumentCaptor<ElastiCacheService.CreateReplicationGroupRequest> captor =
ArgumentCaptor.forClass(ElastiCacheService.CreateReplicationGroupRequest.class);
// a live account reads anything but "false" as true — probed with banana, yes and "TRUE "
for (String value : new String[] {"true", "banana", "yes", "TRUE "}) {
MultivaluedMap<String, String> p = params();
@@ -125,8 +261,9 @@ class ElastiCacheQueryHandlerTest {
omitted.add("ReplicationGroupId", "g1");
handler.handle("CreateReplicationGroup", omitted, "us-east-1");
verify(service, times(7)).createReplicationGroup(any(), any(), any(), any(), any(), captor.capture(), any());
List<Boolean> seen = captor.getAllValues().stream().map(ReplicationGroupSettings::atRestEncryptionEnabled).toList();
verify(service, times(7)).createReplicationGroup(captor.capture());
List<Boolean> seen = captor.getAllValues().stream()
.map(r -> r.settings().atRestEncryptionEnabled()).toList();
assertEquals(java.util.Arrays.asList(true, true, true, true, false, false, null), seen);
}
@@ -12,14 +12,20 @@ import io.github.hectorvent.floci.services.kms.model.KmsKey;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupSettings;
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.ValkeyClusterFormation;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import io.github.hectorvent.floci.services.elasticache.model.ClusterNode;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupStatus;
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -36,6 +42,7 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
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;
@@ -46,6 +53,7 @@ class ElastiCacheServiceTest {
private ElastiCacheContainerManager containerManager;
private ElastiCacheProxyManager proxyManager;
private EmulatorConfig config;
private ValkeyClusterFormation clusterFormation;
@BeforeEach
void setUp() {
@@ -71,8 +79,10 @@ class ElastiCacheServiceTest {
kmsService = org.mockito.Mockito.mock(KmsService.class);
when(kmsService.describeKey(any(), any())).thenThrow(
new AwsException("NotFoundException", "Key not found", 404));
service = new ElastiCacheService(containerManager, proxyManager, storageFactory, config,
ec2Service, new RegionResolver("us-east-1", "000000000000"), kmsService);
clusterFormation = mock(ValkeyClusterFormation.class);
service = new ElastiCacheService(containerManager, proxyManager, clusterFormation,
storageFactory, config, ec2Service, new RegionResolver("us-east-1", "000000000000"),
kmsService);
}
@Test
@@ -97,8 +107,8 @@ class ElastiCacheServiceTest {
when(cm.start(anyString(), anyString()))
.thenReturn(new ElastiCacheContainerHandle("cid", "grp", "localhost", 6379));
doNothing().when(pm).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
ElastiCacheService svc = new ElastiCacheService(cm, pm, sf, cfg,
org.mockito.Mockito.mock(Ec2Service.class),
ElastiCacheService svc = new ElastiCacheService(cm, pm, mock(ValkeyClusterFormation.class),
sf, cfg, org.mockito.Mockito.mock(Ec2Service.class),
new RegionResolver("us-east-1", "000000000000"),
org.mockito.Mockito.mock(KmsService.class));
@@ -207,6 +217,285 @@ class ElastiCacheServiceTest {
"Port from the failed create must be released so the next group reuses it");
}
private static ElastiCacheService.CreateReplicationGroupRequest clusterRequest(
String groupId, Integer numNodeGroups, Integer replicasPerNodeGroup) {
return new ElastiCacheService.CreateReplicationGroupRequest(groupId, "test",
AuthMode.NO_AUTH, null, "us-east-1", "valkey", "8.2", "cache.t4g.micro",
"default.valkey8.cluster.on", null, null, numNodeGroups, replicasPerNodeGroup,
null, true, null, ReplicationGroupSettings.defaults(), Map.of());
}
private void stubPerNodeContainers() {
when(containerManager.start(anyString(), anyString(), any())).thenAnswer(inv ->
new ElastiCacheContainerHandle("cid-" + inv.getArgument(0, String.class),
inv.getArgument(0, String.class), "localhost", 6379));
}
@Test
void clusterModeCreateStartsOneContainerAndProxyPerNode() {
stubPerNodeContainers();
ReplicationGroup group = service.createReplicationGroup(clusterRequest("grp", 2, 1));
assertTrue(group.isClusterEnabled());
assertEquals(2, group.getNumNodeGroups());
assertEquals(1, group.getReplicasPerNodeGroup());
assertEquals(4, group.getClusterNodes().size());
List<ClusterNode> nodes = group.getClusterNodes();
assertEquals("grp-0001-001", nodes.get(0).getMemberClusterId());
assertEquals("grp-0001-002", nodes.get(1).getMemberClusterId());
assertEquals("grp-0002-001", nodes.get(2).getMemberClusterId());
assertEquals("grp-0002-002", nodes.get(3).getMemberClusterId());
assertTrue(nodes.get(0).isPrimary());
assertFalse(nodes.get(1).isPrimary());
assertEquals("0-8191", nodes.get(0).getSlots());
assertEquals("8192-16383", nodes.get(2).getSlots());
assertEquals(4, nodes.stream().map(ClusterNode::getProxyPort).distinct().count(),
"Each node must own its own proxy port");
assertEquals(16379, group.getConfigurationEndpoint().port());
verify(clusterFormation).form(eq("grp"), any(), eq(2));
verify(containerManager, times(4)).start(anyString(), anyString(), any());
verify(proxyManager, times(4)).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
}
@Test
void clusterOnParameterGroupEnablesClusterModeForSingleShard() {
stubPerNodeContainers();
ReplicationGroup group = service.createReplicationGroup(clusterRequest("grp", 1, 0));
assertTrue(group.isClusterEnabled());
assertEquals(1, group.getClusterNodes().size());
assertEquals("0-16383", group.getClusterNodes().getFirst().getSlots());
}
@Test
void numNodeGroupsBeyondQuotaSurfacesModeledQuotaFault() {
AwsException ex = assertThrows(AwsException.class,
() -> service.createReplicationGroup(clusterRequest("grp", 501, 0)));
assertEquals("NodeGroupsPerReplicationGroupQuotaExceeded", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
verify(containerManager, never()).start(anyString(), anyString(), any());
}
@Test
void plainCreateStaysClusterModeDisabled() {
ReplicationGroup group =
service.createReplicationGroup("grp", "test", AuthMode.NO_AUTH, null, "us-east-1");
assertFalse(group.isClusterEnabled());
assertTrue(group.getClusterNodes().isEmpty());
assertEquals(List.of("grp-001"),
service.memberCacheClusters(group).stream()
.map(ElastiCacheService.MemberCacheCluster::cacheClusterId).toList());
verify(containerManager, never()).start(anyString(), anyString(), any());
}
@Test
void clusterFormationFailureRollsBackAllNodesAndReleasesPorts() {
stubPerNodeContainers();
doThrow(new RuntimeException("formation boom"))
.when(clusterFormation).form(anyString(), any(), anyInt());
assertThrows(RuntimeException.class,
() -> service.createReplicationGroup(clusterRequest("grp", 2, 1)));
verify(containerManager, times(4)).stop(any());
verify(proxyManager, never()).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
ReplicationGroup recovered =
service.createReplicationGroup("grp2", "test", AuthMode.PASSWORD, null, "us-east-1");
assertEquals(16379, recovered.getProxyPort(),
"Ports from the failed cluster create must be released for the next group");
}
@Test
void deleteClusterModeGroupStopsEveryNodeAndReleasesPorts() {
stubPerNodeContainers();
service.createReplicationGroup(clusterRequest("grp", 2, 0));
service.deleteReplicationGroup("grp");
verify(proxyManager).stopProxy("grp-0001-001");
verify(proxyManager).stopProxy("grp-0002-001");
verify(containerManager, times(2)).stop(any());
ReplicationGroup recovered =
service.createReplicationGroup("grp2", "test", AuthMode.PASSWORD, null, "us-east-1");
assertEquals(16379, recovered.getProxyPort(),
"Ports from the deleted cluster group must be released for the next group");
}
@Test
void clusterNodesAnnounceTheConfiguredHostnameAsPreferredEndpoint() {
stubPerNodeContainers();
service.createReplicationGroup(clusterRequest("grp", 1, 0));
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> flags = ArgumentCaptor.forClass(List.class);
verify(containerManager).start(eq("grp-0001-001"), anyString(), flags.capture());
List<String> captured = flags.getValue();
assertEquals("localhost", flagValue(captured, "--cluster-announce-hostname"));
assertEquals("hostname", flagValue(captured, "--cluster-preferred-endpoint-type"));
assertEquals("16379", flagValue(captured, "--cluster-announce-port"));
}
@Test
void clusterAnnounceHostnameOverrideIsAnnouncedAndReported() {
when(config.services().elasticache().clusterAnnounceHostname())
.thenReturn(java.util.Optional.of("localhost.floci.io"));
stubPerNodeContainers();
ReplicationGroup group = service.createReplicationGroup(clusterRequest("grp", 1, 0));
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> flags = ArgumentCaptor.forClass(List.class);
verify(containerManager).start(eq("grp-0001-001"), anyString(), flags.capture());
assertEquals("localhost.floci.io", flagValue(flags.getValue(), "--cluster-announce-hostname"));
assertEquals("localhost.floci.io", group.getConfigurationEndpoint().address());
}
private static String flagValue(List<String> flags, String flag) {
int index = flags.indexOf(flag);
assertTrue(index >= 0 && index + 1 < flags.size(), "Missing flag " + flag + " in " + flags);
return flags.get(index + 1);
}
private static StorageFactory sharedStorageFactory() {
StorageFactory storageFactory = mock(StorageFactory.class);
Map<String, Object> backends = new ConcurrentHashMap<>();
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv ->
backends.computeIfAbsent(inv.getArgument(1, String.class),
key -> AccountAwareStorageBackend.inMemory("000000000000")));
return storageFactory;
}
private static ElastiCacheService serviceWith(StorageFactory storageFactory,
ElastiCacheContainerManager containerManager,
ElastiCacheProxyManager proxyManager,
ValkeyClusterFormation clusterFormation) {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.ElastiCacheServiceConfig ecConfig = mock(EmulatorConfig.ElastiCacheServiceConfig.class);
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.elasticache()).thenReturn(ecConfig);
when(ecConfig.proxyBasePort()).thenReturn(16379);
when(ecConfig.proxyMaxPort()).thenReturn(16399);
when(ecConfig.defaultImage()).thenReturn("valkey/valkey:8");
when(config.hostname()).thenReturn(java.util.Optional.of("localhost"));
return new ElastiCacheService(containerManager, proxyManager, clusterFormation,
storageFactory, config, mock(Ec2Service.class),
new RegionResolver("us-east-1", "000000000000"), mock(KmsService.class));
}
private static void stubPerNodeContainers(ElastiCacheContainerManager containerManager) {
when(containerManager.start(anyString(), anyString(), any())).thenAnswer(inv ->
new ElastiCacheContainerHandle("cid-" + inv.getArgument(0, String.class),
inv.getArgument(0, String.class), "localhost", 6379));
when(containerManager.start(anyString(), anyString()))
.thenReturn(new ElastiCacheContainerHandle("cid", "grp", "localhost", 6379));
}
@Test
void restorePersistedRuntimeReprovisionsClusterModeGroups() {
StorageFactory storageFactory = sharedStorageFactory();
ElastiCacheContainerManager beforeRestart = mock(ElastiCacheContainerManager.class);
stubPerNodeContainers(beforeRestart);
serviceWith(storageFactory, beforeRestart, mock(ElastiCacheProxyManager.class),
mock(ValkeyClusterFormation.class))
.createReplicationGroup(clusterRequest("grp", 2, 1));
ElastiCacheContainerManager restartedContainers = mock(ElastiCacheContainerManager.class);
stubPerNodeContainers(restartedContainers);
ElastiCacheProxyManager restartedProxies = mock(ElastiCacheProxyManager.class);
ValkeyClusterFormation restartedFormation = mock(ValkeyClusterFormation.class);
ElastiCacheService restarted = serviceWith(storageFactory, restartedContainers,
restartedProxies, restartedFormation);
restarted.restorePersistedRuntime().join();
verify(restartedContainers, times(4)).start(anyString(), anyString(), any());
verify(restartedFormation).form(eq("grp"), any(), eq(2));
verify(restartedProxies, times(4)).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
ReplicationGroup restored = restarted.getReplicationGroup("grp");
assertEquals(ReplicationGroupStatus.AVAILABLE, restored.getStatus());
assertEquals(16379, restored.getConfigurationEndpoint().port());
assertEquals("cid-grp-0001-001", restored.getClusterNodes().getFirst().getContainerId());
ReplicationGroup next =
restarted.createReplicationGroup("grp2", "test", AuthMode.NO_AUTH, null, "us-east-1");
assertEquals(16383, next.getProxyPort(),
"Restored node ports must be reserved again so new groups cannot take them");
}
@Test
void restoreFailureReportsCreateFailedAndReleasesPorts() {
StorageFactory storageFactory = sharedStorageFactory();
ElastiCacheContainerManager beforeRestart = mock(ElastiCacheContainerManager.class);
stubPerNodeContainers(beforeRestart);
serviceWith(storageFactory, beforeRestart, mock(ElastiCacheProxyManager.class),
mock(ValkeyClusterFormation.class))
.createReplicationGroup(clusterRequest("grp", 2, 0));
ElastiCacheContainerManager restartedContainers = mock(ElastiCacheContainerManager.class);
when(restartedContainers.start(anyString(), anyString(), any()))
.thenThrow(new RuntimeException("docker down"));
when(restartedContainers.start(anyString(), anyString()))
.thenReturn(new ElastiCacheContainerHandle("cid", "grp", "localhost", 6379));
ElastiCacheProxyManager restartedProxies = mock(ElastiCacheProxyManager.class);
ElastiCacheService restarted = serviceWith(storageFactory, restartedContainers,
restartedProxies, mock(ValkeyClusterFormation.class));
restarted.restorePersistedRuntime().join();
ReplicationGroup failed = restarted.getReplicationGroup("grp");
assertEquals(ReplicationGroupStatus.CREATE_FAILED, failed.getStatus());
assertNull(failed.getConfigurationEndpoint(),
"A group whose data plane is gone must not advertise an endpoint");
verify(restartedProxies, never()).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
ReplicationGroup next =
restarted.createReplicationGroup("grp2", "test", AuthMode.NO_AUTH, null, "us-east-1");
assertEquals(16379, next.getProxyPort(),
"Ports from the failed restore must be released for the next group");
}
@Test
void restoreRunsInBackgroundAndReportsCreatingUntilDone() throws InterruptedException {
StorageFactory storageFactory = sharedStorageFactory();
ElastiCacheContainerManager beforeRestart = mock(ElastiCacheContainerManager.class);
stubPerNodeContainers(beforeRestart);
serviceWith(storageFactory, beforeRestart, mock(ElastiCacheProxyManager.class),
mock(ValkeyClusterFormation.class))
.createReplicationGroup(clusterRequest("grp", 2, 0));
ElastiCacheContainerManager restartedContainers = mock(ElastiCacheContainerManager.class);
CountDownLatch restoreStarted = new CountDownLatch(1);
CountDownLatch releaseRestore = new CountDownLatch(1);
when(restartedContainers.start(anyString(), anyString(), any())).thenAnswer(inv -> {
restoreStarted.countDown();
releaseRestore.await(5, TimeUnit.SECONDS);
return new ElastiCacheContainerHandle("cid-" + inv.getArgument(0, String.class),
inv.getArgument(0, String.class), "localhost", 6379);
});
ElastiCacheService restarted = serviceWith(storageFactory, restartedContainers,
mock(ElastiCacheProxyManager.class), mock(ValkeyClusterFormation.class));
CompletableFuture<Void> restore = restarted.restorePersistedRuntime();
assertTrue(restoreStarted.await(5, TimeUnit.SECONDS));
assertFalse(restore.isDone(), "Restore must not block the caller while the data plane comes up");
assertEquals(ReplicationGroupStatus.CREATING, restarted.getReplicationGroup("grp").getStatus(),
"Groups must report creating while their restore is in flight");
releaseRestore.countDown();
restore.join();
assertEquals(ReplicationGroupStatus.AVAILABLE, restarted.getReplicationGroup("grp").getStatus());
}
@Test
void concurrentCreateForSameGroupIdIsRejectedWhileFirstIsProvisioning() throws InterruptedException {
CountDownLatch startedLatch = new CountDownLatch(1);
@@ -356,8 +645,9 @@ class ElastiCacheServiceTest {
.thenAnswer(inv -> new AccountAwareStorageBackend<>(pausing, null, "000000000000"));
when(factory.create(anyString(), org.mockito.ArgumentMatchers.argThat(f -> !"elasticache-groups.json".equals(f)), any()))
.thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
ElastiCacheService svc = new ElastiCacheService(containerManager, proxyManager, factory, config,
org.mockito.Mockito.mock(Ec2Service.class), new RegionResolver("us-east-1", "000000000000"), kmsService);
ElastiCacheService svc = new ElastiCacheService(containerManager, proxyManager, clusterFormation,
factory, config, org.mockito.Mockito.mock(Ec2Service.class),
new RegionResolver("us-east-1", "000000000000"), kmsService);
svc.createReplicationGroup("g1", "d", AuthMode.NO_AUTH, null, "us-east-1");
pausing.pauseOn(PausingStorageBackend.Call.PUT, "g1");