feat(memorydb): add MemoryDB service with mock mode (#1420)

* feat(memorydb): add MemoryDB service with mock mode

Adds Amazon MemoryDB for Redis as a Docker-backed service, modelled on
the existing ElastiCache and DocumentDB services.

Control plane is AWS JSON 1.1 (X-Amz-Target: AmazonMemoryDB.*) dispatched
from AwsJson11Controller, supporting CreateCluster, DescribeClusters,
UpdateCluster, DeleteCluster, ListTags, TagResource and UntagResource.

The data plane reuses ElastiCache's RESP proxy and SigV4 validator, since
MemoryDB is Redis wire-compatible: each cluster starts a real Valkey/Redis
container and an auth proxy forwards client connections to it.

A mock mode (FLOCI_SERVICES_MEMORYDB_MOCK, default false) tracks clusters
as control-plane-only resources without starting a container, so IaC tools
like Terraform and OpenTofu can run where no Docker socket is available.
This mirrors the existing DocumentDB mock flag.

Includes service unit tests and documentation.

* fix(memorydb): return UnknownOperationException for unsupported actions

Unrecognised JSON 1.1 actions returned InvalidParameterValueException,
which mis-signals the error category and can break SDK/CLI probing.
Use UnknownOperationException to match CloudMap and the shared
JsonErrorResponseUtils.createUnknownOperationErrorResponse helper.

* docs(memorydb): drop service-count bump from this PR

The 55->56 edit was built on a stale baseline (main's count does not
reflect already-merged services) and conflicts with a separate docs
branch. Keep the MemoryDB matrix row; leave the headline count to a
dedicated docs PR. No functional change.

* fix(memorydb): use InternalFailure for unexpected errors

Align the generic exception path with Floci's JSON 1.1 convention and the
shared JsonErrorResponseUtils.createErrorResponse helper, which emit
InternalFailure for unexpected server errors. SDKs commonly key on this.

* fix(memorydb): copy AuthToken onto cluster spec on CreateCluster

CreateCluster resolved AuthMode.PASSWORD from the presence of AuthToken
but never copied the token onto the spec, so the service stored a null
token and password auth always failed. Copy AuthToken onto the spec and
add MemoryDbHandlerTest covering token propagation and the NO_AUTH default.

* fix(memorydb): validate cluster name to avoid NPE on null key

getCluster passed the name straight to the ConcurrentHashMap-backed
storage, so a null/blank name (reachable via UpdateCluster/DeleteCluster
without ClusterName) threw a NullPointerException surfaced as a 500.
Guard with an AWS-style InvalidParameterValueException (400), matching
CreateCluster, and add a regression test.

* fix(memorydb): roll back proxy port and container on failed provisioning

If container or proxy startup failed after allocating a proxy port, the
port stayed reserved (and any started container orphaned), eventually
exhausting the range with InsufficientClusterCapacity. Extract backend
startup into startBackend with best-effort rollback that stops the proxy
and container and always releases the port. Add a regression test proving
the port is reclaimed after a failed create.

* fix(memorydb): stop proxies and containers on emulator shutdown

MemoryDbProxyManager.stopAll and MemoryDbContainerManager.stopAll were
never invoked from EmulatorLifecycle.onStop, so MemoryDB clusters left
bound TCP proxy ports and running containers after shutdown. Wire both
managers into onStop alongside the existing ElastiCache and RDS cleanup.

No test: shutdown DI wiring is not meaningfully testable in isolation.

* test(memorydb): update EmulatorLifecycleTest for new constructor params

The shutdown-wiring change added MemoryDb container/proxy managers to the
EmulatorLifecycle constructor; update the direct constructor call in the
unit test to pass the two new mocks.

* test(memorydb): add Docker-backed integration test

End-to-end coverage mirroring ElastiCacheIntegrationTest: JSON 1.1 control
plane (CreateCluster/DescribeClusters/DeleteCluster) plus the real RESP
data plane through a Valkey container and the auth proxy. Covers no-auth
connectivity (PING/SET/GET), password auth (AUTH token accepted, wrong
token and unauthenticated commands rejected), and proxy-port reuse after
delete. Gated on Docker availability via an assumption.

* docs(memorydb): clarify mock endpoint uses configured hostname

Mock mode reports <hostname>:6379 (from floci.hostname / FLOCI_HOSTNAME,
defaulting to localhost), not always localhost. Update the Mock Mode note
so users with a custom hostname aren't surprised.

* fix(memorydb): use correct InsufficientClusterCapacityFault error code
This commit is contained in:
Ahmed khaled authored and GitHub committed 2026-06-20 11:45:37 -05:00
1 parent 760d48b91a
commit fd904bc409
24 files changed
+1699 -1

No files matched your search

@@ -60,6 +60,8 @@ class EmulatorLifecycleTest {
@Mock private ElastiCacheProxyManager elastiCacheProxyManager;
@Mock private RdsContainerManager rdsContainerManager;
@Mock private RdsProxyManager rdsProxyManager;
@Mock private io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerManager memoryDbContainerManager;
@Mock private io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbProxyManager memoryDbProxyManager;
@Mock private DocDbContainerManager docDbContainerManager;
@Mock private NeptuneContainerManager neptuneContainerManager;
@Mock private NeptuneProxyManager neptuneProxyManager;
@@ -89,6 +91,7 @@ class EmulatorLifecycleTest {
storageFactory, serviceRegistry, config,
elastiCacheContainerManager, elastiCacheMemcachedContainerManager,
elastiCacheProxyManager, rdsContainerManager, rdsProxyManager,
memoryDbContainerManager, memoryDbProxyManager,
docDbContainerManager, neptuneContainerManager, neptuneProxyManager, rdsService,
initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller,
pipesService, ec2MetadataServer, ecrRegistryManager, flociUiManager, initLifecycleState);
@@ -0,0 +1,65 @@
package io.github.hectorvent.floci.services.memorydb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.memorydb.model.AuthMode;
import io.github.hectorvent.floci.services.memorydb.model.Cluster;
import io.github.hectorvent.floci.services.memorydb.model.ClusterStatus;
import io.github.hectorvent.floci.services.memorydb.model.Endpoint;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class MemoryDbHandlerTest {
private MemoryDbService service;
private MemoryDbHandler handler;
private final ObjectMapper objectMapper = new ObjectMapper();
@BeforeEach
void setUp() {
service = mock(MemoryDbService.class);
handler = new MemoryDbHandler(service, objectMapper);
when(service.createCluster(any(), any())).thenAnswer(inv -> {
Cluster spec = inv.getArgument(0);
spec.setStatus(ClusterStatus.AVAILABLE);
spec.setClusterEndpoint(new Endpoint("localhost", 6400));
spec.setCreatedAt(Instant.now());
return spec;
});
}
@Test
void createClusterPropagatesAuthTokenToSpec() throws Exception {
JsonNode request = objectMapper.readTree(
"{\"ClusterName\":\"secure\",\"AuthToken\":\"s3cret\"}");
handler.handle("CreateCluster", request, "us-east-1");
ArgumentCaptor<Cluster> captor = ArgumentCaptor.forClass(Cluster.class);
org.mockito.Mockito.verify(service).createCluster(captor.capture(), eq("us-east-1"));
Cluster spec = captor.getValue();
assertEquals("s3cret", spec.getAuthToken(),
"AuthToken must be copied onto the spec so PASSWORD auth can validate it");
assertEquals(AuthMode.PASSWORD, spec.getAuthMode());
}
@Test
void createClusterWithoutAuthTokenDefaultsToNoAuth() throws Exception {
JsonNode request = objectMapper.readTree("{\"ClusterName\":\"open\"}");
handler.handle("CreateCluster", request, "us-east-1");
ArgumentCaptor<Cluster> captor = ArgumentCaptor.forClass(Cluster.class);
org.mockito.Mockito.verify(service).createCluster(captor.capture(), eq("us-east-1"));
assertEquals(AuthMode.NO_AUTH, captor.getValue().getAuthMode());
}
}
@@ -0,0 +1,268 @@
package io.github.hectorvent.floci.services.memorydb;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
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.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.List;
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 MemoryDB test: JSON 1.1 control plane (CreateCluster/DescribeClusters/
* DeleteCluster) plus the real RESP data plane (connectivity and password auth)
* through a Docker-backed Valkey container and the TCP auth proxy.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class MemoryDbIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260412/us-east-1/memorydb/aws4_request";
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String OPEN_CLUSTER = "it-mdb-open";
private static final String AUTH_CLUSTER = "it-mdb-auth";
private static final String AUTH_TOKEN = "it-mdb-token";
private static final int SOCKET_TIMEOUT_MS = 10_000;
private static final int READ_LINE_MAX_ATTEMPTS = 3;
private static int openPort;
private static int authPort;
@BeforeAll
static void setup() {
RestAssuredJsonUtils.configureAwsContentTypes();
Assumptions.assumeTrue(isDockerAvailable(),
"Docker daemon must be available for MemoryDB integration tests");
}
@AfterAll
static void cleanup() {
for (String name : List.of(OPEN_CLUSTER, OPEN_CLUSTER + "-reused", AUTH_CLUSTER)) {
try {
deleteCluster(name);
} catch (Exception ignored) {
// best-effort
}
}
}
@Test
@Order(1)
void createClusterWithoutAuth() {
openPort = memorydb("CreateCluster", "{"
+ "\"ClusterName\":\"" + OPEN_CLUSTER + "\","
+ "\"NodeType\":\"db.t4g.small\","
+ "\"ACLName\":\"open-access\"}")
.then()
.statusCode(200)
.body("Cluster.Name", equalTo(OPEN_CLUSTER))
.body("Cluster.Status", equalTo("available"))
.body("Cluster.ClusterEndpoint.Address", equalTo("localhost"))
.body("Cluster.ClusterEndpoint.Port", notNullValue())
.extract()
.path("Cluster.ClusterEndpoint.Port");
}
@Test
@Order(2)
void describeClustersIncludesCreated() {
memorydb("DescribeClusters", "{\"ClusterName\":\"" + OPEN_CLUSTER + "\"}")
.then()
.statusCode(200)
.body("Clusters[0].Name", equalTo(OPEN_CLUSTER))
.body("Clusters[0].ClusterEndpoint.Port", equalTo(openPort));
}
@Test
@Order(3)
void respDataPlaneWorksWithoutAuth() throws Exception {
try (Socket socket = openSocket(openPort)) {
write(socket, respArray("PING"));
assertEquals("+PONG\r\n", readLine(socket));
write(socket, respArray("SET", "mykey", "hello"));
assertEquals("+OK\r\n", readLine(socket));
write(socket, respArray("GET", "mykey"));
assertEquals("$5\r\n", readLine(socket));
assertEquals("hello\r\n", readLine(socket));
}
}
@Test
@Order(4)
void createClusterWithAuthToken() {
authPort = memorydb("CreateCluster", "{"
+ "\"ClusterName\":\"" + AUTH_CLUSTER + "\","
+ "\"AuthToken\":\"" + AUTH_TOKEN + "\"}")
.then()
.statusCode(200)
.body("Cluster.Name", equalTo(AUTH_CLUSTER))
.body("Cluster.Status", equalTo("available"))
.extract()
.path("Cluster.ClusterEndpoint.Port");
}
@Test
@Order(5)
void passwordClusterRejectsUnauthenticatedCommand() throws Exception {
assertEquals("-NOAUTH Authentication required.\r\n",
sendCommand(authPort, respArray("PING")));
}
@Test
@Order(6)
void authTokenAllowsAccess() throws Exception {
// Exercises end-to-end that CreateCluster propagated AuthToken to the proxy.
try (Socket socket = openSocket(authPort)) {
write(socket, respArray("AUTH", AUTH_TOKEN));
assertEquals("+OK\r\n", readLine(socket));
write(socket, respArray("PING"));
assertEquals("+PONG\r\n", readLine(socket));
}
}
@Test
@Order(7)
void wrongPasswordRejected() throws Exception {
assertEquals("-ERR invalid username-password pair or user is disabled.\r\n",
sendCommand(authPort, respArray("AUTH", "wrong-token")));
}
@Test
@Order(8)
void deleteClusterReleasesProxyPortForReuse() {
deleteCluster(OPEN_CLUSTER)
.then()
.statusCode(200)
.body("Cluster.Name", equalTo(OPEN_CLUSTER));
int reusedPort = memorydb("CreateCluster",
"{\"ClusterName\":\"" + OPEN_CLUSTER + "-reused\"}")
.then()
.statusCode(200)
.body("Cluster.ClusterEndpoint.Address", equalTo("localhost"))
.extract()
.path("Cluster.ClusterEndpoint.Port");
assertEquals(openPort, reusedPort);
deleteCluster(OPEN_CLUSTER + "-reused").then().statusCode(200);
}
// ──────────────────────────── Helpers ────────────────────────────
private static Response memorydb(String action, String body) {
return given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonMemoryDB." + action)
.header("Authorization", AUTH_HEADER)
.body(body)
.when()
.post("/");
}
private static Response deleteCluster(String name) {
return memorydb("DeleteCluster", "{\"ClusterName\":\"" + name + "\"}");
}
private static boolean isDockerAvailable() {
try {
Process process = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}")
.redirectErrorStream(true)
.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.setSoTimeout(SOCKET_TIMEOUT_MS);
return socket;
}
private static String sendCommand(int port, String command) throws Exception {
try (Socket socket = openSocket(port)) {
write(socket, command);
return readLine(socket);
}
}
private static void write(Socket socket, String command) throws IOException {
OutputStream out = socket.getOutputStream();
out.write(command.getBytes(StandardCharsets.UTF_8));
out.flush();
}
private static String readLine(Socket socket) throws IOException {
for (int attempt = 1; attempt <= READ_LINE_MAX_ATTEMPTS; attempt++) {
try {
return readLineOnce(socket);
} catch (SocketTimeoutException e) {
if (attempt == READ_LINE_MAX_ATTEMPTS) {
throw new IOException("Redis response timed out after " + READ_LINE_MAX_ATTEMPTS
+ " attempts (" + SOCKET_TIMEOUT_MS + "ms each). Confirm Docker is running and "
+ "the Valkey container is healthy.", e);
}
}
}
throw new AssertionError("unreachable");
}
private static String readLineOnce(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
byte[] buffer = new byte[256];
int offset = 0;
while (offset < buffer.length) {
int read;
try {
read = in.read();
} catch (SocketTimeoutException e) {
if (offset == 0) {
throw e;
}
throw new IOException("Incomplete Redis line (" + offset + " bytes) before read timeout.", e);
}
if (read == -1) {
break;
}
buffer[offset++] = (byte) read;
if (offset >= 2 && buffer[offset - 2] == '\r' && buffer[offset - 1] == '\n') {
break;
}
}
return new String(buffer, 0, offset, StandardCharsets.UTF_8);
}
private static String respArray(String... parts) {
StringBuilder sb = new StringBuilder();
sb.append("*").append(parts.length).append("\r\n");
for (String part : parts) {
byte[] bytes = part.getBytes(StandardCharsets.UTF_8);
sb.append("$").append(bytes.length).append("\r\n");
sb.append(part).append("\r\n");
}
return sb.toString();
}
}
@@ -0,0 +1,169 @@
package io.github.hectorvent.floci.services.memorydb;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerHandle;
import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerManager;
import io.github.hectorvent.floci.services.memorydb.model.AuthMode;
import io.github.hectorvent.floci.services.memorydb.model.Cluster;
import io.github.hectorvent.floci.services.memorydb.model.ClusterStatus;
import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbProxyManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
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.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class MemoryDbServiceTest {
private MemoryDbService service;
private MemoryDbContainerManager containerManager;
private EmulatorConfig.MemoryDbServiceConfig mdbConfig;
@BeforeEach
void setUp() {
containerManager = mock(MemoryDbContainerManager.class);
MemoryDbProxyManager proxyManager = mock(MemoryDbProxyManager.class);
StorageFactory storageFactory = mock(StorageFactory.class);
EmulatorConfig config = mock(EmulatorConfig.class);
RegionResolver regionResolver = mock(RegionResolver.class);
EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class);
mdbConfig = mock(EmulatorConfig.MemoryDbServiceConfig.class);
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.memorydb()).thenReturn(mdbConfig);
when(mdbConfig.proxyBasePort()).thenReturn(16400);
when(mdbConfig.proxyMaxPort()).thenReturn(16419);
when(mdbConfig.defaultImage()).thenReturn("valkey/valkey:8");
when(config.hostname()).thenReturn(Optional.of("localhost"));
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> new InMemoryStorage<>());
when(containerManager.start(anyString(), anyString()))
.thenReturn(new MemoryDbContainerHandle("cid", "cluster", "localhost", 6379));
doNothing().when(proxyManager).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
service = new MemoryDbService(containerManager, proxyManager, storageFactory, config, regionResolver);
}
@Test
void createAndDescribeCluster() {
Cluster spec = new Cluster();
spec.setName("my-cluster");
spec.setNodeType("db.t4g.small");
Cluster created = service.createCluster(spec, "us-east-1");
assertEquals("my-cluster", created.getName());
assertEquals(ClusterStatus.AVAILABLE, created.getStatus());
assertEquals("arn:aws:memorydb:us-east-1:000000000000:cluster/my-cluster", created.getArn());
assertEquals("localhost", created.getClusterEndpoint().address());
assertEquals(1, service.describeClusters("my-cluster").size());
assertEquals(1, service.describeClusters(null).size());
}
@Test
void duplicateClusterRejected() {
Cluster spec = new Cluster();
spec.setName("dupe");
service.createCluster(spec, "us-east-1");
Cluster again = new Cluster();
again.setName("dupe");
assertThrows(AwsException.class, () -> service.createCluster(again, "us-east-1"));
}
@Test
void deleteClusterRemovesIt() {
Cluster spec = new Cluster();
spec.setName("temp");
service.createCluster(spec, "us-east-1");
service.deleteCluster("temp");
assertThrows(AwsException.class, () -> service.getCluster("temp"));
}
@Test
void tagAndUntagResource() {
Cluster spec = new Cluster();
spec.setName("tagged");
Cluster created = service.createCluster(spec, "us-east-1");
String arn = created.getArn();
service.tagResource(arn, Map.of("env", "dev"));
assertEquals("dev", service.listTags(arn).get("env"));
service.untagResource(arn, List.of("env"));
assertFalse(service.listTags(arn).containsKey("env"));
}
@Test
void passwordValidationUsesAuthToken() {
Cluster spec = new Cluster();
spec.setName("secure");
spec.setAuthMode(AuthMode.PASSWORD);
spec.setAuthToken("s3cret");
service.createCluster(spec, "us-east-1");
assertTrue(service.validatePassword("secure", null, "s3cret"));
assertFalse(service.validatePassword("secure", null, "wrong"));
}
@Test
void nullClusterNameYieldsValidationErrorNotNpe() {
AwsException ex = assertThrows(AwsException.class, () -> service.getCluster(null));
assertEquals(400, ex.getHttpStatus());
assertThrows(AwsException.class, () -> service.deleteCluster(null));
assertThrows(AwsException.class, () -> service.updateCluster(" ", "desc"));
}
@Test
void failedProvisioningReleasesProxyPort() {
when(mdbConfig.proxyBasePort()).thenReturn(16400);
when(mdbConfig.proxyMaxPort()).thenReturn(16400); // exactly one port available
when(containerManager.start(anyString(), anyString()))
.thenThrow(new RuntimeException("docker unavailable"))
.thenReturn(new MemoryDbContainerHandle("cid", "c2", "localhost", 6379));
Cluster first = new Cluster();
first.setName("c1");
assertThrows(RuntimeException.class, () -> service.createCluster(first, "us-east-1"));
// The single port must have been released, so a second create still succeeds
Cluster second = new Cluster();
second.setName("c2");
Cluster created = service.createCluster(second, "us-east-1");
assertEquals(ClusterStatus.AVAILABLE, created.getStatus());
}
@Test
void mockModeSkipsContainerAndReportsStandardPort() {
when(mdbConfig.mock()).thenReturn(true);
Cluster spec = new Cluster();
spec.setName("mock-cluster");
Cluster created = service.createCluster(spec, "us-east-1");
assertEquals(ClusterStatus.AVAILABLE, created.getStatus());
assertEquals("localhost", created.getClusterEndpoint().address());
assertEquals(6379, created.getClusterEndpoint().port());
verifyNoInteractions(containerManager);
}
}