Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
ElastiCache: serverless caches with TLS-only Valkey/Redis containers (#1919)
Jeff Heller897685c859a7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 54ce11c6..e0cc4d34 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **RDS — `MINISTACK_RDS_PUBLIC_ENDPOINT=1` works with a Compose `hostname:`** — the #1884 fix told a containerised MiniStack from a host-run one by its `HOSTNAME` self-lookup, which a Compose `hostname:` defeats, so instances again stayed `creating`. MiniStack now checks Docker's or Podman's marker file for that, and a containerised MiniStack detects its network as with the setting off (`DOCKER_NETWORK`, then the self-lookup).### Added+- **ElastiCache — serverless caches** — `CreateServerlessCache`, `DescribeServerlessCaches` (with `MaxResults` / `NextToken`), `ModifyServerlessCache` and `DeleteServerlessCache` for `valkey` (major 7, 8 or 9) and `redis` (major 7), with `ServerlessCacheNotFoundFault`, `ServerlessCacheAlreadyExistsFault`, `InvalidServerlessCacheStateFault`, `InvalidParameterCombination` ("No modifications were requested") and `UserGroupNotFound`, and `ListTagsForResource` / `AddTagsToResource` / `RemoveTagsFromResource` on the `serverlesscache` ARN. The cache name is lowercased, as AWS stores it. With Docker, each cache gets its own Valkey or Redis container that, like AWS's, has no plaintext listener: the cache is `creating` until the container answers a TLS `PING`, then `available` with `Endpoint` / `ReaderEndpoint` reachable from the host, and its certificate names that address and chains to a CA served at `GET /_ministack/elasticache/ca.pem` (the local stand-in for Amazon's public CA; clients add it to their trust store; it persists across a restart). `ModifyServerlessCache` accepts only the engine changes AWS does — a same-engine major upgrade, redis to valkey, or the one documented valkey 7 to redis 7 rollback — and rejects the rest with `InvalidParameterCombination` before touching state; an accepted change replaces the container on the same host port, without the data AWS would keep. `StorageEncryptionType` reports `sse-kms` or `sse-elasticache` to match whether `KmsKeyId` is set. The container is removed on delete, reset, and respawned on the same port after a restart with persistence. Differences from AWS: with `DOCKER_NETWORK` the endpoint is the container's address, which changes when the container is replaced; the reader endpoint is the primary's port rather than 6380, memcached serverless caches and serverless snapshots (`SnapshotArnsToRestore`, `FinalSnapshotName`) are refused with `InvalidParameterValue`, and without Docker the endpoint is the plaintext Redis sidecar like other ElastiCache resources. Terraform's `aws_elasticache_serverless_cache` (provider 6.66.0) applies, plans with no changes and destroys. Checked against the botocore model, AWS documentation and the provider's source; not validated against a real AWS account.- **IoT — registry events** — with a type enabled through `UpdateEventConfigurations`, the thing, thing type, thing type association, thing group, thing group hierarchy and thing group membership operations publish the AWS payload to `$aws/events/...`, where MQTT subscribers and topic rules receive it.- **CloudFormation — `AWS::Lambda::Version` updates `FunctionScalingConfig` in place** — a stack update re-ran the create, which published a new version for every change; a `FunctionScalingConfig` change now keeps the version, also when the update rolls back. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex 8e82aef5..f7c48a50 100644--- a/README.md+++ b/README.md@@ -605,7 +605,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i| **ECS** | CreateCluster, DeleteCluster, DescribeClusters, ListClusters, UpdateCluster, UpdateClusterSettings, PutClusterCapacityProviders, RegisterTaskDefinition, DeregisterTaskDefinition, DescribeTaskDefinition, ListTaskDefinitions, ListTaskDefinitionFamilies, DeleteTaskDefinitions, CreateService, DeleteService, DescribeServices, UpdateService, ListServices, ListServicesByNamespace, RunTask, StopTask, DescribeTasks, ListTasks, ExecuteCommand, UpdateTaskProtection, GetTaskProtection, CreateCapacityProvider, UpdateCapacityProvider, DeleteCapacityProvider, DescribeCapacityProviders, TagResource, UntagResource, ListTagsForResource, ListAccountSettings, PutAccountSetting, PutAccountSettingDefault, DeleteAccountSetting, PutAttributes, DeleteAttributes, ListAttributes, DescribeServiceDeployments, ListServiceDeployments, DescribeServiceRevisions, SubmitTaskStateChange, SubmitContainerStateChange, SubmitAttachmentStateChanges, DiscoverPollEndpoint | 47 actions; `RunTask` starts real Docker containers via Docker socket; full Terraform ECS coverage || **RDS** | CreateDBInstance, DeleteDBInstance, DescribeDBInstances, ModifyDBInstance, StartDBInstance, StopDBInstance, RebootDBInstance, CreateDBInstanceReadReplica, RestoreDBInstanceFromDBSnapshot, CreateDBCluster, DeleteDBCluster, DescribeDBClusters, ModifyDBCluster, StartDBCluster, StopDBCluster, FailoverDBCluster, SwitchoverGlobalCluster, FailoverGlobalCluster, CreateDBSnapshot, DeleteDBSnapshot, DescribeDBSnapshots, CreateDBClusterSnapshot, DescribeDBClusterSnapshots, DeleteDBClusterSnapshot, CreateDBSubnetGroup, DeleteDBSubnetGroup, DescribeDBSubnetGroups, ModifyDBSubnetGroup, CreateDBParameterGroup, DeleteDBParameterGroup, DescribeDBParameterGroups, DescribeDBParameters, ModifyDBParameterGroup, CreateDBClusterParameterGroup, DescribeDBClusterParameterGroups, DeleteDBClusterParameterGroup, DescribeDBClusterParameters, ModifyDBClusterParameterGroup, CreateOptionGroup, DeleteOptionGroup, DescribeOptionGroups, DescribeOptionGroupOptions, ListTagsForResource, AddTagsToResource, RemoveTagsFromResource, DescribeDBEngineVersions, DescribeOrderableDBInstanceOptions, CreateGlobalCluster, DescribeGlobalClusters, DeleteGlobalCluster, RemoveFromGlobalCluster, ModifyGlobalCluster, CreateDBProxy, DescribeDBProxies, ModifyDBProxy, DeleteDBProxy, CreateDBProxyEndpoint, DescribeDBProxyEndpoints, ModifyDBProxyEndpoint, DeleteDBProxyEndpoint, DescribeDBProxyTargetGroups, ModifyDBProxyTargetGroup, RegisterDBProxyTargets, DeregisterDBProxyTargets, DescribeDBProxyTargets | `CreateDBInstance` spins up real Postgres/MySQL Docker container, returns actual `host:port` endpoint; a cluster's endpoint is its stable AWS-shaped name, registered as a Docker network alias on the backing container (on user-defined networks; the default bridge keeps the address form), so a stored endpoint keeps resolving after the container is replaced; Aurora MySQL 8.0/8.4 compatibility objects (`AWSAuthenticationPlugin`, RDS/Aurora stored procedures, predefined S3 roles) install automatically for supported MySQL images so Aurora provisioning workflows run. IAM database authentication on MySQL and Aurora MySQL 8.0/8.4 (not MariaDB): a user created `IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS'` logs in with an SDK-generated auth token over `mysql_clear_password` when the instance or cluster has `IAMDatabaseAuthenticationEnabled`; with `AUTH=true` the token and the `rds-db:connect` policy are verified too. Planned Aurora MySQL switchover (`SwitchoverGlobalCluster`, and `FailoverGlobalCluster` without data loss allowed) performs a coordinated no-data-loss writer exchange on provisioned two-member MySQL 8 global clusters; other configurations keep the metadata-only path. RDS Proxy is control plane only — proxies, proxy endpoints, the default target group and registered targets are stored and returned with the AWS shapes, but nothing listens on the proxy endpoint hostname; clients keep connecting to the instance or cluster endpoint || **Aurora DSQL** | CreateCluster, GetCluster, UpdateCluster, DeleteCluster, ListClusters, PutClusterPolicy, GetClusterPolicy, DeleteClusterPolicy, CreateStream, GetStream, ListStreams, DeleteStream, GetVpcEndpointServiceName, TagResource, UntagResource, ListTagsForResource | `CreateCluster` spins up a real `postgres:16-alpine` Docker container fronted by a validating PG wire-protocol proxy that **fails like real DSQL** — rejects unsupported SQL (`serial`, extensions, temp tables, ...), accepts `CREATE INDEX ASYNC` + `sys.jobs`; endpoint is `localhost:<port>`; any password accepted |-| **ElastiCache** | CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters, ModifyCacheCluster, RebootCacheCluster, CreateReplicationGroup, DeleteReplicationGroup, DescribeReplicationGroups, ModifyReplicationGroup, IncreaseReplicaCount, DecreaseReplicaCount, CreateCacheSubnetGroup, DescribeCacheSubnetGroups, ModifyCacheSubnetGroup, DeleteCacheSubnetGroup, CreateCacheParameterGroup, DescribeCacheParameterGroups, ModifyCacheParameterGroup, ResetCacheParameterGroup, DeleteCacheParameterGroup, DescribeCacheParameters, DescribeCacheEngineVersions, CreateUser, DescribeUsers, DeleteUser, ModifyUser, CreateUserGroup, DescribeUserGroups, DeleteUserGroup, ModifyUserGroup, ListTagsForResource, AddTagsToResource, RemoveTagsFromResource, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, DescribeEvents | `CreateCacheCluster` spins up a real Redis, Valkey, or Memcached Docker container (`Engine=redis`/`valkey`/`memcached`) |+| **ElastiCache** | CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters, ModifyCacheCluster, RebootCacheCluster, CreateReplicationGroup, DeleteReplicationGroup, DescribeReplicationGroups, ModifyReplicationGroup, IncreaseReplicaCount, DecreaseReplicaCount, CreateCacheSubnetGroup, DescribeCacheSubnetGroups, ModifyCacheSubnetGroup, DeleteCacheSubnetGroup, CreateCacheParameterGroup, DescribeCacheParameterGroups, ModifyCacheParameterGroup, ResetCacheParameterGroup, DeleteCacheParameterGroup, DescribeCacheParameters, DescribeCacheEngineVersions, CreateUser, DescribeUsers, DeleteUser, ModifyUser, CreateUserGroup, DescribeUserGroups, DeleteUserGroup, ModifyUserGroup, ListTagsForResource, AddTagsToResource, RemoveTagsFromResource, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, CreateServerlessCache, DescribeServerlessCaches, ModifyServerlessCache, DeleteServerlessCache, DescribeEvents | `CreateCacheCluster` spins up a real Redis, Valkey, or Memcached Docker container (`Engine=redis`/`valkey`/`memcached`); a serverless cache gets a TLS-only Valkey/Redis container whose certificate chains to the CA at `GET /_ministack/elasticache/ca.pem` || **Glue** | CreateDatabase, DeleteDatabase, GetDatabase, GetDatabases, UpdateDatabase, CreateTable, DeleteTable, GetTable, GetTables, UpdateTable, BatchDeleteTable, CreatePartition, DeletePartition, GetPartition, GetPartitions, BatchCreatePartition, BatchGetPartition, CreatePartitionIndex, GetPartitionIndexes, GetColumnStatisticsForTable, UpdateColumnStatisticsForTable, DeleteColumnStatisticsForTable, GetColumnStatisticsForPartition, UpdateColumnStatisticsForPartition, DeleteColumnStatisticsForPartition, CreateConnection, DeleteConnection, GetConnection, GetConnections, CreateCrawler, DeleteCrawler, GetCrawler, GetCrawlers, UpdateCrawler, StartCrawler, StopCrawler, GetCrawlerMetrics, CreateJob, DeleteJob, GetJob, GetJobs, UpdateJob, StartJobRun, GetJobRun, GetJobRuns, BatchStopJobRun, CreateTrigger, GetTrigger, DeleteTrigger, UpdateTrigger, StartTrigger, StopTrigger, ListTriggers, BatchGetTriggers, GetTriggers, CreateWorkflow, GetWorkflow, DeleteWorkflow, UpdateWorkflow, StartWorkflowRun, CreateUserDefinedFunction, UpdateUserDefinedFunction, DeleteUserDefinedFunction, GetUserDefinedFunction, GetUserDefinedFunctions, CreateSecurityConfiguration, DeleteSecurityConfiguration, GetSecurityConfiguration, GetSecurityConfigurations, CreateClassifier, GetClassifier, GetClassifiers, DeleteClassifier, TagResource, UntagResource, GetTags | Python shell jobs actually execute via subprocess; Spark jobs run on the official `amazon/aws-glue-libs` PySpark image (`GlueVersion: 4.0` / `3.0`) on MiniStack's Docker network; Glue-backed Iceberg REST catalog at `/iceberg` (signed with the `glue` credential scope, prefix `catalogs/{catalog}`) — read path for tables whose `metadata_location` parameter points at a metadata.json on MiniStack S3, e.g. DuckDB `ATTACH ... (TYPE iceberg, ENDPOINT 'localhost:4566/iceberg', AUTHORIZATION_TYPE 'sigv4')` with `USE_SSL=1` || **S3 Tables** | CreateTableBucket, ListTableBuckets, GetTableBucket, DeleteTableBucket, CreateNamespace, ListNamespaces, GetNamespace, DeleteNamespace, CreateTable, ListTables, GetTable, DeleteTable, GetTableMetadataLocation, UpdateTableMetadataLocation | Iceberg-format tables; embedded Iceberg REST catalog at `/iceberg` so Spark jobs (`spark.sql.catalog.*.type=rest`) can create / load / commit without an external catalog; data files in S3, metadata in memory || **Athena** | StartQueryExecution, GetQueryExecution, GetQueryResults, StopQueryExecution, ListQueryExecutions, BatchGetQueryExecution, CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, UpdateWorkGroup, CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries, BatchGetNamedQuery, CreateDataCatalog, GetDataCatalog, ListDataCatalogs, DeleteDataCatalog, UpdateDataCatalog, CreatePreparedStatement, GetPreparedStatement, DeletePreparedStatement, ListPreparedStatements, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; result pagination; column type metadata |@@ -728,6 +728,19 @@ A Redis sidecar is also always available at `localhost:6379` when using Docker C`Engine="valkey"` works the same way — a real `valkey/valkey` container is spawned (versions 7.2, 8.0, 8.1), the default parameter group becomes `default.valkey8`, and the advertised endpoint speaks the same protocol (`redis.Redis(...)` connects unchanged).+Serverless caches are TLS-only, as on AWS. Trust MiniStack's ElastiCache CA and connect with TLS:++```python+import time, urllib.request+ca = urllib.request.urlopen("http://localhost:4566/_ministack/elasticache/ca.pem").read().decode()+ec.create_serverless_cache(ServerlessCacheName="my-cache", Engine="valkey")+while (cache := ec.describe_serverless_caches(ServerlessCacheName="my-cache")["ServerlessCaches"][0])["Status"] == "creating":+ time.sleep(1)+ep = cache["Endpoint"]+r = redis.Redis(host=ep["Address"], port=ep["Port"], ssl=True, ssl_ca_data=ca)+r.ping()+```+---## Athena with Real SQLdiff --git a/ministack/app.py b/ministack/app.pyindex b7beeb97..fff334fc 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1223,9 +1223,31 @@ async def _handle_pre_body_request(method: str, path: str, headers: dict, query_if response is not None:return response+ response = _handle_elasticache_ca_request(method, path)+ if response is not None:+ return response+return await _handle_admin_reset(path, method, query_params)+def _handle_elasticache_ca_request(method: str, path: str):+ """`GET /_ministack/elasticache/ca.pem` returns the CA that signs serverless+ cache certificates; a client trusts it to connect with TLS."""+ if path != "/_ministack/elasticache/ca.pem" or method != "GET":+ return None+ try:+ from ministack.services import elasticache++ cert_pem = elasticache.serverless_ca_cert_pem()+ except Exception as e:+ return (+ 503,+ {"Content-Type": "application/json"},+ json.dumps({"message": str(e)}).encode(),+ )+ return (200, {"Content-Type": "application/x-pem-file"}, cert_pem.encode())++def _handle_rds_ca_request(method: str, path: str):"""`GET /_ministack/rds/ca.pem` returns the CA that signs DB servercertificates, the local stand-in for AWS's certificate bundle."""diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.pyindex 81a2e1ee..8197e5a3 100644--- a/ministack/services/elasticache.py+++ b/ministack/services/elasticache.py@@ -16,18 +16,27 @@ Supports: CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters,DescribeCacheEngineVersions,ListTagsForResource, AddTagsToResource, RemoveTagsFromResource,CreateSnapshot, DeleteSnapshot, DescribeSnapshots,+ CreateServerlessCache, DescribeServerlessCaches, ModifyServerlessCache,+ DeleteServerlessCache,DescribeEvents.When Docker is available, CreateCacheCluster spins up a real Redis/Valkey/Memcachedcontainer. Otherwise returns localhost:6379 (assumes Redis sidecar in docker-compose).+A serverless cache gets its own Valkey/Redis container that, like AWS's, only+speaks TLS; its certificate chains to the CA served at+``GET /_ministack/elasticache/ca.pem``."""import contextvarsimport copy+import io+import ipaddressimport loggingimport os+import tarfileimport timefrom urllib.parse import parse_qs+from xml.sax.saxutils import escape as xml_escapefrom ministack.core import container_reaperfrom ministack.core.arn import ArnParseError, parse_arn@@ -90,6 +99,7 @@ _tags = AccountScopedDict() # arn -> [{"Key": ..., "Value": ...}, ...]_snapshots = AccountRegionScopedDict()_users = AccountRegionScopedDict()_user_groups = AccountRegionScopedDict()+_serverless_caches = AccountRegionScopedDict()# Per-account+region event log under key "entries" so the list manipulation# stays simple and DescribeEvents never leaks cross-tenant or cross-region rows._events = AccountRegionScopedDict()@@ -127,6 +137,10 @@ def get_state():"user_groups": copy.deepcopy(_user_groups),"events": copy.deepcopy(_events),"port_counter": _port_counter[0],+ "serverless_ca": (+ {"ca_cert_pem": _serverless_ca[0], "ca_key_pem": _serverless_ca[1]}+ if _serverless_ca else {}+ ),}clusters = AccountRegionScopedDict()for (account_id, region, name), cl in _clusters.all_items():@@ -134,6 +148,12 @@ def get_state():c.pop("_docker_container_id", None)clusters.set_scoped(account_id, region, name, c)state["clusters"] = clusters+ serverless = AccountRegionScopedDict()+ for (account_id, region, name), cache in _serverless_caches.all_items():+ c = copy.deepcopy(cache)+ c.pop("_docker_container_id", None)+ serverless.set_scoped(account_id, region, name, c)+ state["serverless_caches"] = serverlessreturn state@@ -147,6 +167,7 @@ def get_state():# container is healthy by the time the SDK reaches the endpoint._pending_cluster_respawn: set = set()_pending_rg_respawn: set = set()+_pending_serverless_respawn: set = set()# Serialize lazy respawn so two concurrent first-requests after restart# don't both spawn a container for the same cluster.import threading as _threading@@ -209,11 +230,21 @@ def _restore_clusters(incoming):_pending_cluster_respawn.add((account_id, region, name))+def _restore_serverless_caches(incoming):+ restored = _as_region_scoped(incoming)+ for (account_id, region, name), cache in restored.all_items():+ record = copy.deepcopy(cache)+ record["_docker_container_id"] = None+ _serverless_caches.set_scoped(account_id, region, name, record)+ _pending_serverless_respawn.add((account_id, region, name))++def load_persisted_state(data):return _restore_state(data)def _restore_state(data):+ global _serverless_caif not data:return_restore_replication_groups(data.get("replication_groups", {}))@@ -227,7 +258,12 @@ def _restore_state(data):_events.update(data.get("events", {}))if "port_counter" in data:_port_counter[0] = data["port_counter"]+ ca_data = data.get("serverless_ca")+ if ca_data and ca_data.get("ca_cert_pem") and ca_data.get("ca_key_pem"):+ with _serverless_ca_lock:+ _serverless_ca = (ca_data["ca_cert_pem"], ca_data["ca_key_pem"])_restore_clusters(data.get("clusters", {}))+ _restore_serverless_caches(data.get("serverless_caches", {}))default_state()@@ -239,11 +275,11 @@ def _ensure_live_containers():but the endpoint won't be reachable (matches the old behavior, just nolonger silent)."""# Cheap fast path — no lock needed when nothing's pending.- if not (_pending_cluster_respawn or _pending_rg_respawn):+ if not (_pending_cluster_respawn or _pending_rg_respawn or _pending_serverless_respawn):return# Serialize concurrent first-requests so we don't double-spawn.with _respawn_lock:- if not (_pending_cluster_respawn or _pending_rg_respawn):+ if not (_pending_cluster_respawn or _pending_rg_respawn or _pending_serverless_respawn):return_ensure_live_containers_locked()@@ -308,6 +344,19 @@ def _ensure_live_containers_locked():log.warning("elasticache: failed to respawn containers for replication group %s ""on restart; endpoint will be unreachable", rg_id, exc_info=True)+ for pending in list(_pending_serverless_respawn):+ account_id, region, name = pending+ _pending_serverless_respawn.discard(pending)+ cache = _serverless_caches.get_scoped(account_id, region, name)+ if cache is None or _get_docker() is None:+ continue+ try:+ _start_serverless_container(cache, account_id, region, wait=False)+ log.info("elasticache: respawned container for serverless cache %s after restart", name)+ except Exception:+ log.warning(+ "elasticache: failed to respawn container for serverless cache %s on restart; "+ "endpoint will be unreachable", name, exc_info=True)# ── Seed default ElastiCache parameter groups ─────────────────@@ -413,6 +462,7 @@ _DOCKER_BACKED_ACTIONS = {"RebootCacheCluster", "CreateReplicationGroup", "DeleteReplicationGroup","ModifyReplicationGroup", "IncreaseReplicaCount", "DecreaseReplicaCount","DescribeCacheClusters", "DescribeReplicationGroups",+ "CreateServerlessCache", "DeleteServerlessCache", "ModifyServerlessCache",}@@ -567,12 +617,16 @@ def _spawn_redis_cluster_node(name, engine, engine_version, labels):return None, None, None-def _wait_redis_ready(container, timeout=15):- """Poll PING via docker exec until the node responds, up to ``timeout`` s."""+def _wait_redis_ready(container, timeout=15, cli_args=()):+ """Poll PING via docker exec until the node responds, up to ``timeout`` s.++ ``cli_args`` go before the command, e.g. the ``--tls`` flags a TLS-only+ server needs.+ """deadline = time.time() + timeoutwhile time.time() < deadline:try:- result = container.exec_run(["redis-cli", "-p", "6379", "PING"])+ result = container.exec_run(["redis-cli", *cli_args, "-p", "6379", "PING"])if result.exit_code == 0 and b"PONG" in result.output:return Trueexcept Exception:@@ -822,6 +876,12 @@ def _resolve_taggable_elasticache_arn(arn):"snapshot": (_snapshots, "SnapshotNotFoundFault", f"Snapshot {name} not found", "ARN"),"user": (_users, "UserNotFoundFault", f"User {name} not found", "ARN"),"usergroup": (_user_groups, "UserGroupNotFoundFault", f"User group {name} not found", "ARN"),+ "serverlesscache": (+ _serverless_caches,+ "ServerlessCacheNotFoundFault",+ f"Serverless cache {name} not found.",+ "ARN",+ ),}entry = resources.get(resource_type)if not entry:@@ -896,6 +956,10 @@ async def handle_request(method, path, headers, body, query_params):"CreateSnapshot": _create_snapshot,"DeleteSnapshot": _delete_snapshot,"DescribeSnapshots": _describe_snapshots,+ "CreateServerlessCache": _create_serverless_cache,+ "DescribeServerlessCaches": _describe_serverless_caches,+ "ModifyServerlessCache": _modify_serverless_cache,+ "DeleteServerlessCache": _delete_serverless_cache,"DescribeEvents": _describe_events,}@@ -2041,6 +2105,469 @@ def _describe_snapshots(p):f"<DescribeSnapshotsResult><Snapshots>{members}</Snapshots></DescribeSnapshotsResult>")+# ---- Serverless Caches ----++# AWS pins only the major version of a serverless cache and reports the minor it+# runs as FullEngineVersion; the container runs that minor's image.+_SERVERLESS_ENGINE_VERSIONS = {+ "valkey": {"7": "7.2", "8": "8.1", "9": "9.0"},+ "redis": {"7": "7.1"},+}+_SERVERLESS_DEFAULT_MAJOR = {"valkey": "8", "redis": "7"}+_SERVERLESS_TLS_DIR = "/ministack-elasticache-tls"+_SERVERLESS_TLS_CLI_ARGS = ("--tls", "--cacert", f"{_SERVERLESS_TLS_DIR}/ca.crt", "-h", "127.0.0.1")+# The certificate has to name the container's address, which is only known once+# it runs, so the server waits for the material; `ready` is the archive's last+# member. The image's entrypoint then drops to the uid that owns /data.+_SERVERLESS_TLS_WRAPPER = (+ f"d={_SERVERLESS_TLS_DIR}; "+ 'while [ ! -e "$d/ready" ]; do sleep 0.1; done; '+ 'chown -R "$(stat -c %u:%g /data)" "$d"; '+ 'exec docker-entrypoint.sh "$@"'+)+_serverless_ca_lock = _threading.Lock()+_serverless_ca = None+++def serverless_ca_cert_pem() -> str:+ """The CA that signs serverless cache certificates, minted on first use."""+ return _ensure_serverless_ca()[0]+++def _ensure_serverless_ca():+ global _serverless_ca+ if _serverless_ca is None:+ with _serverless_ca_lock:+ if _serverless_ca is None:+ from ministack.core.x509_utils import generate_ca+ _serverless_ca = generate_ca(org_name="MiniStack",+ common_name="MiniStack ElastiCache Root CA")+ return _serverless_ca+++def _arn_serverless_cache(name):+ return f"arn:aws:elasticache:{get_region()}:{get_account_id()}:serverlesscache:{name}"+++def _serverless_container_name(account_id, region, name):+ return f"ministack-elasticache-serverless-{account_id}-{region}-{name}"+++def _is_ip(value):+ try:+ ipaddress.ip_address(value)+ return True+ except ValueError:+ return False+++def _serverless_tls_archive(ca_pem, cert_pem, key_pem):+ root = _SERVERLESS_TLS_DIR.lstrip("/")+ archive = io.BytesIO()+ with tarfile.open(fileobj=archive, mode="w") as bundle:+ entry = tarfile.TarInfo(root)+ entry.type = tarfile.DIRTYPE+ entry.mode = 0o755+ bundle.addfile(entry)+ for filename, content, mode in (("ca.crt", ca_pem, 0o644), ("server.crt", cert_pem, 0o644),+ ("server.key", key_pem, 0o600), ("ready", "", 0o644)):+ data = content.encode()+ entry = tarfile.TarInfo(f"{root}/{filename}")+ entry.mode = mode+ entry.size = len(data)+ bundle.addfile(entry, io.BytesIO(data))+ return archive.getvalue()+++def _spawn_serverless_container(name, engine, full_version, host_port, labels, wait=True):+ """Start a TLS-only Valkey/Redis container and return ``(address, port, id)``.++ Raises on any failure, after removing what it started: a serverless cache+ has no plaintext listener, so there is no degraded endpoint to fall back to.+ """+ from ministack.core.x509_utils import sign_leaf_certificate++ docker_client = _get_docker()+ if docker_client is None:+ raise RuntimeError("Docker is not available")+ image, container_port = _engine_image_and_port(engine, full_version)+ run_kwargs = dict(+ image=image, detach=True, name=name, labels=labels,+ ports={f"{container_port}/tcp": host_port},+ entrypoint=["sh", "-c", _SERVERLESS_TLS_WRAPPER, "ministack-elasticache-tls"],+ command=[+ "--port", "0", "--tls-port", str(container_port),+ "--tls-cert-file", f"{_SERVERLESS_TLS_DIR}/server.crt",+ "--tls-key-file", f"{_SERVERLESS_TLS_DIR}/server.key",+ "--tls-ca-cert-file", f"{_SERVERLESS_TLS_DIR}/ca.crt",+ "--tls-auth-clients", "no",+ "--protected-mode", "no",+ ],+ )+ if DOCKER_NETWORK:+ run_kwargs["network"] = DOCKER_NETWORK+ container = docker_client.containers.run(**run_kwargs)+ try:+ address, port, container_ip = _MINISTACK_HOST, host_port, ""+ if DOCKER_NETWORK:+ container.reload()+ networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})+ container_ip = networks.get(DOCKER_NETWORK, {}).get("IPAddress", "")+ if container_ip:+ address, port = container_ip, container_port+ candidates = ("localhost", _MINISTACK_HOST, name, "127.0.0.1", "::1", container_ip)+ dns_names = [n for n in dict.fromkeys(candidates) if n and not _is_ip(n)]+ ips = [n for n in dict.fromkeys(candidates) if n and _is_ip(n)]+ ca_pem, ca_key = _ensure_serverless_ca()+ cert_pem, key_pem, _public = sign_leaf_certificate(+ ca_pem, ca_key, common_name=dns_names[0], san_dns=dns_names, san_ips=ips)+ if not container.put_archive("/", _serverless_tls_archive(ca_pem, cert_pem, key_pem)):+ raise RuntimeError("Docker rejected the TLS material")+ if wait and not _wait_redis_ready(container, timeout=30, cli_args=_SERVERLESS_TLS_CLI_ARGS):+ raise RuntimeError(f"{engine} in {name} never answered a TLS PING")+ except Exception:+ _teardown_containers(docker_client, [container.id])+ raise+ logger.info("ElastiCache: started serverless %s container %s at %s:%s (TLS)",+ engine, name, address, port)+ return address, port, container.id+++def _start_serverless_container(record, account_id, region, wait=True):+ """Start ``record``'s container and publish its endpoint, unless the cache+ was deleted meanwhile — then the container is removed instead."""+ name = record["ServerlessCacheName"]+ address, port, cid = _spawn_serverless_container(+ name=_serverless_container_name(account_id, region, name),+ engine=record["Engine"],+ full_version=record["FullEngineVersion"],+ host_port=record["_host_port"],+ labels={+ **container_reaper.own_labels("elasticache"),+ "serverless_cache": name,+ "account_id": account_id,+ "region": region,+ },+ wait=wait,+ )+ with resource_lock("elasticache-serverless", f"{account_id}/{region}/{name}"):+ orphaned = _serverless_caches.get_scoped(account_id, region, name) is not record+ if not orphaned:+ record["_docker_container_id"] = cid+ record["Endpoint"] = {"Address": address, "Port": port}+ record["ReaderEndpoint"] = {"Address": address, "Port": port}+ record["Status"] = "available"+ if orphaned:+ _teardown_containers(_get_docker(), [cid])+++def _provision_serverless_cache(record, account_id, region, replaced_container_id=None):+ if replaced_container_id:+ _teardown_containers(_get_docker(), [replaced_container_id])+ try:+ _start_serverless_container(record, account_id, region)+ except Exception:+ logger.warning("ElastiCache: serverless cache %s failed to start",+ record["ServerlessCacheName"], exc_info=True)+ with resource_lock("elasticache-serverless",+ f"{account_id}/{region}/{record['ServerlessCacheName']}"):+ if _serverless_caches.get_scoped(account_id, region, record["ServerlessCacheName"]) is record:+ record["Status"] = "create-failed"+++def _provision_in_background(record, replaced_container_id=None):+ record["Status"] = "creating" if replaced_container_id is None else "modifying"+ record["_docker_container_id"] = None+ spawn_background(_provision_serverless_cache, record, get_account_id(), get_region(),+ replaced_container_id,+ thread_name=f"ministack-elasticache-serverless-{record['ServerlessCacheName']}")+++def _optional_int(p, key):+ value = _p(p, key)+ return int(value) if value != "" else None+++def _extract_cache_usage_limits(p):+ limits = {}+ data_storage = {k: _optional_int(p, f"CacheUsageLimits.DataStorage.{k}") for k in ("Maximum", "Minimum")}+ data_storage = {k: v for k, v in data_storage.items() if v is not None}+ unit = _p(p, "CacheUsageLimits.DataStorage.Unit")+ if data_storage or unit:+ limits["DataStorage"] = {**data_storage, **({"Unit": unit} if unit else {})}+ ecpu = {k: _optional_int(p, f"CacheUsageLimits.ECPUPerSecond.{k}") for k in ("Maximum", "Minimum")}+ ecpu = {k: v for k, v in ecpu.items() if v is not None}+ if ecpu:+ limits["ECPUPerSecond"] = ecpu+ return limits+++def _resolve_serverless_engine(engine, major):+ """Return ``(engine, major, full_version)`` or an error response."""+ engine = (engine or "").lower()+ versions = _SERVERLESS_ENGINE_VERSIONS.get(engine)+ if versions is None:+ return None, _error("InvalidParameterValue",+ f"Engine {engine or '(empty)'} is not supported for serverless caches "+ f"in MiniStack; use valkey or redis.", 400)+ major = major or _SERVERLESS_DEFAULT_MAJOR[engine]+ if major not in versions:+ return None, _error("InvalidParameterValue",+ f"Invalid major engine version {major} for engine {engine}.", 400)+ return (engine, major, versions[major]), None+++def _validate_serverless_engine_change(cur_engine, cur_major, new_engine, new_major):+ """AWS allows only a same-engine major upgrade, a redis-to-valkey move (any+ supported valkey major), or valkey 7 -> redis 7 — the one documented+ rollback ("ElastiCache only supports rolling back from Valkey 7.2 to+ Redis OSS 7.1", AWS ElastiCache version-management guide). Anything else,+ including a same-engine downgrade or valkey 8/9 -> redis, is rejected."""+ if new_engine == cur_engine:+ if int(new_major) > int(cur_major):+ return None+ elif cur_engine == "redis" and new_engine == "valkey":+ return None+ elif cur_engine == "valkey" and new_engine == "redis" and cur_major == "7" and new_major == "7":+ return None+ return _error("InvalidParameterCombination",+ f"Cannot change a serverless cache from {cur_engine} {cur_major} to "+ f"{new_engine} {new_major}.", 400)+++def _create_serverless_cache(p):+ name = _p(p, "ServerlessCacheName")+ if not name:+ return _error("InvalidParameterValue", "ServerlessCacheName is required.", 400)+ name = name.lower()+ resolved, err = _resolve_serverless_engine(_p(p, "Engine"), _p(p, "MajorEngineVersion"))+ if err:+ return err+ engine, major, full_version = resolved+ if name in _serverless_caches:+ return _error("ServerlessCacheAlreadyExistsFault",+ f"Serverless cache {name} already exists.", 400)+ user_group_id = _p(p, "UserGroupId")+ if user_group_id and user_group_id not in _user_groups:+ return _error("UserGroupNotFound", "The user group was not found or does not exist", 404)+ if _extract_configs(p, "SnapshotArnsToRestore", ("SnapshotArn", "member")):+ return _error("InvalidParameterValue",+ "MiniStack has no serverless cache snapshots to restore from.", 400)+ try:+ limits = _extract_cache_usage_limits(p)+ retention = _optional_int(p, "SnapshotRetentionLimit")+ except ValueError:+ return _error("InvalidParameterValue", "Invalid numeric parameter value.", 400)++ arn = _arn_serverless_cache(name)+ host_port = _port_counter[0]+ _port_counter[0] += 1+ record = {+ "ServerlessCacheName": name,+ "Description": _p(p, "Description"),+ "CreateTime": time.time(),+ "Status": "creating",+ "Engine": engine,+ "MajorEngineVersion": major,+ "FullEngineVersion": full_version,+ "CacheUsageLimits": limits,+ "KmsKeyId": _p(p, "KmsKeyId"),+ "SecurityGroupIds": _extract_configs(p, "SecurityGroupIds", ("SecurityGroupId", "member")),+ "SubnetIds": _extract_configs(p, "SubnetIds", ("SubnetId", "member")),+ "ARN": arn,+ "UserGroupId": user_group_id,+ "SnapshotRetentionLimit": retention or 0,+ "DailySnapshotTime": _p(p, "DailySnapshotTime"),+ "NetworkType": _p(p, "NetworkType") or "ipv4",+ "_host_port": host_port,+ "_docker_container_id": None,+ }+ _serverless_caches[name] = record+ _tags[arn] = _extract_tags(p)+ if _get_docker() is None:+ # Same fallback as every other ElastiCache resource: the shared sidecar,+ # which is plaintext — there is nothing to terminate TLS without Docker.+ logger.warning("ElastiCache: Docker unavailable; serverless cache %s points at the "+ "plaintext sidecar %s:%s", name, REDIS_DEFAULT_HOST, REDIS_DEFAULT_PORT)+ endpoint = {"Address": REDIS_DEFAULT_HOST, "Port": REDIS_DEFAULT_PORT}+ record["Endpoint"] = dict(endpoint)+ record["ReaderEndpoint"] = dict(endpoint)+ record["Status"] = "available"+ else:+ _provision_in_background(record)+ _record_event(name, "serverless-cache", "Serverless cache created")+ return _xml(200, "CreateServerlessCacheResponse",+ f"<CreateServerlessCacheResult><ServerlessCache>{_serverless_cache_xml(record)}"+ f"</ServerlessCache></CreateServerlessCacheResult>")+++def _describe_serverless_caches(p):+ name = _p(p, "ServerlessCacheName").lower()+ if name:+ cache = _serverless_caches.get(name)+ if not cache:+ return _error("ServerlessCacheNotFoundFault", f"Serverless cache {name} not found.", 404)+ caches = [cache]+ else:+ caches = list(_serverless_caches.values())+ try:+ max_results = int(_p(p, "MaxResults") or "50")+ start = int(_p(p, "NextToken") or "0")+ except ValueError:+ return _error("InvalidParameterValue", "Invalid MaxResults or NextToken.", 400)+ page = caches[start:start + max_results]+ token = ""+ if start + max_results < len(caches):+ token = f"<NextToken>{start + max_results}</NextToken>"+ members = "".join(f"<member>{_serverless_cache_xml(c)}</member>" for c in page)+ return _xml(200, "DescribeServerlessCachesResponse",+ f"<DescribeServerlessCachesResult>{token}<ServerlessCaches>{members}</ServerlessCaches>"+ f"</DescribeServerlessCachesResult>")+++def _modify_serverless_cache(p):+ name = _p(p, "ServerlessCacheName").lower()+ cache = _serverless_caches.get(name)+ if not cache:+ return _error("ServerlessCacheNotFoundFault", f"Serverless cache {name} not found.", 404)+ if cache["Status"] != "available":+ return _error("InvalidServerlessCacheStateFault",+ f"Serverless cache {name} is not in available state.", 400)+ remove_user_group = _p(p, "RemoveUserGroup").lower() == "true"+ user_group_id = _p(p, "UserGroupId")+ if remove_user_group and user_group_id:+ return _error("InvalidParameterCombination",+ "RemoveUserGroup and UserGroupId cannot be specified together.", 400)+ if user_group_id and user_group_id not in _user_groups:+ return _error("UserGroupNotFound", "The user group was not found or does not exist", 404)+ engine_change = None+ if _p(p, "Engine") or _p(p, "MajorEngineVersion"):+ engine = _p(p, "Engine") or cache["Engine"]+ major = _p(p, "MajorEngineVersion")+ if not major and engine == cache["Engine"]:+ major = cache["MajorEngineVersion"]+ resolved, err = _resolve_serverless_engine(engine, major)+ if err:+ return err+ if resolved[:2] != (cache["Engine"], cache["MajorEngineVersion"]):+ err = _validate_serverless_engine_change(+ cache["Engine"], cache["MajorEngineVersion"], resolved[0], resolved[1])+ if err:+ return err+ engine_change = resolved+ try:+ limits = _extract_cache_usage_limits(p)+ retention = _optional_int(p, "SnapshotRetentionLimit")+ except ValueError:+ return _error("InvalidParameterValue", "Invalid numeric parameter value.", 400)+ security_group_ids = _extract_configs(p, "SecurityGroupIds", ("SecurityGroupId", "member"))++ changes = {}+ if "Description" in p:+ changes["Description"] = _p(p, "Description")+ if limits:+ # All-zero limits remove them (AWS "Pre-Scaling" guide).+ values = [v for part in limits.values() for k, v in part.items() if k != "Unit"]+ changes["CacheUsageLimits"] = {} if values and not any(values) else limits+ if retention is not None:+ changes["SnapshotRetentionLimit"] = retention+ if _p(p, "DailySnapshotTime"):+ changes["DailySnapshotTime"] = _p(p, "DailySnapshotTime")+ if security_group_ids:+ changes["SecurityGroupIds"] = security_group_ids+ if user_group_id:+ changes["UserGroupId"] = user_group_id+ if remove_user_group:+ changes["UserGroupId"] = ""+ if not changes and engine_change is None:+ return _error("InvalidParameterCombination", "No modifications were requested", 400)++ cache.update(changes)+ if engine_change is not None:+ cache["Engine"], cache["MajorEngineVersion"], cache["FullEngineVersion"] = engine_change+ if cache.get("_docker_container_id") or _get_docker() is not None:+ # A different engine is a different image: replace the container on+ # the same host port so the endpoint a client holds stays valid.+ _provision_in_background(cache, replaced_container_id=cache.get("_docker_container_id") or "")+ _record_event(name, "serverless-cache", "Serverless cache modified")+ return _xml(200, "ModifyServerlessCacheResponse",+ f"<ModifyServerlessCacheResult><ServerlessCache>{_serverless_cache_xml(cache)}"+ f"</ServerlessCache></ModifyServerlessCacheResult>")+++def _delete_serverless_cache(p):+ name = _p(p, "ServerlessCacheName").lower()+ if _p(p, "FinalSnapshotName"):+ return _error("InvalidParameterValue",+ "MiniStack does not take serverless cache snapshots; omit FinalSnapshotName.", 400)+ account_id, region = get_account_id(), get_region()+ with resource_lock("elasticache-serverless", f"{account_id}/{region}/{name}"):+ cache = _serverless_caches.get(name)+ if not cache:+ return _error("ServerlessCacheNotFoundFault", f"Serverless cache {name} not found.", 404)+ del _serverless_caches[name]+ cache["Status"] = "deleting"+ docker_client = _get_docker()+ if docker_client:+ # By id and by name: a delete during provisioning has no id to go on yet.+ ids = [cache["_docker_container_id"]] if cache.get("_docker_container_id") else []+ try:+ ids.append(docker_client.containers.get(+ _serverless_container_name(account_id, region, name)).id)+ except Exception:+ pass+ _teardown_containers(docker_client, list(dict.fromkeys(ids)))+ _tags.pop(cache["ARN"], None)+ _record_event(name, "serverless-cache", "Serverless cache deleted")+ return _xml(200, "DeleteServerlessCacheResponse",+ f"<DeleteServerlessCacheResult><ServerlessCache>{_serverless_cache_xml(cache)}"+ f"</ServerlessCache></DeleteServerlessCacheResult>")+++def _serverless_cache_xml(c):+ def endpoint(tag):+ e = c.get(tag)+ if not e:+ return ""+ return f"<{tag}><Address>{xml_escape(e['Address'])}</Address><Port>{e['Port']}</Port></{tag}>"++ def optional(tag, value):+ return f"<{tag}>{xml_escape(str(value))}</{tag}>" if value not in (None, "") else ""++ limits = c.get("CacheUsageLimits") or {}+ limits_xml = ""+ if limits:+ parts = "".join(+ f"<{part}>" + "".join(optional(k, v) for k, v in limits[part].items()) + f"</{part}>"+ for part in ("DataStorage", "ECPUPerSecond") if part in limits)+ limits_xml = f"<CacheUsageLimits>{parts}</CacheUsageLimits>"+ created = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(c["CreateTime"]))+ security_groups = "".join(f"<SecurityGroupId>{xml_escape(g)}</SecurityGroupId>"+ for g in c.get("SecurityGroupIds") or [])+ subnets = "".join(f"<SubnetId>{xml_escape(s)}</SubnetId>" for s in c.get("SubnetIds") or [])+ return (+ f"<ServerlessCacheName>{xml_escape(c['ServerlessCacheName'])}</ServerlessCacheName>"+ f"{optional('Description', c.get('Description'))}"+ f"<CreateTime>{created}</CreateTime>"+ f"<Status>{c['Status']}</Status>"+ f"<Engine>{c['Engine']}</Engine>"+ f"<MajorEngineVersion>{c['MajorEngineVersion']}</MajorEngineVersion>"+ f"<FullEngineVersion>{c['FullEngineVersion']}</FullEngineVersion>"+ f"{limits_xml}"+ f"{optional('KmsKeyId', c.get('KmsKeyId'))}"+ f"<StorageEncryptionType>{'sse-kms' if c.get('KmsKeyId') else 'sse-elasticache'}</StorageEncryptionType>"+ f"<SecurityGroupIds>{security_groups}</SecurityGroupIds>"+ f"{endpoint('Endpoint')}"+ f"{endpoint('ReaderEndpoint')}"+ f"<ARN>{c['ARN']}</ARN>"+ f"{optional('UserGroupId', c.get('UserGroupId'))}"+ f"<SubnetIds>{subnets}</SubnetIds>"+ f"<SnapshotRetentionLimit>{c.get('SnapshotRetentionLimit', 0)}</SnapshotRetentionLimit>"+ f"{optional('DailySnapshotTime', c.get('DailySnapshotTime'))}"+ f"<NetworkType>{c.get('NetworkType', 'ipv4')}</NetworkType>"+ )++# ---- Events ----def _describe_events(p):@@ -2532,6 +3059,9 @@ def reset():c.remove(v=True)except Exception as e:logger.warning("reset: failed to stop/remove RG container %s: %s", cid, e)+ _teardown_containers(docker_client, [+ c["_docker_container_id"] for c in _serverless_caches.all_values()+ if c.get("_docker_container_id")])_clusters.clear()_replication_groups.clear()_subnet_groups.clear()@@ -2540,10 +3070,12 @@ def reset():_snapshots.clear()_users.clear()_user_groups.clear()+ _serverless_caches.clear()_events.clear()_tags.clear() # was missing from reset() — HIGH-severity gap from audit_pending_cluster_respawn.clear()_pending_rg_respawn.clear()+ _pending_serverless_respawn.clear()_port_counter[0] = BASE_PORTdefault_state()@@ -2559,6 +3091,9 @@ def _live_container_ids():for _key, rg in _replication_groups.all_items():for cid2 in rg.get("_docker_container_ids") or []:ids.add(cid2)+ for _key, cache in _serverless_caches.all_items():+ if cache.get("_docker_container_id"):+ ids.add(cache["_docker_container_id"])return idsdiff --git a/tests/test_elasticache.py b/tests/test_elasticache.pyindex 44e09f07..12133153 100644--- a/tests/test_elasticache.py+++ b/tests/test_elasticache.py@@ -1384,18 +1384,277 @@ def test_replication_group_tag_updates_propagate_to_member_clusters(ec):# ----------------------------------------------------------------------------# 12. Serverless cache operations — not implemented in MiniStack+# 12. Serverless caches# ----------------------------------------------------------------------------@requires_docker+def _wait_serverless(ec, name, timeout=180):+ deadline = time.time() + timeout+ while True:+ cache = ec.describe_serverless_caches(ServerlessCacheName=name)["ServerlessCaches"][0]+ if cache["Status"] not in ("creating", "modifying") or time.time() > deadline:+ return cache+ time.sleep(0.5)+++def _serverless_ca_file(tmp_path):+ import urllib.request+ with urllib.request.urlopen(f"{ENDPOINT}/_ministack/elasticache/ca.pem", timeout=10) as resp:+ pem = resp.read()+ assert pem.startswith(b"-----BEGIN CERTIFICATE-----")+ path = tmp_path / "elasticache-ca.pem"+ path.write_bytes(pem)+ return str(path)+++def _tls_command(endpoint, ca_file, command):+ import socket+ import ssl+ ctx = ssl.create_default_context(cafile=ca_file)+ with socket.create_connection((endpoint["Address"], endpoint["Port"]), timeout=10) as raw:+ with ctx.wrap_socket(raw, server_hostname=endpoint["Address"]) as conn:+ parts = command.split()+ conn.sendall(f"*{len(parts)}\r\n".encode()+ + b"".join(f"${len(p)}\r\n{p}\r\n".encode() for p in parts))+ return conn.recv(65536)+++def test_serverless_cache_create_describe_delete(ec):+ name = f"sls-{_uid()}"+ created = ec.create_serverless_cache(+ ServerlessCacheName=name,+ Engine="valkey",+ MajorEngineVersion="8",+ Description="cache & <counters>",+ SecurityGroupIds=["sg-0123"],+ SubnetIds=["subnet-a", "subnet-b"],+ CacheUsageLimits={"DataStorage": {"Maximum": 1, "Unit": "GB"},+ "ECPUPerSecond": {"Maximum": 1000}},+ Tags=[{"Key": "env", "Value": "dev"}],+ )["ServerlessCache"]+ try:+ assert created["Status"] in ("creating", "available")+ assert created["Engine"] == "valkey"+ assert created["MajorEngineVersion"] == "8"+ assert created["FullEngineVersion"] == "8.1"+ assert created["Description"] == "cache & <counters>"+ assert created["SecurityGroupIds"] == ["sg-0123"]+ assert created["SubnetIds"] == ["subnet-a", "subnet-b"]+ assert created["CacheUsageLimits"] == {"DataStorage": {"Maximum": 1, "Unit": "GB"},+ "ECPUPerSecond": {"Maximum": 1000}}+ assert created["SnapshotRetentionLimit"] == 0+ assert "KmsKeyId" not in created and "UserGroupId" not in created+ assert created["StorageEncryptionType"] == "sse-elasticache"+ arn = created["ARN"]+ assert arn.startswith("arn:aws:elasticache:us-east-1:") and arn.endswith(f":serverlesscache:{name}")++ described = ec.describe_serverless_caches(ServerlessCacheName=name)["ServerlessCaches"]+ assert [c["ARN"] for c in described] == [arn]+ assert {t["Key"]: t["Value"] for t in ec.list_tags_for_resource(ResourceName=arn)["TagList"]} == {"env": "dev"}+ ec.add_tags_to_resource(ResourceName=arn, Tags=[{"Key": "team", "Value": "core"}])+ ec.remove_tags_from_resource(ResourceName=arn, TagKeys=["env"])+ assert ec.list_tags_for_resource(ResourceName=arn)["TagList"] == [{"Key": "team", "Value": "core"}]++ with pytest.raises(ClientError) as exc:+ ec.create_serverless_cache(ServerlessCacheName=name, Engine="valkey")+ assert exc.value.response["Error"]["Code"] == "ServerlessCacheAlreadyExistsFault"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+ finally:+ deleted = ec.delete_serverless_cache(ServerlessCacheName=name)["ServerlessCache"]+ assert deleted["Status"] == "deleting"+ for call in (lambda: ec.describe_serverless_caches(ServerlessCacheName=name),+ lambda: ec.delete_serverless_cache(ServerlessCacheName=name),+ lambda: ec.list_tags_for_resource(ResourceName=arn)):+ with pytest.raises(ClientError) as exc:+ call()+ assert exc.value.response["Error"]["Code"] == "ServerlessCacheNotFoundFault"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404++[email protected]("engine,major", [("memcached", None), ("valkey", "6"), ("redis", "8")])+def test_serverless_cache_rejects_unsupported_engine_version(ec, engine, major):+ kwargs = {"MajorEngineVersion": major} if major else {}+ with pytest.raises(ClientError) as exc:+ ec.create_serverless_cache(ServerlessCacheName=f"sls-bad-{_uid()}", Engine=engine, **kwargs)+ assert exc.value.response["Error"]["Code"] == "InvalidParameterValue"+++def test_serverless_cache_storage_encryption_type_sse_kms(ec):+ name = f"sls-kms-{_uid()}"+ created = ec.create_serverless_cache(+ ServerlessCacheName=name, Engine="valkey",+ KmsKeyId="arn:aws:kms:us-east-1:000000000000:key/test-key",+ )["ServerlessCache"]+ try:+ assert created["KmsKeyId"] == "arn:aws:kms:us-east-1:000000000000:key/test-key"+ assert created["StorageEncryptionType"] == "sse-kms"+ finally:+ ec.delete_serverless_cache(ServerlessCacheName=name)+++def test_serverless_cache_valkey_major_9(ec):+ name = f"sls-v9-{_uid()}"+ created = ec.create_serverless_cache(+ ServerlessCacheName=name, Engine="valkey", MajorEngineVersion="9",+ )["ServerlessCache"]+ try:+ assert created["MajorEngineVersion"] == "9"+ assert created["FullEngineVersion"] == "9.0"+ finally:+ ec.delete_serverless_cache(ServerlessCacheName=name)+++def test_serverless_cache_name_is_lowercased(ec):+ mixed = f"MyCache-{_uid()}"+ lower = mixed.lower()+ created = ec.create_serverless_cache(ServerlessCacheName=mixed, Engine="valkey")["ServerlessCache"]+ try:+ assert created["ServerlessCacheName"] == lower+ assert created["ARN"].endswith(f":serverlesscache:{lower}")+ described = ec.describe_serverless_caches(ServerlessCacheName=mixed.upper())["ServerlessCaches"]+ assert [c["ServerlessCacheName"] for c in described] == [lower]+ finally:+ ec.delete_serverless_cache(ServerlessCacheName=mixed)+ with pytest.raises(ClientError) as exc:+ ec.describe_serverless_caches(ServerlessCacheName=lower)+ assert exc.value.response["Error"]["Code"] == "ServerlessCacheNotFoundFault"+++def test_serverless_cache_modify_rejects_invalid_engine_change(ec):+ name = f"sls-engchg-{_uid()}"+ ec.create_serverless_cache(ServerlessCacheName=name, Engine="valkey", MajorEngineVersion="8")+ try:+ cache = _wait_serverless(ec, name)+ assert (cache["Engine"], cache["MajorEngineVersion"]) == ("valkey", "8")++ with pytest.raises(ClientError) as exc:+ ec.modify_serverless_cache(ServerlessCacheName=name, MajorEngineVersion="7")+ assert exc.value.response["Error"]["Code"] == "InvalidParameterCombination"+ cache = ec.describe_serverless_caches(ServerlessCacheName=name)["ServerlessCaches"][0]+ assert (cache["Engine"], cache["MajorEngineVersion"]) == ("valkey", "8")++ with pytest.raises(ClientError) as exc:+ ec.modify_serverless_cache(ServerlessCacheName=name, Engine="redis")+ assert exc.value.response["Error"]["Code"] == "InvalidParameterCombination"+ cache = ec.describe_serverless_caches(ServerlessCacheName=name)["ServerlessCaches"][0]+ assert (cache["Engine"], cache["MajorEngineVersion"]) == ("valkey", "8")+ finally:+ ec.delete_serverless_cache(ServerlessCacheName=name)+++def test_serverless_cache_modify(ec):+ name = f"sls-mod-{_uid()}"+ ec.create_serverless_cache(+ ServerlessCacheName=name, Engine="redis",+ CacheUsageLimits={"DataStorage": {"Maximum": 5, "Unit": "GB"}},+ )+ try:+ cache = _wait_serverless(ec, name)+ assert cache["Status"] == "available"+ assert (cache["MajorEngineVersion"], cache["FullEngineVersion"]) == ("7", "7.1")++ modified = ec.modify_serverless_cache(ServerlessCacheName=name, Description="rate limits")+ assert modified["ServerlessCache"]["Description"] == "rate limits"+ ec.modify_serverless_cache(ServerlessCacheName=name, SnapshotRetentionLimit=3,+ DailySnapshotTime="09:00")+ # All-zero limits remove them, as the Terraform provider sends to clear the block.+ ec.modify_serverless_cache(ServerlessCacheName=name, CacheUsageLimits={+ "DataStorage": {"Maximum": 0, "Minimum": 0, "Unit": "GB"},+ "ECPUPerSecond": {"Maximum": 0, "Minimum": 0}})+ cache = ec.describe_serverless_caches(ServerlessCacheName=name)["ServerlessCaches"][0]+ assert cache["SnapshotRetentionLimit"] == 3+ assert cache["DailySnapshotTime"] == "09:00"+ assert "CacheUsageLimits" not in cache++ for kwargs, code in (+ ({}, "InvalidParameterCombination"),+ ({"UserGroupId": "missing-group", "RemoveUserGroup": True}, "InvalidParameterCombination"),+ ({"UserGroupId": "missing-group"}, "UserGroupNotFound"),+ ):+ with pytest.raises(ClientError) as exc:+ ec.modify_serverless_cache(ServerlessCacheName=name, **kwargs)+ assert exc.value.response["Error"]["Code"] == code+ finally:+ ec.delete_serverless_cache(ServerlessCacheName=name)+ with pytest.raises(ClientError) as exc:+ ec.modify_serverless_cache(ServerlessCacheName=name, Description="gone")+ assert exc.value.response["Error"]["Code"] == "ServerlessCacheNotFoundFault"+++def test_serverless_cache_describe_pages(ec):+ names = [f"sls-page-{_uid()}" for _ in range(3)]+ for name in names:+ ec.create_serverless_cache(ServerlessCacheName=name, Engine="valkey")+ try:+ seen, token = [], None+ while True:+ kwargs = {"MaxResults": 2, **({"NextToken": token} if token else {})}+ page = ec.describe_serverless_caches(**kwargs)+ assert len(page["ServerlessCaches"]) <= 2+ seen += [c["ServerlessCacheName"] for c in page["ServerlessCaches"]]+ token = page.get("NextToken")+ if not token:+ break+ assert set(names) <= set(seen)+ assert len(seen) == len(set(seen))+ finally:+ for name in names:+ ec.delete_serverless_cache(ServerlessCacheName=name)++@pytest.mark.data_plane-def test_serverless_cache_not_implemented(ec):- """Serverless cache operations are not yet implemented; verify graceful error."""- with pytest.raises(ClientError):- ec.create_serverless_cache(- ServerlessCacheName="test-serverless",- Engine="redis",- )+def test_serverless_cache_serves_tls_only(ec, tmp_path):+ """Serverless caches have no plaintext listener; a client that trusts+ MiniStack's ElastiCache CA connects with TLS and verifies the hostname."""+ import socket+ ca_file = _serverless_ca_file(tmp_path)+ name = f"sls-tls-{_uid()}"+ ec.create_serverless_cache(ServerlessCacheName=name, Engine="valkey")+ try:+ cache = _wait_serverless(ec, name)+ assert cache["Status"] == "available"+ endpoint = cache["Endpoint"]+ assert cache["ReaderEndpoint"] == endpoint+ assert _tls_command(endpoint, ca_file, "PING") == b"+PONG\r\n"+ assert b"valkey_version:8.1" in _tls_command(endpoint, ca_file, "INFO server")++ with socket.create_connection((endpoint["Address"], endpoint["Port"]), timeout=10) as raw:+ raw.sendall(b"*1\r\n$4\r\nPING\r\n")+ raw.settimeout(5)+ try:+ reply = raw.recv(64)+ except (ConnectionResetError, socket.timeout):+ reply = b""+ assert b"PONG" not in reply+ finally:+ ec.delete_serverless_cache(ServerlessCacheName=name)+ with pytest.raises(OSError):+ _tls_command(endpoint, ca_file, "PING")++[email protected]_plane+def test_serverless_cache_engine_change_replaces_container_on_same_endpoint(ec, tmp_path):+ ca_file = _serverless_ca_file(tmp_path)+ name = f"sls-eng-{_uid()}"+ ec.create_serverless_cache(ServerlessCacheName=name, Engine="redis")+ try:+ before = _wait_serverless(ec, name)+ assert b"redis_version:" in _tls_command(before["Endpoint"], ca_file, "INFO server")+ assert b"valkey_version" not in _tls_command(before["Endpoint"], ca_file, "INFO server")++ modified = ec.modify_serverless_cache(ServerlessCacheName=name, Engine="valkey",+ MajorEngineVersion="8")["ServerlessCache"]+ assert modified["Status"] == "modifying"+ with pytest.raises(ClientError) as exc:+ ec.modify_serverless_cache(ServerlessCacheName=name, Description="busy")+ assert exc.value.response["Error"]["Code"] == "InvalidServerlessCacheStateFault"++ after = _wait_serverless(ec, name)+ assert (after["Status"], after["Engine"], after["FullEngineVersion"]) == ("available", "valkey", "8.1")+ if not os.environ.get("DOCKER_NETWORK"):+ assert after["Endpoint"] == before["Endpoint"]+ assert b"valkey_version:8.1" in _tls_command(after["Endpoint"], ca_file, "INFO server")+ finally:+ ec.delete_serverless_cache(ServerlessCacheName=name)@@ -1868,3 +2127,148 @@ def test_elasticache_cluster_create_time_present_and_parsed(ec):assert isinstance(cluster.get("CacheClusterCreateTime"), datetime.datetime)finally:ec.delete_cache_cluster(CacheClusterId="cluster-createtime")+++# ---------------------------------------------------------------------------+# Serverless caches — provisioning state, not liveness+# ---------------------------------------------------------------------------++def _serverless_create_params(name, engine="valkey"):+ return {"ServerlessCacheName": [name], "Engine": [engine]}+++def test_serverless_cache_without_docker_points_at_sidecar(monkeypatch):+ from ministack.core.responses import set_request_account_id, set_request_region+ from ministack.services import elasticache as ec++ set_request_account_id("000000000000")+ set_request_region("us-east-1")+ ec.reset()+ monkeypatch.setattr(ec, "_get_docker", lambda: None)+ status, _headers, _body = ec._create_serverless_cache(_serverless_create_params("nodocker"))+ assert status == 200+ rec = ec._serverless_caches["nodocker"]+ assert rec["Status"] == "available"+ assert rec["Endpoint"] == {"Address": ec.REDIS_DEFAULT_HOST, "Port": ec.REDIS_DEFAULT_PORT}+ ec.reset()+++def test_serverless_cache_deleted_while_provisioning_leaves_no_container(fake_docker, monkeypatch):+ """A container that comes up after its cache was deleted is removed by the+ finisher itself: the delete had nothing to find, by id or by name."""+ import threading++ from ministack.core.responses import set_request_account_id, set_request_region+ from ministack.services import elasticache as ec++ set_request_account_id("000000000000")+ set_request_region("us-east-1")+ ec.reset()+ monkeypatch.setattr(ec, "_get_docker", lambda: fake_docker)++ started, release, finished = threading.Event(), threading.Event(), threading.Event()++ def fake_spawn(name, engine, full_version, host_port, labels, wait=True):+ started.set()+ release.wait(timeout=10)+ container = fake_docker.containers.run(name=name, labels=labels)+ return "localhost", host_port, container.id+ monkeypatch.setattr(ec, "_spawn_serverless_container", fake_spawn)++ orig = ec.spawn_background++ def tracked(fn, *a, **kw):+ t = orig(fn, *a, **kw)+ threading.Thread(target=lambda: (t.join(), finished.set()), daemon=True).start()+ return t+ monkeypatch.setattr(ec, "spawn_background", tracked)++ ec._create_serverless_cache(_serverless_create_params("race"))+ assert started.wait(timeout=10)+ ec._delete_serverless_cache({"ServerlessCacheName": ["race"]})+ release.set()+ assert finished.wait(timeout=10)++ assert "race" not in ec._serverless_caches+ assert fake_docker.live() == [], f"leaked container(s) {fake_docker.live()}"+++def test_serverless_cache_failed_start_reports_create_failed(fake_docker, monkeypatch):+ import threading++ from ministack.core.responses import set_request_account_id, set_request_region+ from ministack.services import elasticache as ec++ set_request_account_id("000000000000")+ set_request_region("us-east-1")+ ec.reset()+ monkeypatch.setattr(ec, "_get_docker", lambda: fake_docker)++ def boom(**_kw):+ raise RuntimeError("valkey never answered a TLS PING")+ monkeypatch.setattr(ec, "_spawn_serverless_container", boom)+ finished = threading.Event()+ orig = ec.spawn_background++ def tracked(fn, *a, **kw):+ t = orig(fn, *a, **kw)+ threading.Thread(target=lambda: (t.join(), finished.set()), daemon=True).start()+ return t+ monkeypatch.setattr(ec, "spawn_background", tracked)++ ec._create_serverless_cache(_serverless_create_params("broken"))+ assert finished.wait(timeout=10)+ assert ec._serverless_caches["broken"]["Status"] == "create-failed"+ assert "Endpoint" not in ec._serverless_caches["broken"]+ ec.reset()+++def test_serverless_cache_persists_and_respawns_on_the_same_port(monkeypatch):+ from ministack.services import elasticache as ec++ ec.reset()+ record = {+ "ServerlessCacheName": "kept", "Status": "available", "Engine": "valkey",+ "MajorEngineVersion": "8", "FullEngineVersion": "8.1", "CreateTime": time.time(),+ "ARN": "arn:aws:elasticache:us-west-2:000000000000:serverlesscache:kept",+ "Endpoint": {"Address": "localhost", "Port": 16400},+ "_host_port": 16400, "_docker_container_id": "dead",+ }+ ec._serverless_caches.set_scoped("000000000000", "us-west-2", "kept", record)+ state = ec.get_state()+ persisted = state["serverless_caches"].get_scoped("000000000000", "us-west-2", "kept")+ assert "_docker_container_id" not in persisted+ ec.reset()++ spawned = []++ def fake_spawn(name, engine, full_version, host_port, labels, wait=True):+ spawned.append((name, engine, full_version, host_port, labels["region"], wait))+ return "localhost", host_port, "cid-new"+ monkeypatch.setattr(ec, "_spawn_serverless_container", fake_spawn)+ monkeypatch.setattr(ec, "_get_docker", lambda: object())++ ec.load_persisted_state(state)+ ec._ensure_live_containers()+ assert spawned == [("ministack-elasticache-serverless-000000000000-us-west-2-kept",+ "valkey", "8.1", 16400, "us-west-2", False)]+ restored = ec._serverless_caches.get_scoped("000000000000", "us-west-2", "kept")+ assert restored["_docker_container_id"] == "cid-new"+ assert restored["Endpoint"] == {"Address": "localhost", "Port": 16400}+ assert "cid-new" in ec._live_container_ids()+ ec.reset()+++def test_serverless_ca_persists_across_restart(monkeypatch):+ from ministack.services import elasticache as ec++ pem = ec.serverless_ca_cert_pem()+ state = ec.get_state()+ assert state["serverless_ca"]["ca_cert_pem"] == pem++ monkeypatch.setattr(ec, "_serverless_ca", None)+ ec.load_persisted_state(state)+ assert ec.serverless_ca_cert_pem() == pem