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

@@ -167,6 +167,7 @@ public interface EmulatorConfig {
AppConfigStorageConfig appconfig();
AppConfigDataStorageConfig appconfigdata();
ElastiCacheStorageConfig elasticache();
MemoryDbStorageConfig memorydb();
RdsStorageConfig rds();
Ec2StorageConfig ec2();
NeptuneStorageConfig neptune();
@@ -268,6 +269,13 @@ public interface EmulatorConfig {
long flushIntervalMs();
}
interface MemoryDbStorageConfig {
Optional<String> mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface RdsStorageConfig {
Optional<String> mode();
}
@@ -333,6 +341,7 @@ public interface EmulatorConfig {
IamServiceConfig iam();
MskServiceConfig msk();
ElastiCacheServiceConfig elasticache();
MemoryDbServiceConfig memorydb();
RdsServiceConfig rds();
RdsDataServiceConfig rdsData();
EventBridgeServiceConfig eventbridge();
@@ -542,6 +551,26 @@ public interface EmulatorConfig {
Optional<String> dockerNetwork();
}
interface MemoryDbServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("false")
boolean mock();
@WithDefault("6400")
int proxyBasePort();
@WithDefault("6419")
int proxyMaxPort();
@WithDefault("valkey/valkey:8")
String defaultImage();
/** Docker network to attach MemoryDB containers to. Empty = default bridge. */
Optional<String> dockerNetwork();
}
interface RdsServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -26,6 +26,7 @@ import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler;
import io.github.hectorvent.floci.services.cloudmap.CloudMapHandler;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler;
import io.github.hectorvent.floci.services.emr.EmrHandler;
import io.github.hectorvent.floci.services.memorydb.MemoryDbHandler;
import io.github.hectorvent.floci.services.wafv2.WafV2Handler;
import io.github.hectorvent.floci.services.kinesis.KinesisJsonHandler;
import io.github.hectorvent.floci.services.kms.KmsJsonHandler;
@@ -60,6 +61,7 @@ public class AwsJson11Controller {
private final EventBridgeHandler eventBridgeHandler;
private final CloudMapHandler cloudMapHandler;
private final EmrHandler emrHandler;
private final MemoryDbHandler memoryDbHandler;
private final WafV2Handler wafV2Handler;
private final CloudWatchLogsHandler cloudWatchLogsHandler;
private final SecretsManagerJsonHandler secretsManagerJsonHandler;
@@ -93,6 +95,7 @@ public class AwsJson11Controller {
SsmJsonHandler ssmJsonHandler, EventBridgeHandler eventBridgeHandler,
CloudMapHandler cloudMapHandler,
EmrHandler emrHandler,
MemoryDbHandler memoryDbHandler,
WafV2Handler wafV2Handler,
CloudWatchLogsHandler cloudWatchLogsHandler,
SecretsManagerJsonHandler secretsManagerJsonHandler,
@@ -123,6 +126,7 @@ public class AwsJson11Controller {
this.eventBridgeHandler = eventBridgeHandler;
this.cloudMapHandler = cloudMapHandler;
this.emrHandler = emrHandler;
this.memoryDbHandler = memoryDbHandler;
this.wafV2Handler = wafV2Handler;
this.cloudWatchLogsHandler = cloudWatchLogsHandler;
this.secretsManagerJsonHandler = secretsManagerJsonHandler;
@@ -182,6 +186,7 @@ public class AwsJson11Controller {
case "servicediscovery" -> cloudMapHandler.handle(action, request, region);
case "elasticmapreduce" -> emrHandler.handle(action, request, region);
case "wafv2" -> wafV2Handler.handle(action, request, region);
case "memorydb" -> memoryDbHandler.handle(action, request, region);
case "logs" -> cloudWatchLogsHandler.handle(action, request, region);
case "secretsmanager" -> secretsManagerJsonHandler.handle(action, request, region);
case "kinesis" -> kinesisJsonHandler.handle(action, request, region);
@@ -86,6 +86,11 @@ public class ResolvedServiceCatalog {
config.storage().services().elasticache().flushIntervalMs(), AwsNamespaces.EC, ServiceProtocol.QUERY,
protocols(ServiceProtocol.QUERY),
Set.of(), Set.of("elasticache"), Set.of(), Set.of()),
descriptor("memorydb", "memorydb", config.services().memorydb().enabled(), true,
"memorydb", storageMode(config.storage().services().memorydb().mode(), config.storage().mode()),
config.storage().services().memorydb().flushIntervalMs(), null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("AmazonMemoryDB."), Set.of("memorydb"), Set.of(), Set.of()),
descriptor("rds", "rds", config.services().rds().enabled(), true,
"rds", storageMode(config.storage().services().rds().mode(), config.storage().mode()),
5000L, AwsNamespaces.RDS, ServiceProtocol.QUERY,
@@ -19,6 +19,8 @@ import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerMan
import io.github.hectorvent.floci.services.neptune.proxy.NeptuneProxyManager;
import io.github.hectorvent.floci.services.pipes.PipesService;
import io.github.hectorvent.floci.services.rds.RdsService;
import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerManager;
import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbProxyManager;
import io.github.hectorvent.floci.services.rds.container.RdsContainerManager;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
import io.quarkus.runtime.Quarkus;
@@ -62,6 +64,8 @@ public class EmulatorLifecycle {
private final ElastiCacheProxyManager elastiCacheProxyManager;
private final RdsContainerManager rdsContainerManager;
private final RdsProxyManager rdsProxyManager;
private final MemoryDbContainerManager memoryDbContainerManager;
private final MemoryDbProxyManager memoryDbProxyManager;
private final DocDbContainerManager docDbContainerManager;
private final NeptuneContainerManager neptuneContainerManager;
private final NeptuneProxyManager neptuneProxyManager;
@@ -84,6 +88,8 @@ public class EmulatorLifecycle {
ElastiCacheProxyManager elastiCacheProxyManager,
RdsContainerManager rdsContainerManager,
RdsProxyManager rdsProxyManager,
MemoryDbContainerManager memoryDbContainerManager,
MemoryDbProxyManager memoryDbProxyManager,
DocDbContainerManager docDbContainerManager,
NeptuneContainerManager neptuneContainerManager,
NeptuneProxyManager neptuneProxyManager,
@@ -105,6 +111,8 @@ public class EmulatorLifecycle {
this.elastiCacheProxyManager = elastiCacheProxyManager;
this.rdsContainerManager = rdsContainerManager;
this.rdsProxyManager = rdsProxyManager;
this.memoryDbContainerManager = memoryDbContainerManager;
this.memoryDbProxyManager = memoryDbProxyManager;
this.docDbContainerManager = docDbContainerManager;
this.neptuneContainerManager = neptuneContainerManager;
this.neptuneProxyManager = neptuneProxyManager;
@@ -230,10 +238,12 @@ public class EmulatorLifecycle {
}
elastiCacheProxyManager.stopAll();
rdsProxyManager.stopAll();
memoryDbProxyManager.stopAll();
neptuneProxyManager.stopAll();
elastiCacheContainerManager.stopAll();
elastiCacheMemcachedContainerManager.stopAll();
rdsContainerManager.stopAll();
memoryDbContainerManager.stopAll();
docDbContainerManager.stopAll();
neptuneContainerManager.stopAll();
ecrRegistryManager.shutdown();
@@ -0,0 +1,191 @@
package io.github.hectorvent.floci.services.memorydb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsJson11Controller;
import io.github.hectorvent.floci.services.memorydb.model.AuthMode;
import io.github.hectorvent.floci.services.memorydb.model.Cluster;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* MemoryDB JSON 1.1 handler. Dispatched from {@link AwsJson11Controller} under the
* {@code AmazonMemoryDB.} target prefix.
*/
@ApplicationScoped
public class MemoryDbHandler {
private static final Logger LOG = Logger.getLogger(MemoryDbHandler.class);
private final MemoryDbService service;
private final ObjectMapper objectMapper;
@Inject
public MemoryDbHandler(MemoryDbService service, ObjectMapper objectMapper) {
this.service = service;
this.objectMapper = objectMapper;
}
public Response handle(String action, JsonNode request, String region) {
LOG.debugv("MemoryDB action: {0}", action);
try {
return switch (action) {
case "CreateCluster" -> handleCreateCluster(request, region);
case "DescribeClusters" -> handleDescribeClusters(request);
case "UpdateCluster" -> handleUpdateCluster(request);
case "DeleteCluster" -> handleDeleteCluster(request);
case "ListTags" -> handleListTags(request);
case "TagResource" -> handleTagResource(request);
case "UntagResource" -> handleUntagResource(request);
default -> Response.status(400)
.entity(new AwsErrorResponse("UnknownOperationException",
"Operation " + action + " is not supported."))
.build();
};
} catch (AwsException e) {
return Response.status(e.getHttpStatus())
.entity(new AwsErrorResponse(e.jsonType(), e.getMessage()))
.build();
} catch (Exception e) {
LOG.errorv("MemoryDB error processing action {0}: {1}", action, e.getMessage());
return Response.status(500)
.entity(new AwsErrorResponse("InternalFailure", e.getMessage()))
.build();
}
}
private Response handleCreateCluster(JsonNode request, String region) {
Cluster spec = new Cluster();
spec.setName(text(request, "ClusterName"));
spec.setDescription(text(request, "Description"));
spec.setNodeType(text(request, "NodeType"));
if (request.hasNonNull("NumShards")) {
spec.setNumberOfShards(request.get("NumShards").asInt());
}
spec.setEngine(text(request, "Engine"));
spec.setEngineVersion(text(request, "EngineVersion"));
spec.setAclName(text(request, "ACLName"));
spec.setTlsEnabled(request.path("TLSEnabled").asBoolean(false));
spec.setAuthToken(text(request, "AuthToken"));
spec.setAuthMode(resolveAuthMode(request));
spec.setTags(parseTags(request.path("Tags")));
Cluster created = service.createCluster(spec, region);
ObjectNode response = objectMapper.createObjectNode();
response.set("Cluster", clusterNode(created));
return Response.ok(response).build();
}
private Response handleDescribeClusters(JsonNode request) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = response.putArray("Clusters");
for (Cluster cluster : service.describeClusters(text(request, "ClusterName"))) {
arr.add(clusterNode(cluster));
}
return Response.ok(response).build();
}
private Response handleUpdateCluster(JsonNode request) {
Cluster updated = service.updateCluster(text(request, "ClusterName"), text(request, "Description"));
ObjectNode response = objectMapper.createObjectNode();
response.set("Cluster", clusterNode(updated));
return Response.ok(response).build();
}
private Response handleDeleteCluster(JsonNode request) {
Cluster deleted = service.deleteCluster(text(request, "ClusterName"));
ObjectNode response = objectMapper.createObjectNode();
response.set("Cluster", clusterNode(deleted));
return Response.ok(response).build();
}
private Response handleListTags(JsonNode request) {
Map<String, String> tags = service.listTags(text(request, "ResourceArn"));
return Response.ok(tagListResponse(tags)).build();
}
private Response handleTagResource(JsonNode request) {
Map<String, String> tags = service.tagResource(text(request, "ResourceArn"),
parseTags(request.path("Tags")));
return Response.ok(tagListResponse(tags)).build();
}
private Response handleUntagResource(JsonNode request) {
List<String> keys = new java.util.ArrayList<>();
request.path("TagKeys").forEach(k -> keys.add(k.asText()));
Map<String, String> tags = service.untagResource(text(request, "ResourceArn"), keys);
return Response.ok(tagListResponse(tags)).build();
}
// ──────────────────────────── Builders ────────────────────────────
private ObjectNode clusterNode(Cluster cluster) {
ObjectNode node = objectMapper.createObjectNode();
node.put("Name", cluster.getName());
if (cluster.getDescription() != null) {
node.put("Description", cluster.getDescription());
}
node.put("Status", cluster.getStatus().wireValue());
node.put("NodeType", cluster.getNodeType());
node.put("NumberOfShards", cluster.getNumberOfShards());
node.put("Engine", cluster.getEngine());
node.put("EngineVersion", cluster.getEngineVersion());
node.put("ACLName", cluster.getAclName());
node.put("TLSEnabled", cluster.isTlsEnabled());
node.put("ARN", cluster.getArn());
if (cluster.getClusterEndpoint() != null) {
ObjectNode endpoint = node.putObject("ClusterEndpoint");
endpoint.put("Address", cluster.getClusterEndpoint().address());
endpoint.put("Port", cluster.getClusterEndpoint().port());
}
return node;
}
private ObjectNode tagListResponse(Map<String, String> tags) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = response.putArray("TagList");
tags.forEach((k, v) -> {
ObjectNode tag = objectMapper.createObjectNode();
tag.put("Key", k);
tag.put("Value", v);
arr.add(tag);
});
return response;
}
// ──────────────────────────── Parsing ────────────────────────────
private AuthMode resolveAuthMode(JsonNode request) {
if (request.hasNonNull("AuthToken") && !request.get("AuthToken").asText().isBlank()) {
return AuthMode.PASSWORD;
}
return AuthMode.NO_AUTH;
}
private Map<String, String> parseTags(JsonNode tagsNode) {
Map<String, String> tags = new LinkedHashMap<>();
if (tagsNode != null && tagsNode.isArray()) {
for (JsonNode tag : tagsNode) {
String key = tag.path("Key").asText(null);
if (key != null) {
tags.put(key, tag.path("Value").asText(null));
}
}
}
return tags;
}
private String text(JsonNode request, String field) {
JsonNode node = request.path(field);
return node.isMissingNode() || node.isNull() ? null : node.asText(null);
}
}
@@ -0,0 +1,247 @@
package io.github.hectorvent.floci.services.memorydb;
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;
import io.github.hectorvent.floci.core.storage.StorageBackend;
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.model.Endpoint;
import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbProxyManager;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Core MemoryDB business logic — clusters and tags.
* Creates a real Redis-compatible container plus an auth proxy on cluster creation.
*/
@ApplicationScoped
public class MemoryDbService {
private static final Logger LOG = Logger.getLogger(MemoryDbService.class);
private static final String DEFAULT_ENGINE = "redis";
private static final String DEFAULT_ACL = "open-access";
private static final int REDIS_PORT = 6379;
private final StorageBackend<String, Cluster> clusters;
private final MemoryDbContainerManager containerManager;
private final MemoryDbProxyManager proxyManager;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
@Inject
public MemoryDbService(MemoryDbContainerManager containerManager,
MemoryDbProxyManager proxyManager,
StorageFactory storageFactory,
EmulatorConfig config,
RegionResolver regionResolver) {
this.containerManager = containerManager;
this.proxyManager = proxyManager;
this.config = config;
this.regionResolver = regionResolver;
this.clusters = storageFactory.create("memorydb", "memorydb-clusters.json",
new TypeReference<Map<String, Cluster>>() {});
}
public Cluster createCluster(Cluster spec, String region) {
String name = spec.getName();
if (name == null || name.isBlank()) {
throw new AwsException("InvalidParameterValueException", "ClusterName is required.", 400);
}
if (clusters.get(name).isPresent()) {
throw new AwsException("ClusterAlreadyExistsFault",
"Cluster with specified name already exists.", 400);
}
AuthMode authMode = spec.getAuthMode() != null ? spec.getAuthMode() : AuthMode.NO_AUTH;
Cluster cluster = new Cluster();
cluster.setName(name);
cluster.setDescription(spec.getDescription());
cluster.setStatus(ClusterStatus.AVAILABLE);
cluster.setNodeType(spec.getNodeType() != null ? spec.getNodeType() : "db.t4g.small");
cluster.setNumberOfShards(spec.getNumberOfShards() > 0 ? spec.getNumberOfShards() : 1);
cluster.setEngine(spec.getEngine() != null ? spec.getEngine() : DEFAULT_ENGINE);
cluster.setEngineVersion(spec.getEngineVersion() != null ? spec.getEngineVersion() : "7.1");
cluster.setAclName(spec.getAclName() != null ? spec.getAclName() : DEFAULT_ACL);
cluster.setTlsEnabled(spec.isTlsEnabled());
cluster.setAuthMode(authMode);
cluster.setArn(buildArn(region, name));
cluster.setCreatedAt(Instant.now());
cluster.setAuthToken(spec.getAuthToken());
cluster.setTags(spec.getTags());
if (config.services().memorydb().mock()) {
LOG.infov("Creating MemoryDB cluster {0} in mock mode (no container)", name);
cluster.setClusterEndpoint(new Endpoint(resolveEndpointHost(), REDIS_PORT));
} else {
startBackend(cluster, authMode);
}
clusters.put(name, cluster);
LOG.infov("MemoryDB cluster {0} created, endpoint={1}:{2}",
name, cluster.getClusterEndpoint().address(),
String.valueOf(cluster.getClusterEndpoint().port()));
return cluster;
}
public Cluster getCluster(String name) {
if (name == null || name.isBlank()) {
throw new AwsException("InvalidParameterValueException", "ClusterName is required.", 400);
}
return clusters.get(name).orElseThrow(() ->
new AwsException("ClusterNotFoundFault", "Cluster not found.", 404));
}
public Collection<Cluster> describeClusters(String filterName) {
if (filterName != null && !filterName.isBlank()) {
return clusters.get(filterName)
.map(List::of)
.orElseThrow(() -> new AwsException("ClusterNotFoundFault",
"Cluster not found.", 404));
}
return clusters.scan(k -> true);
}
public Cluster updateCluster(String name, String description) {
Cluster cluster = getCluster(name);
if (description != null) {
cluster.setDescription(description);
}
clusters.put(name, cluster);
return cluster;
}
public Cluster deleteCluster(String name) {
Cluster cluster = getCluster(name);
cluster.setStatus(ClusterStatus.DELETING);
proxyManager.stopProxy(name);
if (cluster.getContainerId() != null) {
containerManager.stop(new MemoryDbContainerHandle(
cluster.getContainerId(), name, cluster.getContainerHost(), cluster.getContainerPort()));
}
releaseProxyPort(cluster.getProxyPort());
clusters.delete(name);
LOG.infov("MemoryDB cluster {0} deleted", name);
return cluster;
}
public Map<String, String> listTags(String resourceArn) {
return clusterByArn(resourceArn).getTags();
}
public Map<String, String> tagResource(String resourceArn, Map<String, String> tags) {
Cluster cluster = clusterByArn(resourceArn);
cluster.getTags().putAll(tags);
clusters.put(cluster.getName(), cluster);
return cluster.getTags();
}
public Map<String, String> untagResource(String resourceArn, List<String> tagKeys) {
Cluster cluster = clusterByArn(resourceArn);
tagKeys.forEach(cluster.getTags()::remove);
clusters.put(cluster.getName(), cluster);
return cluster.getTags();
}
/**
* Validates a Redis AUTH password for the given cluster against its stored auth token.
*/
public boolean validatePassword(String clusterName, String username, String password) {
Cluster cluster = clusters.get(clusterName).orElse(null);
if (cluster == null || cluster.getAuthToken() == null) {
return false;
}
return cluster.getAuthToken().equals(password);
}
private Cluster clusterByArn(String resourceArn) {
if (resourceArn == null) {
throw new AwsException("InvalidParameterValueException", "ResourceArn is required.", 400);
}
return clusters.scan(k -> true).stream()
.filter(c -> resourceArn.equals(c.getArn()))
.findFirst()
.orElseThrow(() -> new AwsException("ClusterNotFoundFault", "Cluster not found.", 404));
}
private void startBackend(Cluster cluster, AuthMode authMode) {
String name = cluster.getName();
int proxyPort = allocateProxyPort();
String image = config.services().memorydb().defaultImage();
LOG.infov("Creating MemoryDB cluster {0} with authMode={1} on proxy port {2}",
name, authMode, String.valueOf(proxyPort));
MemoryDbContainerHandle handle = null;
try {
handle = containerManager.start(name, image);
cluster.setClusterEndpoint(new Endpoint(resolveEndpointHost(), proxyPort));
cluster.setProxyPort(proxyPort);
cluster.setContainerId(handle.getContainerId());
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
proxyManager.startProxy(name, authMode, proxyPort,
handle.getHost(), handle.getPort(),
(username, password) -> validatePassword(name, username, password));
} catch (RuntimeException e) {
LOG.warnv("MemoryDB cluster {0} provisioning failed, rolling back: {1}", name, e.getMessage());
rollbackBackend(name, handle, proxyPort);
throw e;
}
}
private void rollbackBackend(String name, MemoryDbContainerHandle handle, int proxyPort) {
try {
proxyManager.stopProxy(name);
if (handle != null) {
containerManager.stop(handle);
}
} catch (RuntimeException e) {
LOG.warnv("Error rolling back MemoryDB cluster {0}: {1}", name, e.getMessage());
} finally {
releaseProxyPort(proxyPort);
}
}
private String buildArn(String region, String name) {
return "arn:aws:memorydb:" + region + ":" + regionResolver.getAccountId() + ":cluster/" + name;
}
private String resolveEndpointHost() {
return config.hostname().orElse("localhost");
}
private int allocateProxyPort() {
int base = config.services().memorydb().proxyBasePort();
int max = config.services().memorydb().proxyMaxPort();
for (int port = base; port <= max; port++) {
if (usedPorts.add(port)) {
return port;
}
}
throw new AwsException("InsufficientClusterCapacityFault",
"No available proxy ports in range " + base + "-" + max, 503);
}
private void releaseProxyPort(int port) {
usedPorts.remove(port);
}
}
@@ -0,0 +1,29 @@
package io.github.hectorvent.floci.services.memorydb.container;
import java.io.Closeable;
/**
* Wraps a running backend Docker container for a MemoryDB cluster.
*/
public class MemoryDbContainerHandle {
private final String containerId;
private final String clusterName;
private final String host;
private final int port;
private Closeable logStream;
public MemoryDbContainerHandle(String containerId, String clusterName, String host, int port) {
this.containerId = containerId;
this.clusterName = clusterName;
this.host = host;
this.port = port;
}
public String getContainerId() { return containerId; }
public String getClusterName() { return clusterName; }
public String getHost() { return host; }
public int getPort() { return port; }
public Closeable getLogStream() { return logStream; }
public void setLogStream(Closeable logStream) { this.logStream = logStream; }
}
@@ -0,0 +1,184 @@
package io.github.hectorvent.floci.services.memorydb.container;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Manages backend Docker container lifecycle for MemoryDB clusters.
* In native (dev) mode, binds container port 6379 to a random host port.
* In Docker mode, uses the container's internal network IP directly.
*/
@ApplicationScoped
public class MemoryDbContainerManager {
private static final Logger LOG = Logger.getLogger(MemoryDbContainerManager.class);
private static final int BACKEND_PORT = 6379;
private static final int BACKEND_READY_DEADLINE_MS = 60_000;
private static final int BACKEND_READY_RETRY_MS = 100;
private static final int BACKEND_PROBE_CONNECT_MS = 2_000;
private static final byte[] RESP_PING = "*1\r\n$4\r\nPING\r\n".getBytes(StandardCharsets.UTF_8);
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final ContainerLogStreamer logStreamer;
private final ContainerDetector containerDetector;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final Map<String, MemoryDbContainerHandle> activeContainers = new ConcurrentHashMap<>();
@Inject
public MemoryDbContainerManager(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
ContainerLogStreamer logStreamer,
ContainerDetector containerDetector,
EmulatorConfig config,
RegionResolver regionResolver) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.logStreamer = logStreamer;
this.containerDetector = containerDetector;
this.config = config;
this.regionResolver = regionResolver;
}
public MemoryDbContainerHandle start(String clusterName, String image) {
LOG.infov("Starting MemoryDB backend container for cluster: {0}", clusterName);
String containerName = "floci-memorydb-" + clusterName;
lifecycleManager.removeIfExists(containerName);
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(containerName)
.withDockerNetwork(config.services().memorydb().dockerNetwork())
.withLogRotation();
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(BACKEND_PORT);
} else {
specBuilder.withExposedPort(BACKEND_PORT);
}
ContainerSpec spec = specBuilder.build();
ContainerInfo info = lifecycleManager.createAndStart(spec);
EndpointInfo endpoint = info.getEndpoint(BACKEND_PORT);
LOG.infov("MemoryDB backend for cluster {0}: {1}", clusterName, endpoint);
MemoryDbContainerHandle handle = new MemoryDbContainerHandle(
info.containerId(), clusterName, endpoint.host(), endpoint.port());
activeContainers.put(clusterName, handle);
String shortId = info.containerId().length() >= 8
? info.containerId().substring(0, 8)
: info.containerId();
String logGroup = "/aws/memorydb/cluster/" + clusterName + "/engine-log";
String logStream = logStreamer.generateLogStreamName(shortId);
String region = regionResolver.getDefaultRegion();
Closeable logHandle = logStreamer.attach(
info.containerId(), logGroup, logStream, region, "memorydb:" + clusterName);
handle.setLogStream(logHandle);
waitForBackendReady(clusterName, endpoint.host(), endpoint.port());
return handle;
}
private static void waitForBackendReady(String clusterName, String host, int port) {
long deadline = System.currentTimeMillis() + BACKEND_READY_DEADLINE_MS;
int attempt = 0;
while (System.currentTimeMillis() < deadline) {
attempt++;
try (Socket s = new Socket()) {
s.connect(new InetSocketAddress(host, port), BACKEND_PROBE_CONNECT_MS);
s.setTcpNoDelay(true);
s.setSoTimeout(BACKEND_PROBE_CONNECT_MS);
OutputStream out = s.getOutputStream();
out.write(RESP_PING);
out.flush();
String line = readAsciiLineCrLf(s.getInputStream());
if (line.startsWith("+PONG")) {
if (attempt > 1) {
LOG.infov("MemoryDB backend ready for cluster {0} after {1} probe attempt(s)", clusterName, attempt);
}
return;
}
if (LOG.isDebugEnabled()) {
LOG.debugv("MemoryDB backend probe for cluster {0}: unexpected line {1}", clusterName, line);
}
} catch (IOException e) {
if (LOG.isDebugEnabled()) {
LOG.debugv("MemoryDB backend probe for cluster {0} attempt {1}: {2}", clusterName, attempt, e.getMessage());
}
}
try {
Thread.sleep(BACKEND_READY_RETRY_MS);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while waiting for MemoryDB backend " + clusterName, ie);
}
}
throw new RuntimeException(
"MemoryDB backend for cluster " + clusterName + " did not become ready on " + host + ":" + port
+ " within " + BACKEND_READY_DEADLINE_MS + "ms");
}
private static String readAsciiLineCrLf(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
int b;
while ((b = in.read()) != -1) {
if (b == '\r') {
int next = in.read();
if (next != '\n') {
throw new IOException("Expected \\n after \\r in RESP line");
}
break;
}
sb.append((char) b);
}
return sb.toString();
}
public void stop(MemoryDbContainerHandle handle) {
if (handle == null) {
return;
}
activeContainers.remove(handle.getClusterName());
lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream());
}
public void stopAll() {
List<MemoryDbContainerHandle> handles = new ArrayList<>(activeContainers.values());
if (!handles.isEmpty()) {
LOG.infov("Stopping {0} MemoryDB container(s) on shutdown", handles.size());
}
for (MemoryDbContainerHandle handle : handles) {
stop(handle);
}
}
}
@@ -0,0 +1,5 @@
package io.github.hectorvent.floci.services.memorydb.model;
public enum AuthMode {
IAM, PASSWORD, NO_AUTH
}
@@ -0,0 +1,94 @@
package io.github.hectorvent.floci.services.memorydb.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
@RegisterForReflection
public class Cluster {
private String name;
private String description;
private ClusterStatus status;
private String nodeType;
private int numberOfShards;
private String engine;
private String engineVersion;
private String aclName;
private boolean tlsEnabled;
private AuthMode authMode;
private Endpoint clusterEndpoint;
private String arn;
private Instant createdAt;
private int proxyPort;
private String authToken; // stored plain-text for PASSWORD auth validation in the proxy
private Map<String, String> tags = new LinkedHashMap<>();
// Transient fields — not persisted, restored on container restart
private transient String containerId;
private transient String containerHost;
private transient int containerPort;
public Cluster() {}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public ClusterStatus getStatus() { return status; }
public void setStatus(ClusterStatus status) { this.status = status; }
public String getNodeType() { return nodeType; }
public void setNodeType(String nodeType) { this.nodeType = nodeType; }
public int getNumberOfShards() { return numberOfShards; }
public void setNumberOfShards(int numberOfShards) { this.numberOfShards = numberOfShards; }
public String getEngine() { return engine; }
public void setEngine(String engine) { this.engine = engine; }
public String getEngineVersion() { return engineVersion; }
public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; }
public String getAclName() { return aclName; }
public void setAclName(String aclName) { this.aclName = aclName; }
public boolean isTlsEnabled() { return tlsEnabled; }
public void setTlsEnabled(boolean tlsEnabled) { this.tlsEnabled = tlsEnabled; }
public AuthMode getAuthMode() { return authMode; }
public void setAuthMode(AuthMode authMode) { this.authMode = authMode; }
public Endpoint getClusterEndpoint() { return clusterEndpoint; }
public void setClusterEndpoint(Endpoint clusterEndpoint) { this.clusterEndpoint = clusterEndpoint; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
public int getProxyPort() { return proxyPort; }
public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; }
public String getAuthToken() { return authToken; }
public void setAuthToken(String authToken) { this.authToken = authToken; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) {
this.tags = tags != null ? tags : new LinkedHashMap<>();
}
public String getContainerId() { return containerId; }
public void setContainerId(String containerId) { this.containerId = containerId; }
public String getContainerHost() { return containerHost; }
public void setContainerHost(String containerHost) { this.containerHost = containerHost; }
public int getContainerPort() { return containerPort; }
public void setContainerPort(int containerPort) { this.containerPort = containerPort; }
}
@@ -0,0 +1,22 @@
package io.github.hectorvent.floci.services.memorydb.model;
/**
* MemoryDB cluster lifecycle states. The wire value is lowercase
* (e.g. {@code available}) to match the real AWS MemoryDB API.
*/
public enum ClusterStatus {
CREATING("creating"),
AVAILABLE("available"),
UPDATING("updating"),
DELETING("deleting");
private final String wireValue;
ClusterStatus(String wireValue) {
this.wireValue = wireValue;
}
public String wireValue() {
return wireValue;
}
}
@@ -0,0 +1,3 @@
package io.github.hectorvent.floci.services.memorydb.model;
public record Endpoint(String address, int port) {}
@@ -0,0 +1,221 @@
package io.github.hectorvent.floci.services.memorydb.proxy;
import io.github.hectorvent.floci.services.elasticache.proxy.RespReader;
import io.github.hectorvent.floci.services.elasticache.proxy.SigV4Validator;
import io.github.hectorvent.floci.services.memorydb.model.AuthMode;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
/**
* TCP auth proxy for a single MemoryDB cluster.
* Intercepts the Redis AUTH command, validates credentials (IAM or password),
* then becomes a transparent byte relay to the backend Redis container.
*
* <p>MemoryDB speaks the Redis wire protocol, so this reuses ElastiCache's
* {@link RespReader} and {@link SigV4Validator}. A future refactor should lift
* the shared Redis-auth pieces into a common package.
*/
public class MemoryDbAuthProxy {
private static final Logger LOG = Logger.getLogger(MemoryDbAuthProxy.class);
private static final byte[] OK_RESPONSE = "+OK\r\n".getBytes(StandardCharsets.UTF_8);
private static final byte[] NOAUTH_RESPONSE =
"-NOAUTH Authentication required.\r\n".getBytes(StandardCharsets.UTF_8);
private static final byte[] INVALID_AUTH_RESPONSE =
"-ERR invalid username-password pair or user is disabled.\r\n"
.getBytes(StandardCharsets.UTF_8);
private static final byte[] WRONG_ARGS_RESPONSE =
"-ERR wrong number of arguments for 'auth' command\r\n"
.getBytes(StandardCharsets.UTF_8);
private final String clusterName;
private final AuthMode authMode;
private final String backendHost;
private final int backendPort;
private final PasswordValidator passwordValidator;
private final SigV4Validator sigV4Validator;
private volatile boolean running;
private ServerSocket serverSocket;
public MemoryDbAuthProxy(String clusterName, AuthMode authMode,
String backendHost, int backendPort,
PasswordValidator passwordValidator,
SigV4Validator sigV4Validator) {
this.clusterName = clusterName;
this.authMode = authMode;
this.backendHost = backendHost;
this.backendPort = backendPort;
this.passwordValidator = passwordValidator;
this.sigV4Validator = sigV4Validator;
}
public void start(int proxyPort) throws IOException {
serverSocket = new ServerSocket(proxyPort);
running = true;
Thread.ofVirtual().name("memorydb-proxy-accept-" + clusterName).start(this::acceptLoop);
LOG.infov("MemoryDB proxy started for cluster {0} on port {1} → {2}:{3}",
clusterName, String.valueOf(proxyPort), backendHost, String.valueOf(backendPort));
}
public void stop() {
running = false;
try {
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
LOG.warnv("Error closing proxy server socket for cluster {0}: {1}", clusterName, e.getMessage());
}
}
private void acceptLoop() {
while (running) {
try {
Socket client = serverSocket.accept();
Thread.ofVirtual().name("memorydb-proxy-conn-" + clusterName).start(() -> handleConnection(client));
} catch (IOException e) {
if (running) {
LOG.warnv("Accept error for cluster {0}: {1}", clusterName, e.getMessage());
}
}
}
}
private void handleConnection(Socket client) {
try {
client.setTcpNoDelay(true);
RespReader reader = new RespReader(client.getInputStream());
String[] cmd = reader.readCommand();
if (cmd.length == 0) {
closeQuietly(client);
return;
}
if (cmd[0].equalsIgnoreCase("AUTH")) {
handleAuth(client, cmd);
} else if (authMode != AuthMode.NO_AUTH) {
client.getOutputStream().write(NOAUTH_RESPONSE);
client.getOutputStream().flush();
closeQuietly(client);
} else {
Socket backend = new Socket(backendHost, backendPort);
backend.setTcpNoDelay(true);
resendCommand(cmd, backend.getOutputStream());
bridge(client, backend);
}
} catch (Exception e) {
LOG.debugv("Connection error for cluster {0}: {1}", clusterName, e.getMessage());
closeQuietly(client);
}
}
private void handleAuth(Socket client, String[] cmd) throws IOException {
String username;
String password;
if (cmd.length == 2) {
username = null;
password = cmd[1];
} else if (cmd.length == 3) {
username = cmd[1];
password = cmd[2];
} else {
client.getOutputStream().write(WRONG_ARGS_RESPONSE);
client.getOutputStream().flush();
closeQuietly(client);
return;
}
boolean authenticated = validate(username, password);
if (!authenticated) {
client.getOutputStream().write(INVALID_AUTH_RESPONSE);
client.getOutputStream().flush();
closeQuietly(client);
return;
}
client.getOutputStream().write(OK_RESPONSE);
client.getOutputStream().flush();
Socket backend = new Socket(backendHost, backendPort);
backend.setTcpNoDelay(true);
bridge(client, backend);
}
private boolean validate(String username, String password) {
return switch (authMode) {
case IAM -> sigV4Validator.validate(password, clusterName, username);
case PASSWORD -> passwordValidator.validatePassword(username, password);
case NO_AUTH -> true;
};
}
private void bridge(Socket client, Socket backend) {
Thread t1 = Thread.ofPlatform().daemon(true).name("memorydb-relay-c2b-" + clusterName)
.start(() -> relay(client, backend));
Thread t2 = Thread.ofPlatform().daemon(true).name("memorydb-relay-b2c-" + clusterName)
.start(() -> relay(backend, client));
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
closeQuietly(client);
closeQuietly(backend);
}
}
private static void relay(Socket from, Socket to) {
byte[] buf = new byte[8192];
try {
InputStream in = from.getInputStream();
OutputStream out = to.getOutputStream();
int n;
while ((n = in.read(buf)) != -1) {
out.write(buf, 0, n);
out.flush();
}
} catch (IOException ignored) {
// Normal when either side closes the connection
}
}
private static void resendCommand(String[] args, OutputStream out) throws IOException {
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");
out.write(sb.toString().getBytes(StandardCharsets.UTF_8));
sb.setLength(0);
out.write(bytes);
out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}
if (sb.length() > 0) {
out.write(sb.toString().getBytes(StandardCharsets.UTF_8));
}
out.flush();
}
private static void closeQuietly(Socket s) {
try { s.close(); } catch (IOException ignored) {}
}
/**
* Callback interface for password validation, provided by MemoryDbService.
*/
@FunctionalInterface
public interface PasswordValidator {
boolean validatePassword(String username, String password);
}
}
@@ -0,0 +1,56 @@
package io.github.hectorvent.floci.services.memorydb.proxy;
import io.github.hectorvent.floci.services.elasticache.proxy.SigV4Validator;
import io.github.hectorvent.floci.services.memorydb.model.AuthMode;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
/**
* Registry of all active MemoryDB auth proxies. One proxy instance per cluster.
*/
@ApplicationScoped
public class MemoryDbProxyManager {
private static final Logger LOG = Logger.getLogger(MemoryDbProxyManager.class);
private final SigV4Validator sigV4Validator;
private final ConcurrentHashMap<String, MemoryDbAuthProxy> proxies = new ConcurrentHashMap<>();
@Inject
public MemoryDbProxyManager(SigV4Validator sigV4Validator) {
this.sigV4Validator = sigV4Validator;
}
public void startProxy(String clusterName, AuthMode authMode, int proxyPort,
String backendHost, int backendPort,
MemoryDbAuthProxy.PasswordValidator passwordValidator) {
MemoryDbAuthProxy proxy = new MemoryDbAuthProxy(
clusterName, authMode, backendHost, backendPort,
passwordValidator, sigV4Validator);
try {
proxy.start(proxyPort);
proxies.put(clusterName, proxy);
} catch (IOException e) {
throw new RuntimeException("Failed to start proxy for cluster " + clusterName
+ " on port " + proxyPort, e);
}
}
public void stopProxy(String clusterName) {
MemoryDbAuthProxy proxy = proxies.remove(clusterName);
if (proxy != null) {
proxy.stop();
LOG.infov("Stopped proxy for cluster {0}", clusterName);
}
}
public void stopAll() {
proxies.values().forEach(MemoryDbAuthProxy::stop);
proxies.clear();
LOG.info("Stopped all MemoryDB proxies");
}
}