Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Ahmed khaledfd904bc409cf
diff --git a/README.md b/README.md
index 14e957ce7c..845bb922a1 100644
--- a/README.md
+++ b/README.md
@@ -225,7 +225,7 @@ Floci supports local emulation for application services, data services, eventing
| Containers and compute | ECS, EC2, EKS, CodeBuild, CodeDeploy, Auto Scaling, ELB v2 |
| Data and analytics | Athena, Glue, EMR, Firehose, OpenSearch, Textract, Transcribe |
| Security and governance | WAF v2, CloudTrail |
-| Databases | RDS, RDS Data API, Neptune, DocumentDB |
+| Databases | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB |
| Messaging and transfer | SES, SES v2, Kinesis, Transfer Family |
| Cost and billing | Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports |
| Backup and config | AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation |
@@ -262,6 +262,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
| CloudWatch Logs | In-process | Log groups, streams, ingestion, filtering |
| CloudWatch Metrics | In-process | Custom metrics, statistics, alarms |
| ElastiCache | Real Docker | Redis / Valkey protocol, IAM auth, SigV4 validation |
+| MemoryDB | Real Docker | Redis / Valkey protocol via real containers; JSON 1.1 control plane; reuses ElastiCache RESP proxy |
| RDS | Real Docker | PostgreSQL, MySQL, MariaDB, IAM auth, JDBC-compatible engines |
| RDS Data API | REST JSON over real RDS containers | Raw SQL execution and transactions for local MySQL / MariaDB RDS resources |
| Neptune | Real Docker | Graph DB via TinkerPop Gremlin Server (default) or Neo4j for openCypher/Bolt (`NEPTUNE_DB_TYPE`); RDS-shaped control plane; SigV4 proxy on port 8182 |
diff --git a/docs/services/index.md b/docs/services/index.md
index d1ba6ebe5a..765e26dc6a 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -33,6 +33,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [CloudWatch Logs](cloudwatch.md) | `POST /` + `X-Amz-Target: Logs.*` | JSON 1.1 | 17 |
| [CloudWatch Metrics](cloudwatch.md#metrics) | `POST /` with `Action=` or JSON 1.1 | Query / JSON | 11 |
| [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 8 |
+| [MemoryDB](memorydb.md) | `POST /` + `X-Amz-Target: AmazonMemoryDB.*` + TCP proxy | JSON 1.1 + RESP | 7 |
| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 14 |
| [RDS Data API](rds-data.md) | `/Execute`, `/BeginTransaction`, `/CommitTransaction`, `/RollbackTransaction` | REST JSON | 4 |
| [MSK](msk.md) | `/v1/clusters/...`, `/api/v2/clusters/...` + Redpanda broker | REST JSON + Kafka | 8 |
diff --git a/docs/services/memorydb.md b/docs/services/memorydb.md
new file mode 100644
index 0000000000..eea80a91a4
--- /dev/null
+++ b/docs/services/memorydb.md
@@ -0,0 +1,77 @@
+# MemoryDB
+
+**Protocol:** JSON 1.1 (`X-Amz-Target: AmazonMemoryDB.*`) for management API + Redis RESP protocol for data plane
+**Management Endpoint:** `POST http://localhost:4566/`
+**Data Endpoint:** `localhost:<proxy-port>` (TCP)
+
+Floci manages real Valkey/Redis Docker containers and proxies TCP connections to them, so any Redis client works — including IAM-style authentication. MemoryDB is Redis wire-compatible, so it reuses Floci's ElastiCache RESP proxy and SigV4 validator.
+
+## Mock Mode
+
+Set `FLOCI_SERVICES_MEMORYDB_MOCK=true` to manage clusters as control-plane-only resources — no Redis container is started. The management API (`CreateCluster`, `DescribeClusters`, tagging, etc.) behaves normally and returns a `ClusterEndpoint` of `<hostname>:6379` (defaults to `localhost:6379`, controlled by `FLOCI_HOSTNAME`), but there is no live data plane to connect to. This is intended for Infrastructure-as-Code tools like Terraform and OpenTofu running in environments without a Docker socket, where you only need the AWS resources to exist and return consistent attributes.
+
+## Supported Management Actions
+
+| Action | Description |
+|---|---|
+| `CreateCluster` | Start a new MemoryDB (Redis/Valkey) cluster |
+| `DescribeClusters` | List clusters and their connection info |
+| `UpdateCluster` | Update mutable cluster attributes (e.g. description) |
+| `DeleteCluster` | Stop and remove a cluster |
+| `ListTags` | List tags for a cluster |
+| `TagResource` | Add tags to a cluster |
+| `UntagResource` | Remove tags from a cluster |
+
+## Configuration
+
+| Variable | Default | Description |
+|---|---|---|
+| `FLOCI_SERVICES_MEMORYDB_ENABLED` | `true` | Enable or disable the service |
+| `FLOCI_SERVICES_MEMORYDB_MOCK` | `false` | Track clusters without starting a real Redis container. Useful for IaC tools (Terraform/OpenTofu) when no Docker socket is available |
+| `FLOCI_SERVICES_MEMORYDB_PROXY_BASE_PORT` | `6400` | First host port in the MemoryDB proxy range |
+| `FLOCI_SERVICES_MEMORYDB_PROXY_MAX_PORT` | `6419` | Last host port in the MemoryDB proxy range |
+| `FLOCI_SERVICES_MEMORYDB_DEFAULT_IMAGE` | `valkey/valkey:8` | Docker image for Redis/Valkey containers |
+
+### Docker Compose
+
+MemoryDB requires the Docker socket and port range exposure. For private registry authentication and other Docker settings see [Docker Configuration](../configuration/docker.md).
+
+```yaml
+services:
+ floci:
+ image: floci/floci:latest
+ ports:
+ - "4566:4566"
+ - "6400-6419:6400-6419" # MemoryDB proxy ports
+ volumes:
+ - /var/run/docker.sock:/var/run/docker.sock
+ environment:
+ FLOCI_SERVICES_DOCKER_NETWORK: my-project_default
+```
+
+## Examples
+
+```bash
+export AWS_ENDPOINT_URL=http://localhost:4566
+
+# Create a cluster (starts a Valkey container)
+aws memorydb create-cluster \
+ --cluster-name my-memdb \
+ --node-type db.t4g.small \
+ --acl-name open-access \
+ --endpoint-url $AWS_ENDPOINT_URL
+
+# Get the connection address and port
+aws memorydb describe-clusters \
+ --cluster-name my-memdb \
+ --query 'Clusters[0].ClusterEndpoint' \
+ --endpoint-url $AWS_ENDPOINT_URL
+
+# Connect with redis-cli (use the Port from ClusterEndpoint)
+redis-cli -h localhost -p 6400 ping
+
+# Delete the cluster
+aws memorydb delete-cluster \
+ --cluster-name my-memdb \
+ --endpoint-url $AWS_ENDPOINT_URL
+```
diff --git a/mkdocs.yml b/mkdocs.yml
index d98baf93e5..bc2a6091cc 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -91,6 +91,7 @@ nav:
- IAM: services/iam.md
- STS: services/sts.md
- ElastiCache: services/elasticache.md
+ - MemoryDB: services/memorydb.md
- RDS: services/rds.md
- RDS Data API: services/rds-data.md
- MSK (Kafka): services/msk.md
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index f356b9fae5..9b81c67e2a 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -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();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
index b2e001e26b..1f7e4e6e43 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
@@ -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);
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index 48bc0440ad..ba7e1ab6b5 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -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,
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
index f34b7b09ff..d93d532349 100644
--- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
@@ -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();
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbHandler.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbHandler.java
new file mode 100644
index 0000000000..2dc859395e
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbHandler.java
@@ -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);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java
new file mode 100644
index 0000000000..f3b887e3bd
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java
@@ -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);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerHandle.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerHandle.java
new file mode 100644
index 0000000000..6c35752c51
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerHandle.java
@@ -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; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManager.java
new file mode 100644
index 0000000000..6b9891996a
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManager.java
@@ -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);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/model/AuthMode.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/AuthMode.java
new file mode 100644
index 0000000000..adef1d68b6
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/AuthMode.java
@@ -0,0 +1,5 @@
+package io.github.hectorvent.floci.services.memorydb.model;
+
+public enum AuthMode {
+ IAM, PASSWORD, NO_AUTH
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/model/Cluster.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/Cluster.java
new file mode 100644
index 0000000000..e2cfcab725
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/Cluster.java
@@ -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; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/model/ClusterStatus.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/ClusterStatus.java
new file mode 100644
index 0000000000..0c5f1e0d49
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/ClusterStatus.java
@@ -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;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/model/Endpoint.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/Endpoint.java
new file mode 100644
index 0000000000..8fd8ffc9c7
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/Endpoint.java
@@ -0,0 +1,3 @@
+package io.github.hectorvent.floci.services.memorydb.model;
+
+public record Endpoint(String address, int port) {}
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/proxy/MemoryDbAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/proxy/MemoryDbAuthProxy.java
new file mode 100644
index 0000000000..5b20337ac2
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/proxy/MemoryDbAuthProxy.java
@@ -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);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/proxy/MemoryDbProxyManager.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/proxy/MemoryDbProxyManager.java
new file mode 100644
index 0000000000..d4522ca821
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/proxy/MemoryDbProxyManager.java
@@ -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");
+ }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 89c578c6c2..832a1b100c 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -193,6 +193,12 @@ floci:
proxy-max-port: 6399
default-image: "valkey/valkey:8"
default-memcached-image: "memcached:1.6"
+ memorydb:
+ enabled: true
+ mock: false
+ proxy-base-port: 6400
+ proxy-max-port: 6419
+ default-image: "valkey/valkey:8"
rds:
enabled: true
proxy-base-port: 7001
diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java
index 91251e303a..07e6a2287f 100644
--- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java
+++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java
@@ -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);
diff --git a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbHandlerTest.java
new file mode 100644
index 0000000000..7028019bd0
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbHandlerTest.java
@@ -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());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbIntegrationTest.java
new file mode 100644
index 0000000000..485d499500
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbIntegrationTest.java
@@ -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();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java
new file mode 100644
index 0000000000..611d4cf072
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java
@@ -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);
+ }
+}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index c9028100d2..6406980ed8 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -98,6 +98,12 @@ floci:
proxy-max-port: 6399
default-image: "valkey/valkey:8"
default-memcached-image: "memcached:1.6"
+ memorydb:
+ enabled: true
+ mock: false
+ proxy-base-port: 6400
+ proxy-max-port: 6419
+ default-image: "valkey/valkey:8"
rds:
enabled: true
proxy-base-port: 7001