Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

Enhancing the elasticache emulator code (#945)

ZiningYin5f5c6d323493
diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.py
index 169cb2a3..9feb79fa 100644
--- a/ministack/services/elasticache.py
+++ b/ministack/services/elasticache.py
@@ -45,6 +45,30 @@ DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "")
# CI/dev deterministic; flip to "1" to exercise sharded discovery.
ELASTICACHE_CLUSTER_MODE_REAL = os.environ.get("ELASTICACHE_CLUSTER_MODE_REAL", "") == "1"
+# All default parameter group names verified against the AWS ElastiCache console.
+_DEFAULT_PARAM_GROUP_FAMILIES = [
+ ("default.memcached1.4", "memcached1.4", "Default parameter group for memcached1.4"),
+ ("default.memcached1.5", "memcached1.5", "Default parameter group for memcached1.5"),
+ ("default.memcached1.6", "memcached1.6", "Default parameter group for memcached1.6"),
+ ("default.redis2.6", "redis2.6", "Default parameter group for redis2.6"),
+ ("default.redis2.8", "redis2.8", "Default parameter group for redis2.8"),
+ ("default.redis3.2", "redis3.2", "Default parameter group for redis3.2"),
+ ("default.redis3.2.cluster.on", "redis3.2", "Customized default parameter group for redis3.2 with cluster mode on"),
+ ("default.redis4.0", "redis4.0", "Default parameter group for redis4.0"),
+ ("default.redis4.0.cluster.on", "redis4.0", "Customized default parameter group for redis4.0 with cluster mode on"),
+ ("default.redis5.0", "redis5.0", "Default parameter group for redis5.0"),
+ ("default.redis5.0.cluster.on", "redis5.0", "Customized default parameter group for redis5.0 with cluster mode on"),
+ ("default.redis6.x", "redis6.x", "Default parameter group for redis6.x"),
+ ("default.redis6.x.cluster.on", "redis6.x", "Customized default parameter group for redis6.x with cluster mode on"),
+ ("default.redis7", "redis7", "Default parameter group for redis7"),
+ ("default.redis7.cluster.on", "redis7", "Customized default parameter group for redis7 with cluster mode on"),
+ ("default.valkey7", "valkey7", "Default parameter group for valkey7"),
+ ("default.valkey7.cluster.on", "valkey7", "Customized default parameter group for valkey7 with cluster mode on"),
+ ("default.valkey8", "valkey8", "Default parameter group for valkey8"),
+ ("default.valkey8.cluster.on", "valkey8", "Customized default parameter group for valkey8 with cluster mode on"),
+]
+_DEFAULT_PARAM_GROUP_NAMES = {name for name, _family, _desc in _DEFAULT_PARAM_GROUP_FAMILIES}
+
_clusters = AccountScopedDict()
_replication_groups = AccountScopedDict()
_subnet_groups = AccountScopedDict()
@@ -119,6 +143,7 @@ _respawn_lock = _threading.Lock()
def restore_state(data):
if not data:
+ default_state()
return
for name, rg in data.get("replication_groups", {}).items():
# Wipe stale container ids — the old Docker containers are dead.
@@ -140,6 +165,7 @@ def restore_state(data):
cl["CacheClusterStatus"] = "available"
_clusters[name] = cl
_pending_cluster_respawn.add(name)
+ default_state()
def _ensure_live_containers():
@@ -214,15 +240,100 @@ def _ensure_live_containers_locked():
"on restart; endpoint will be unreachable", rg_id, exc_info=True)
-try:
- _restored = load_state("elasticache")
- if _restored:
- restore_state(_restored)
-except Exception:
- import logging
- logging.getLogger(__name__).exception(
- "Failed to restore persisted state; continuing with fresh store"
+# ── Seed default ElastiCache parameter groups ─────────────────
+# AWS always provides built-in "default.*" parameter groups. Seed any that
+# are not already present (e.g. from restored state or user creation).
+def _seed_default_param_groups():
+ for _name, _family, _desc in _DEFAULT_PARAM_GROUP_FAMILIES:
+ if _name not in _param_groups:
+ _param_groups[_name] = {
+ "CacheParameterGroupName": _name,
+ "CacheParameterGroupFamily": _family,
+ "Description": _desc,
+ "IsGlobal": False,
+ "ARN": _arn_param_group(_name),
+ }
+ _param_group_params[_name] = _default_params_for_family(_family)
+
+
+def _stamp_replication_group_on_user_groups(rg_id, user_group_ids):
+ for group_id in user_group_ids:
+ group = _user_groups.get(group_id)
+ if not group:
+ continue
+ replication_groups = group.setdefault("ReplicationGroups", [])
+ if rg_id not in replication_groups:
+ replication_groups.append(rg_id)
+
+
+def _unstamp_replication_group_from_user_groups(rg_id, user_group_ids):
+ for group_id in user_group_ids:
+ group = _user_groups.get(group_id)
+ if not group:
+ continue
+ replication_groups = group.get("ReplicationGroups", [])
+ if rg_id in replication_groups:
+ replication_groups.remove(rg_id)
+
+
+def default_state():
+ _seed_default_param_groups()
+
+
+def _param_group_family_for_engine(engine, version):
+ engine = (engine or "redis").lower()
+ version = version or ""
+ parts = version.split(".")
+ major = parts[0] if parts and parts[0] else ""
+ minor = parts[1] if len(parts) > 1 else ""
+
+ if engine == "redis":
+ if major in {"2", "3", "4", "5"} and minor:
+ return f"redis{major}.{minor}"
+ if major == "6":
+ return "redis6.x"
+ if major == "7":
+ return "redis7"
+ elif engine == "memcached":
+ if major and minor:
+ return f"memcached{major}.{minor}"
+ elif engine == "valkey" and major:
+ return f"valkey{major}"
+
+ return f"{engine}{major}" if major else engine
+
+
+def _default_param_group_for_engine(engine, version, cluster_enabled=False):
+ family = _param_group_family_for_engine(engine, version)
+ name = f"default.{family}"
+ cluster_name = f"{name}.cluster.on"
+ if cluster_enabled and (cluster_name in _DEFAULT_PARAM_GROUP_NAMES or cluster_name in _param_groups):
+ return cluster_name
+ return name
+
+
+def _is_default_param_group(name):
+ return name in _DEFAULT_PARAM_GROUP_NAMES
+
+
+def _validate_create_replication_group_request(p):
+ for user_group_id in _extract_configs(p, "UserGroupIds", ("member", "UserGroupId")):
+ if user_group_id not in _user_groups:
+ return _error("UserGroupNotFound",
+ "The user group was not found or does not exist", 404)
+ return None
+
+
+def _validate_modify_replication_group_request(p):
+ user_group_ids = (
+ _extract_configs(p, "UserGroupIdsToAdd", ("member",)) +
+ _extract_configs(p, "UserGroupIdsToRemove", ("member",))
)
+ for user_group_id in user_group_ids:
+ if user_group_id not in _user_groups:
+ return _error("UserGroupNotFound",
+ "The user group was not found or does not exist", 404)
+ return None
def _get_docker():
@@ -647,7 +758,7 @@ def _create_cache_cluster(p):
)
subnet_group = _p(p, "CacheSubnetGroupName") or "default"
- param_group_name = _p(p, "CacheParameterGroupName") or f"default.{engine}{engine_version[:3]}"
+ param_group_name = _p(p, "CacheParameterGroupName") or _default_param_group_for_engine(engine, engine_version)
_clusters[cluster_id] = {
"CacheClusterId": cluster_id,
@@ -685,9 +796,7 @@ def _create_cache_cluster(p):
"_endpoint": {"Address": endpoint_host, "Port": endpoint_port},
}
- tags = _extract_tags(p)
- if tags:
- _tags[arn] = tags
+ _tags[arn] = _extract_tags(p)
_record_event(cluster_id, "cache-cluster", "Cache cluster created")
return _xml_cluster_response("CreateCacheClusterResponse", "CreateCacheClusterResult", _clusters[cluster_id])
@@ -787,13 +896,18 @@ def _create_replication_group(p):
engine = _p(p, "Engine") or "redis"
engine_version = _p(p, "EngineVersion") or "7.0.12"
num_node_groups = int(_p(p, "NumNodeGroups") or "1")
- replicas_per_node_group = int(_p(p, "ReplicasPerNodeGroup") or "1")
+ num_cache_clusters = int(_p(p, "NumCacheClusters") or "1")
+ replicas_per_node_group = int(_p(p, "ReplicasPerNodeGroup") or max(num_cache_clusters - 1, 0))
arn = _arn_replication_group(rg_id)
if rg_id in _replication_groups:
return _error("ReplicationGroupAlreadyExistsFault",
f"Replication group {rg_id} already exists", 400)
+ validation_error = _validate_create_replication_group_request(p)
+ if validation_error:
+ return validation_error
+
# AWS rejects NumNodeGroups=2: cluster-mode-enabled requires the redis-
# cluster minimum of 3 masters; cluster-mode-disabled requires 1.
if num_node_groups == 2:
@@ -887,22 +1001,50 @@ def _create_replication_group(p):
if num_node_groups > 1 and node_groups:
config_ep = node_groups[0]["PrimaryEndpoint"]
+ user_group_ids = _extract_configs(p, "UserGroupIds", ("member", "UserGroupId"))
+ subnet_group = _p(p, "CacheSubnetGroupName") or "default"
+ cluster_mode = _p(p, "ClusterMode") or ("enabled" if num_node_groups > 1 else "disabled")
+ cluster_enabled = cluster_mode == "enabled"
+ param_group_name = _p(p, "CacheParameterGroupName") or _default_param_group_for_engine(
+ engine, engine_version, cluster_enabled=cluster_enabled)
+ maintenance_window = _p(p, "PreferredMaintenanceWindow") or "sun:05:00-sun:06:00"
+ snapshot_retention_limit = int(_p(p, "SnapshotRetentionLimit") or "0")
+ snapshot_window = _p(p, "SnapshotWindow") or "05:00-06:00"
+ security_groups = []
+ for sg_id in _extract_configs(p, "SecurityGroupIds", ("SecurityGroupId", "member")):
+ security_groups.append({"SecurityGroupId": sg_id, "Status": "active"})
+ log_delivery_configs = _extract_log_delivery_configs(p)
+ member_cluster_ids = []
+ for ng in node_groups:
+ for m in ng.get("NodeGroupMembers", []):
+ member_cluster_ids.append(m["CacheClusterId"])
+
_replication_groups[rg_id] = {
"ReplicationGroupId": rg_id,
"Description": desc,
"Status": "available",
- "MemberClusters": [],
+ "MemberClusters": member_cluster_ids,
"NodeGroups": node_groups,
"SnapshottingClusterId": "",
- "SnapshotRetentionLimit": int(_p(p, "SnapshotRetentionLimit") or "0"),
- "SnapshotWindow": _p(p, "SnapshotWindow") or "05:00-06:00",
+ "SnapshotRetentionLimit": snapshot_retention_limit,
+ "SnapshotWindow": snapshot_window,
+ "Engine": engine,
+ "EngineVersion": engine_version,
"ClusterEnabled": num_node_groups > 1,
+ "ClusterMode": cluster_mode,
"CacheNodeType": node_type,
+ "CacheParameterGroupName": param_group_name,
+ "CacheSubnetGroupName": subnet_group,
+ "PreferredMaintenanceWindow": maintenance_window,
+ "SecurityGroups": security_groups,
"AuthTokenEnabled": _p(p, "AuthToken") != "",
"TransitEncryptionEnabled": _p(p, "TransitEncryptionEnabled", "false").lower() == "true",
"AtRestEncryptionEnabled": _p(p, "AtRestEncryptionEnabled", "false").lower() == "true",
+ "AutoMinorVersionUpgrade": _p(p, "AutoMinorVersionUpgrade", "true").lower() == "true",
"AutomaticFailover": "enabled" if _p(p, "AutomaticFailoverEnabled", "false").lower() == "true" else "disabled",
"MultiAZ": "enabled" if _p(p, "MultiAZEnabled", "false").lower() == "true" else "disabled",
+ "LogDeliveryConfigurations": log_delivery_configs,
+ "UserGroupIds": user_group_ids,
"ConfigurationEndpoint": config_ep,
"ARN": arn,
"_num_node_groups": num_node_groups,
@@ -910,11 +1052,55 @@ def _create_replication_group(p):
"_docker_container_ids": container_ids,
}
- tags = _extract_tags(p)
- if tags:
- _tags[arn] = tags
+ _tags[arn] = _extract_tags(p)
+
+ for ng in node_groups:
+ for m in ng.get("NodeGroupMembers", []):
+ cluster_id = m["CacheClusterId"]
+ cluster_arn = _arn_cluster(cluster_id)
+ endpoint = m.get("ReadEndpoint", {}) or ng.get("PrimaryEndpoint", {})
+ _clusters[cluster_id] = {
+ "CacheClusterId": cluster_id,
+ "CacheClusterArn": cluster_arn,
+ "CacheClusterStatus": "available",
+ "Engine": engine,
+ "EngineVersion": engine_version,
+ "CacheNodeType": node_type,
+ "NumCacheNodes": 1,
+ "CacheClusterCreateTime": time.time(),
+ "PreferredAvailabilityZone": m.get("PreferredAvailabilityZone", f"{get_region()}a"),
+ "CacheParameterGroup": {
+ "CacheParameterGroupName": param_group_name,
+ "ParameterApplyStatus": "in-sync",
+ },
+ "CacheSubnetGroupName": subnet_group,
+ "AutoMinorVersionUpgrade": _p(p, "AutoMinorVersionUpgrade", "true").lower() == "true",
+ "SecurityGroups": security_groups,
+ "ReplicationGroupId": rg_id,
+ "SnapshotRetentionLimit": snapshot_retention_limit,
+ "SnapshotWindow": snapshot_window,
+ "PreferredMaintenanceWindow": maintenance_window,
+ "LogDeliveryConfigurations": log_delivery_configs,
+ "AtRestEncryptionEnabled": _p(p, "AtRestEncryptionEnabled", "false").lower() == "true",
+ "AuthTokenEnabled": _p(p, "AuthToken") != "",
+ "TransitEncryptionEnabled": _p(p, "TransitEncryptionEnabled", "false").lower() == "true",
+ "CacheNodes": [
+ {
+ "CacheNodeId": m.get("CacheNodeId", "0001"),
+ "CacheNodeStatus": "available",
+ "CacheNodeCreateTime": time.time(),
+ "Endpoint": endpoint,
+ "ParameterGroupStatus": "in-sync",
+ "SourceCacheNodeId": "",
+ }
+ ],
+ "_docker_container_id": None,
+ "_endpoint": endpoint,
+ }
+ _tags[cluster_arn] = _copy_tag_list(_tags[arn])
_record_event(rg_id, "replication-group", "Replication group created")
+ _stamp_replication_group_on_user_groups(rg_id, user_group_ids)
return _xml(200, "CreateReplicationGroupResponse",
f"<CreateReplicationGroupResult><ReplicationGroup>{_rg_xml(_replication_groups[rg_id])}</ReplicationGroup></CreateReplicationGroupResult>")
@@ -936,7 +1122,12 @@ def _delete_replication_group(p):
logger.warning("ElastiCache: failed to remove RG container %s for %s: %s", cid, rg_id, e)
_tags.pop(rg.get("ARN", ""), None)
+ for cluster_id in rg.get("MemberClusters") or []:
+ cluster = _clusters.pop(cluster_id, None)
+ if cluster:
+ _tags.pop(cluster.get("CacheClusterArn", ""), None)
_record_event(rg_id, "replication-group", "Replication group deleted")
+ _unstamp_replication_group_from_user_groups(rg_id, rg.get("UserGroupIds", []))
return _xml(200, "DeleteReplicationGroupResponse",
f"<DeleteReplicationGroupResult><ReplicationGroup>{_rg_xml(rg)}</ReplicationGroup></DeleteReplicationGroupResult>")
@@ -963,6 +1154,10 @@ def _modify_replication_group(p):
if not rg:
return _error("ReplicationGroupNotFoundFault", f"Replication group {rg_id} not found", 404)
+ validation_error = _validate_modify_replication_group_request(p)
+ if validation_error:
+ return validation_error
+
if _p(p, "ReplicationGroupDescription"):
rg["Description"] = _p(p, "ReplicationGroupDescription")
if _p(p, "CacheNodeType"):
@@ -980,6 +1175,20 @@ def _modify_replication_group(p):
if _p(p, "CacheParameterGroupName"):
rg["CacheParameterGroupName"] = _p(p, "CacheParameterGroupName")
+ user_group_ids_to_add = _extract_configs(p, "UserGroupIdsToAdd", ("member",))
+ user_group_ids_to_remove = _extract_configs(p, "UserGroupIdsToRemove", ("member",))
+
+ rg_user_group_ids = rg.setdefault("UserGroupIds", [])
+ for group_id in user_group_ids_to_add:
+ if group_id not in rg_user_group_ids:
+ rg_user_group_ids.append(group_id)
+ _stamp_replication_group_on_user_groups(rg_id, [group_id])
+
+ for group_id in user_group_ids_to_remove:
+ if group_id in rg_user_group_ids:
+ rg_user_group_ids.remove(group_id)
+ _unstamp_replication_group_from_user_groups(rg_id, [group_id])
+
_record_event(rg_id, "replication-group", "Replication group modified")
return _xml(200, "ModifyReplicationGroupResponse",
f"<ModifyReplicationGroupResult><ReplicationGroup>{_rg_xml(rg)}</ReplicationGroup></ModifyReplicationGroupResult>")
@@ -1061,6 +1270,7 @@ def _create_subnet_group(p):
"Subnets": subnets,
"ARN": arn,
}
+ _tags[arn] = []
subnets_xml = "".join(
f"<Subnet><SubnetIdentifier>{s['SubnetIdentifier']}</SubnetIdentifier>"
f"<SubnetAvailabilityZone><Name>{s['SubnetAvailabilityZone']['Name']}</Name></SubnetAvailabilityZone>"
@@ -1143,8 +1353,11 @@ def _modify_subnet_group(p):
def _create_param_group(p):
name = _p(p, "CacheParameterGroupName")
- family = _p(p, "CacheParameterGroupFamily") or "redis7.0"
+ family = _p(p, "CacheParameterGroupFamily") or _param_group_family_for_engine("redis", "7.0")
desc = _p(p, "Description") or ""
+ if name in _param_groups:
+ return _error("CacheParameterGroupAlreadyExists",
+ f"Cache parameter group {name} already exists.", 400)
arn = _arn_param_group(name)
_param_groups[name] = {
"CacheParameterGroupName": name,
@@ -1154,6 +1367,9 @@ def _create_param_group(p):
"ARN": arn,
}
_param_group_params[name] = _default_params_for_family(family)
+
+ _tags[arn] = _extract_tags(p)
+
return _xml(200, "CreateCacheParameterGroupResponse",
f"<CreateCacheParameterGroupResult><CacheParameterGroup>"
f"<CacheParameterGroupName>{name}</CacheParameterGroupName>"
@@ -1184,6 +1400,9 @@ def _delete_param_group(p):
name = _p(p, "CacheParameterGroupName")
if name not in _param_groups:
return _error("CacheParameterGroupNotFound", f"Cache parameter group {name} not found.", 404)
+ if _is_default_param_group(name):
+ return _error("InvalidCacheParameterGroupState",
+ "Default cache parameter groups cannot be deleted.", 400)
pg = _param_groups.pop(name, None)
_param_group_params.pop(name, None)
if pg:
@@ -1221,6 +1440,9 @@ def _modify_cache_parameter_group(p):
if name not in _param_groups:
return _error("CacheParameterGroupNotFound",
f"Parameter group {name} not found", 404)
+ if _is_default_param_group(name):
+ return _error("InvalidCacheParameterGroupState",
+ "Default cache parameter groups cannot be modified.", 400)
params = _param_group_params.setdefault(name, {})
idx = 1
@@ -1246,9 +1468,12 @@ def _reset_cache_parameter_group(p):
if name not in _param_groups:
return _error("CacheParameterGroupNotFound",
f"Parameter group {name} not found", 404)
+ if _is_default_param_group(name):
+ return _error("InvalidCacheParameterGroupState",
+ "Default cache parameter groups cannot be modified.", 400)
reset_all = _p(p, "ResetAllParameters", "false").lower() == "true"
- family = _param_groups[name].get("CacheParameterGroupFamily", "redis7.0")
+ family = _param_groups[name].get("CacheParameterGroupFamily", _param_group_family_for_engine("redis", "7.0"))
if reset_all:
_param_group_params[name] = _default_params_for_family(family)
@@ -1270,7 +1495,7 @@ def _reset_cache_parameter_group(p):
def _default_params_for_family(family):
"""Seed with commonly queried Redis/Memcached default parameters."""
- if family.startswith("redis"):
+ if family.startswith(("redis", "valkey")):
return {
"maxmemory-policy": {"Value": "volatile-lru", "Description": "Eviction policy",
"Source": "system", "DataType": "string",
@@ -1295,6 +1520,16 @@ def _default_params_for_family(family):
}
+try:
+ _restored = load_state("elasticache")
+ restore_state(_restored)
+except Exception:
+ import logging
+ logging.getLogger(__name__).exception(
+ "Failed to restore persisted state; continuing with fresh store"
+ )
+
+
# ---- Engine Versions ----
def _describe_engine_versions(p):
@@ -1303,7 +1538,7 @@ def _describe_engine_versions(p):
# CacheEngineVersionList.member.locationName = "CacheEngineVersion"
members = "".join(
f"<CacheEngineVersion><Engine>{engine}</Engine><EngineVersion>{v}</EngineVersion>"
- f"<CacheParameterGroupFamily>{engine}{v[:3]}</CacheParameterGroupFamily></CacheEngineVersion>"
+ f"<CacheParameterGroupFamily>{_param_group_family_for_engine(engine, v)}</CacheParameterGroupFamily></CacheEngineVersion>"
for v in versions.get(engine, ["7.0.12"])
)
return _xml(200, "DescribeCacheEngineVersionsResponse",
@@ -1328,6 +1563,101 @@ def _extract_tags(p):
return tags
+def _extract_configs(p, container, item_names):
+ values = []
+ for item_name in item_names:
+ idx = 1
+ while _p(p, f"{container}.{item_name}.{idx}"):
+ values.append(_p(p, f"{container}.{item_name}.{idx}"))
+ idx += 1
+ if values:
+ break
+ return values
+
+
+def _extract_log_delivery_configs(p):
+ configs = []
+ for prefix in (
+ "LogDeliveryConfigurations.LogDeliveryConfigurationRequest",
+ "LogDeliveryConfigurations.member",
+ ):
+ idx = 1
+ while (
+ _p(p, f"{prefix}.{idx}.LogType")
+ or _p(p, f"{prefix}.{idx}.Enabled")
+ or _p(p, f"{prefix}.{idx}.DestinationType")
+ ):
+ enabled = _p(p, f"{prefix}.{idx}.Enabled", "true").lower() == "true"
+ if enabled:
+ log_type = _p(p, f"{prefix}.{idx}.LogType")
+ log_group = _p(
+ p,
+ f"{prefix}.{idx}.DestinationDetails.CloudWatchLogsDetails.LogGroup",
+ )
+ configs.append({
+ "DestinationDetails": {
+ "CloudWatchLogsDetails": {"LogGroup": log_group},
+ },
+ "DestinationType": _p(p, f"{prefix}.{idx}.DestinationType") or "cloudwatch-logs",
+ "LogFormat": _p(p, f"{prefix}.{idx}.LogFormat") or "text",
+ "LogType": log_type,
+ "Status": "active",
+ "Message": "",
+ })
+ idx += 1
+ if configs:
+ break
+ return configs
+
+
+def _tag_list_to_map(tags):
+ return {t["Key"]: t.get("Value", "") for t in (tags or [])}
+
+
+def _tag_map_to_list(tag_map):
+ return [{"Key": k, "Value": v} for k, v in tag_map.items()]
+
+
+def _copy_tag_list(tags):
+ return [{"Key": t["Key"], "Value": t.get("Value", "")} for t in (tags or [])]
+
+
+def _replication_group_for_arn(arn):
+ parts = arn.split(":", 5)
+ if len(parts) < 6:
+ return None
+ resource_type, sep, resource_id = parts[5].partition(":")
+ if sep and resource_type == "replicationgroup":
+ return _replication_groups.get(resource_id)
+ return None
+
+
+def _propagate_replication_group_tags(arn):
+ rg = _replication_group_for_arn(arn)
+ if not rg:
+ return
+ tags = _copy_tag_list(_tags.get(arn, []))
+ for cluster_id in rg.get("MemberClusters") or []:
+ cluster = _clusters.get(cluster_id)
+ cluster_arn = cluster.get("CacheClusterArn") if cluster else _arn_cluster(cluster_id)
+ _tags[cluster_arn] = _copy_tag_list(tags)
+
+
+def _merge_tags_for_arn(arn, tags):
+ existing = _tag_list_to_map(_tags.get(arn, []))
+ existing.update(_tag_list_to_map(tags))
+ _tags[arn] = _tag_map_to_list(existing)
+ _propagate_replication_group_tags(arn)
+ return _tags[arn]
+
+
+def _remove_tag_keys_for_arn(arn, keys):
+ keys = set(keys or [])
+ _tags[arn] = [t for t in _tags.get(arn, []) if t["Key"] not in keys]
+ _propagate_replication_group_tags(arn)
+ return _tags[arn]
+
+
def _list_tags(p):
arn = _p(p, "ResourceName")
tags = _tags.get(arn, [])
@@ -1340,19 +1670,9 @@ def _list_tags(p):
def _add_tags(p):
arn = _p(p, "ResourceName")
new_tags = _extract_tags(p)
- existing = _tags.setdefault(arn, [])
- existing_keys = {t["Key"] for t in existing}
- for t in new_tags:
- if t["Key"] in existing_keys:
- for e in existing:
- if e["Key"] == t["Key"]:
- e["Value"] = t["Value"]
- break
- else:
- existing.append(t)
- existing_keys.add(t["Key"])
+ tags = _merge_tags_for_arn(arn, new_tags)
- tag_xml = "".join(f"<Tag><Key>{t['Key']}</Key><Value>{t['Value']}</Value></Tag>" for t in existing)
+ tag_xml = "".join(f"<Tag><Key>{t['Key']}</Key><Value>{t['Value']}</Value></Tag>" for t in tags)
return _xml(200, "AddTagsToResourceResponse",
f"<AddTagsToResourceResult><TagList>{tag_xml}</TagList></AddTagsToResourceResult>")
@@ -1364,10 +1684,7 @@ def _remove_tags(p):
while _p(p, f"TagKeys.member.{idx}"):
keys_to_remove.add(_p(p, f"TagKeys.member.{idx}"))
idx += 1
- if arn in _tags:
- _tags[arn] = [t for t in _tags[arn] if t["Key"] not in keys_to_remove]
-
- tags = _tags.get(arn, [])
+ tags = _remove_tag_keys_for_arn(arn, keys_to_remove)
tag_xml = "".join(f"<Tag><Key>{t['Key']}</Key><Value>{t['Value']}</Value></Tag>" for t in tags)
return _xml(200, "RemoveTagsFromResourceResponse",
f"<RemoveTagsFromResourceResult><TagList>{tag_xml}</TagList></RemoveTagsFromResourceResult>")
@@ -1411,6 +1728,7 @@ def _create_snapshot(p):
_snapshots[snapshot_name]["Engine"] = src.get("Engine", "redis")
_snapshots[snapshot_name]["EngineVersion"] = src.get("EngineVersion", "7.0.12")
+ _tags[arn] = []
_record_event(snapshot_name, "snapshot", "Snapshot created")
return _xml(200, "CreateSnapshotResponse",
f"<CreateSnapshotResult><Snapshot>{_snapshot_xml(_snapshots[snapshot_name])}</Snapshot></CreateSnapshotResult>")
@@ -1490,7 +1808,7 @@ def _create_user(p):
if not user_id:
return _error("InvalidParameterValue", "UserId is required", 400)
if user_id in _users:
- return _error("UserAlreadyExistsFault", f"User {user_id} already exists", 400)
+ return _error("UserAlreadyExists", f"User {user_id} already exists", 400)
arn = _arn_user(user_id)
user = {
@@ -1505,9 +1823,7 @@ def _create_user(p):
}
_users[user_id] = user
- tags = _extract_tags(p)
- if tags:
- _tags[arn] = tags
+ _tags[arn] = _extract_tags(p)
return _xml(200, "CreateUserResponse", f"<CreateUserResult>{_user_xml(user)}</CreateUserResult>")
@@ -1519,7 +1835,7 @@ def _describe_users(p):
if user_id:
user = _users.get(user_id)
if not user:
- return _error("UserNotFoundFault", f"User {user_id} not found", 404)
+ return _error("UserNotFound", f"User {user_id} not found", 404)
users = [user]
else:
users = list(_users.values())
@@ -1535,7 +1851,7 @@ def _delete_user(p):
user_id = _p(p, "UserId")
user = _users.pop(user_id, None)
if not user:
- return _error("UserNotFoundFault", f"User {user_id} not found", 404)
+ return _error("UserNotFound", f"User {user_id} not found", 404)
_tags.pop(user.get("ARN", ""), None)
user["Status"] = "deleting"
return _xml(200, "DeleteUserResponse", f"<DeleteUserResult>{_user_xml(user)}</DeleteUserResult>")
@@ -1545,7 +1861,7 @@ def _modify_user(p):
user_id = _p(p, "UserId")
user = _users.get(user_id)
if not user:
- return _error("UserNotFoundFault", f"User {user_id} not found", 404)
+ return _error("UserNotFound", f"User {user_id} not found", 404)
if _p(p, "AccessString"):
user["AccessString"] = _p(p, "AccessString")
@@ -1560,7 +1876,7 @@ def _create_user_group(p):
if not group_id:
return _error("InvalidParameterValue", "UserGroupId is required", 400)
if group_id in _user_groups:
- return _error("UserGroupAlreadyExistsFault", f"User group {group_id} already exists", 400)
+ return _error("UserGroupAlreadyExists", f"User group {group_id} already exists", 400)
arn = _arn_user_group(group_id)
user_ids = []
@@ -1584,9 +1900,7 @@ def _create_user_group(p):
if uid in _users:
_users[uid].setdefault("UserGroupIds", []).append(group_id)
- tags = _extract_tags(p)
- if tags:
- _tags[arn] = tags
+ _tags[arn] = _extract_tags(p)
return _xml(200, "CreateUserGroupResponse", f"<CreateUserGroupResult>{_user_group_xml(group)}</CreateUserGroupResult>")
@@ -1597,7 +1911,7 @@ def _describe_user_groups(p):
if group_id:
group = _user_groups.get(group_id)
if not group:
- return _error("UserGroupNotFoundFault", f"User group {group_id} not found", 404)
+ return _error("UserGroupNotFound", f"User group {group_id} not found", 404)
groups = [group]
else:
groups = list(_user_groups.values())
@@ -1611,7 +1925,7 @@ def _delete_user_group(p):
group_id = _p(p, "UserGroupId")
group = _user_groups.pop(group_id, None)
if not group:
- return _error("UserGroupNotFoundFault", f"User group {group_id} not found", 404)
+ return _error("UserGroupNotFound", f"User group {group_id} not found", 404)
_tags.pop(group.get("ARN", ""), None)
for uid in group.get("UserIds", []):
@@ -1628,7 +1942,7 @@ def _modify_user_group(p):
group_id = _p(p, "UserGroupId")
group = _user_groups.get(group_id)
if not group:
- return _error("UserGroupNotFoundFault", f"User group {group_id} not found", 404)
+ return _error("UserGroupNotFound", f"User group {group_id} not found", 404)
to_add = []
idx = 1
@@ -1690,6 +2004,42 @@ def _user_group_xml(g):
# ---- XML helpers ----
+def _security_groups_xml(groups):
+ xml = ""
+ for g in groups or []:
+ xml += (
+ f"<member><SecurityGroupId>{g.get('SecurityGroupId', '')}</SecurityGroupId>"
+ f"<Status>{g.get('Status', 'active')}</Status></member>"
+ )
+ return xml
+
+
+def _log_delivery_configs_xml(configs):
+ items = []
+ for config in configs or []:
+ destination = config.get("DestinationDetails", {})
+ cloudwatch = destination.get("CloudWatchLogsDetails", {})
+ log_group = cloudwatch.get("LogGroup", "")
+ destination_xml = ""
+ if log_group:
+ destination_xml = (
+ f"<DestinationDetails><CloudWatchLogsDetails>"
+ f"<LogGroup>{log_group}</LogGroup>"
+ f"</CloudWatchLogsDetails></DestinationDetails>"
+ )
+ items.append(
+ f"<LogDeliveryConfiguration>"
+ f"{destination_xml}"
+ f"<DestinationType>{config.get('DestinationType', 'cloudwatch-logs')}</DestinationType>"
+ f"<LogFormat>{config.get('LogFormat', 'text')}</LogFormat>"
+ f"<LogType>{config.get('LogType', '')}</LogType>"
+ f"<Status>{config.get('Status', 'active')}</Status>"
+ f"<Message>{config.get('Message', '')}</Message>"
+ f"</LogDeliveryConfiguration>"
+ )
+ return "".join(items)
+
+
def _cluster_xml_inner(c):
"""Render cluster fields — no wrapping element."""
ep = c.get("_endpoint", {})
@@ -1720,6 +2070,9 @@ def _cluster_xml_inner(c):
f"{src_xml}"
f"</CacheNode>"
)
+ parameter_group = c.get("CacheParameterGroup", {})
+ security_groups_xml = _security_groups_xml(c.get("SecurityGroups", []))
+ log_delivery_configs_xml = _log_delivery_configs_xml(c.get("LogDeliveryConfigurations", []))
return (
f"<CacheClusterId>{c['CacheClusterId']}</CacheClusterId>"
f"<CacheClusterStatus>{c['CacheClusterStatus']}</CacheClusterStatus>"
@@ -1730,10 +2083,15 @@ def _cluster_xml_inner(c):
f"<CacheClusterArn>{c['CacheClusterArn']}</CacheClusterArn>"
f"<ARN>{c.get('CacheClusterArn', '')}</ARN>"
f"<PreferredAvailabilityZone>{c.get('PreferredAvailabilityZone', '')}</PreferredAvailabilityZone>"
+ f"<PreferredMaintenanceWindow>{c.get('PreferredMaintenanceWindow', '')}</PreferredMaintenanceWindow>"
+ f"<CacheParameterGroup><CacheParameterGroupName>{parameter_group.get('CacheParameterGroupName', '')}</CacheParameterGroupName>"
+ f"<ParameterApplyStatus>{parameter_group.get('ParameterApplyStatus', 'in-sync')}</ParameterApplyStatus></CacheParameterGroup>"
f"<CacheSubnetGroupName>{c.get('CacheSubnetGroupName', '')}</CacheSubnetGroupName>"
+ f"<SecurityGroups>{security_groups_xml}</SecurityGroups>"
f"<ReplicationGroupId>{c.get('ReplicationGroupId', '')}</ReplicationGroupId>"
f"<SnapshotRetentionLimit>{c.get('SnapshotRetentionLimit', 0)}</SnapshotRetentionLimit>"
f"<SnapshotWindow>{c.get('SnapshotWindow', '')}</SnapshotWindow>"
+ f"<LogDeliveryConfigurations>{log_delivery_configs_xml}</LogDeliveryConfigurations>"
f"<CacheNodes>{nodes_xml}</CacheNodes>"
)
@@ -1786,21 +2144,34 @@ def _rg_xml(rg):
f"<Port>{cep['Port']}</Port></ConfigurationEndpoint>"
)
+ member_clusters_xml = ""
+ for cluster_id in rg.get("MemberClusters", []):
+ member_clusters_xml += f"<ClusterId>{cluster_id}</ClusterId>"
+ user_group_ids_xml = ""
+ for user_group_id in rg.get("UserGroupIds", []):
+ user_group_ids_xml += f"<member>{user_group_id}</member>"
+ log_delivery_configs_xml = _log_delivery_configs_xml(rg.get("LogDeliveryConfigurations", []))
return (
f"<ReplicationGroupId>{rg['ReplicationGroupId']}</ReplicationGroupId>"
f"<Description>{rg.get('Description', '')}</Description>"
f"<Status>{rg['Status']}</Status>"
+ f"<Engine>{rg.get('Engine', 'redis')}</Engine>"
f"<CacheNodeType>{rg.get('CacheNodeType', 'cache.t3.micro')}</CacheNodeType>"
f"<AutomaticFailover>{rg.get('AutomaticFailover', 'disabled')}</AutomaticFailover>"
+ f"<AutoMinorVersionUpgrade>{str(rg.get('AutoMinorVersionUpgrade', False)).lower()}</AutoMinorVersionUpgrade>"
f"<MultiAZ>{rg.get('MultiAZ', 'disabled')}</MultiAZ>"
f"<ClusterEnabled>{str(rg.get('ClusterEnabled', False)).lower()}</ClusterEnabled>"
+ f"<ClusterMode>{rg.get('ClusterMode', 'enabled' if rg.get('ClusterEnabled', False) else 'disabled')}</ClusterMode>"
f"<AuthTokenEnabled>{str(rg.get('AuthTokenEnabled', False)).lower()}</AuthTokenEnabled>"
f"<TransitEncryptionEnabled>{str(rg.get('TransitEncryptionEnabled', False)).lower()}</TransitEncryptionEnabled>"
f"<AtRestEncryptionEnabled>{str(rg.get('AtRestEncryptionEnabled', False)).lower()}</AtRestEncryptionEnabled>"
f"<SnapshotRetentionLimit>{rg.get('SnapshotRetentionLimit', 0)}</SnapshotRetentionLimit>"
f"<SnapshotWindow>{rg.get('SnapshotWindow', '')}</SnapshotWindow>"
f"{config_ep_xml}"
+ f"<MemberClusters>{member_clusters_xml}</MemberClusters>"
f"<NodeGroups>{node_groups_xml}</NodeGroups>"
+ f"<LogDeliveryConfigurations>{log_delivery_configs_xml}</LogDeliveryConfigurations>"
+ f"<UserGroupIds>{user_group_ids_xml}</UserGroupIds>"
f"<ARN>{rg['ARN']}</ARN>"
)
@@ -1888,3 +2259,4 @@ def reset():
_events.clear()
_tags.clear() # was missing from reset() — HIGH-severity gap from audit
_port_counter[0] = BASE_PORT
+ default_state()
diff --git a/ministack/services/tagging.py b/ministack/services/tagging.py
index 3246f928..c771d56a 100644
--- a/ministack/services/tagging.py
+++ b/ministack/services/tagging.py
@@ -187,6 +187,12 @@ def _collect_backup():
yield arn, _normalise_flat(p.get("Tags", {}))
+def _collect_elasticache():
+ import ministack.services.elasticache as svc
+ for arn, tags in svc._tags.items():
+ yield arn, _normalise_list(tags)
+
+
# ResourceTypeFilter prefix -> collector
_COLLECTORS = {
# Phase 1
@@ -208,6 +214,7 @@ _COLLECTORS = {
"cloudfront": _collect_cloudfront,
"elasticfilesystem": _collect_efs,
"backup": _collect_backup,
+ "elasticache": _collect_elasticache,
}
@@ -221,9 +228,20 @@ def _account():
def _matches_type_filters(arn, type_filters):
if not type_filters:
return True
+ parts = arn.split(":", 5)
+ arn_service = parts[2] if len(parts) > 2 else ""
+ resource = parts[5] if len(parts) > 5 else ""
+ if "/" in resource:
+ arn_resource_type = resource.split("/", 1)[0]
+ else:
+ arn_resource_type = resource.split(":", 1)[0]
+
for tf in type_filters:
- svc_prefix = tf.split(":")[0]
- if f"::{svc_prefix}:" in arn or f":{svc_prefix}:" in arn:
+ tf_parts = tf.split(":", 1)
+ svc_prefix = tf_parts[0]
+ if svc_prefix != arn_service:
+ continue
+ if len(tf_parts) == 1 or not tf_parts[1] or tf_parts[1] == arn_resource_type:
return True
return False
@@ -399,6 +417,39 @@ def _write_backup(arn, tags):
raise _ResourceNotFound(arn)
+def _resolve_elasticache_resource(svc, arn):
+ """Check that an ElastiCache ARN refers to an existing resource."""
+ resource_part = arn.split(":", 5)[-1] if arn.count(":") >= 5 else ""
+ if ":" not in resource_part:
+ raise _ResourceNotFound(arn)
+ resource_type, resource_id = resource_part.split(":", 1)
+ match resource_type:
+ case "cluster":
+ store = svc._clusters
+ case "replicationgroup":
+ store = svc._replication_groups
+ case "subnetgroup":
+ store = svc._subnet_groups
+ case "parametergroup":
+ store = svc._param_groups
+ case "snapshot":
+ store = svc._snapshots
+ case "user":
+ store = svc._users
+ case "usergroup":
+ store = svc._user_groups
+ case _:
+ raise _ResourceNotFound(arn)
+ if resource_id not in store:
+ raise _ResourceNotFound(arn)
+
+
+def _write_elasticache(arn, tags):
+ import ministack.services.elasticache as svc
+ _resolve_elasticache_resource(svc, arn)
+ svc._merge_tags_for_arn(arn, [{"Key": k, "Value": v} for k, v in tags.items()])
+
+
_WRITERS = {
"s3": _write_s3, "lambda": _write_lambda, "sqs": _write_sqs,
"sns": _write_sns, "dynamodb": _write_dynamodb, "events": _write_eventbridge,
@@ -407,6 +458,7 @@ _WRITERS = {
"cognito-identity": _write_cognito_identity, "appsync": _write_appsync,
"scheduler": _write_scheduler, "cloudfront": _write_cloudfront,
"elasticfilesystem": _write_efs, "backup": _write_backup,
+ "elasticache": _write_elasticache,
}
@@ -556,6 +608,12 @@ def _remove_backup(arn, keys):
tags.pop(k, None)
+def _remove_elasticache(arn, keys):
+ import ministack.services.elasticache as svc
+ _resolve_elasticache_resource(svc, arn)
+ svc._remove_tag_keys_for_arn(arn, keys)
+
+
_REMOVERS = {
"s3": _remove_s3, "lambda": _remove_lambda, "sqs": _remove_sqs,
"sns": _remove_sns, "dynamodb": _remove_dynamodb, "events": _remove_eventbridge,
@@ -564,6 +622,7 @@ _REMOVERS = {
"cognito-identity": _remove_cognito_identity, "appsync": _remove_appsync,
"scheduler": _remove_scheduler, "cloudfront": _remove_cloudfront,
"elasticfilesystem": _remove_efs, "backup": _remove_backup,
+ "elasticache": _remove_elasticache,
}
diff --git a/tests/test_elasticache.py b/tests/test_elasticache.py
index e17f0e96..bbf3763a 100644
--- a/tests/test_elasticache.py
+++ b/tests/test_elasticache.py
@@ -116,12 +116,13 @@ def test_elasticache_user_group_crud(ec):
@requires_docker
def test_elasticache_reset_clears_param_groups():
- """ElastiCache reset clears _param_group_params and resets port counter."""
+ """ElastiCache reset restores built-in parameter groups and resets port counter."""
from ministack.services import elasticache as _ec
_ec._param_group_params["test-group"] = {"param1": "val1"}
_ec._port_counter[0] = 99999
_ec.reset()
- assert not _ec._param_group_params
+ assert "test-group" not in _ec._param_group_params
+ assert "default.redis7" in _ec._param_group_params
assert _ec._port_counter[0] == _ec.BASE_PORT
@requires_docker
@@ -315,6 +316,59 @@ def test_elasticache_modify_cache_parameter_group(ec):
assert maxmem["ParameterValue"] == "allkeys-lru"
+def test_elasticache_default_parameter_groups_are_immutable(ec):
+ """Built-in default parameter groups cannot be overwritten, deleted, or modified."""
+ resp = ec.describe_cache_parameter_groups(CacheParameterGroupName="default.redis7")
+ assert resp["CacheParameterGroups"][0]["CacheParameterGroupFamily"] == "redis7"
+
+ with pytest.raises(ClientError) as exc:
+ ec.create_cache_parameter_group(
+ CacheParameterGroupName="default.redis7",
+ CacheParameterGroupFamily="redis7",
+ Description="duplicate default",
+ )
+ assert exc.value.response["Error"]["Code"] == "CacheParameterGroupAlreadyExists"
+
+ with pytest.raises(ClientError) as exc:
+ ec.delete_cache_parameter_group(CacheParameterGroupName="default.redis7")
+ assert exc.value.response["Error"]["Code"] == "InvalidCacheParameterGroupState"
+
+ with pytest.raises(ClientError) as exc:
+ ec.modify_cache_parameter_group(
+ CacheParameterGroupName="default.redis7",
+ ParameterNameValues=[{"ParameterName": "maxmemory-policy", "ParameterValue": "allkeys-lru"}],
+ )
+ assert exc.value.response["Error"]["Code"] == "InvalidCacheParameterGroupState"
+
+ with pytest.raises(ClientError) as exc:
+ ec.reset_cache_parameter_group(
+ CacheParameterGroupName="default.redis7",
+ ResetAllParameters=True,
+ )
+ assert exc.value.response["Error"]["Code"] == "InvalidCacheParameterGroupState"
+
+
+def test_elasticache_default_parameter_group_family_mapping(ec):
+ """Default parameter group names use AWS-style engine family names."""
+ cid = f"pg-map-mc-{_uid()}"
+ resp = ec.create_cache_cluster(
+ CacheClusterId=cid,
+ Engine="memcached",
+ EngineVersion="1.6.17",
+ CacheNodeType="cache.t3.micro",
+ NumCacheNodes=1,
+ )
+ group = resp["CacheCluster"]["CacheParameterGroup"]
+ assert group["CacheParameterGroupName"] == "default.memcached1.6"
+ ec.delete_cache_cluster(CacheClusterId=cid)
+
+ redis_versions = ec.describe_cache_engine_versions(Engine="redis")["CacheEngineVersions"]
+ families = {v["EngineVersion"]: v["CacheParameterGroupFamily"] for v in redis_versions}
+ assert families["7.0.12"] == "redis7"
+ assert families["6.2.14"] == "redis6.x"
+ assert families["5.0.6"] == "redis5.0"
+
+
def _uid():
return _uuid_mod.uuid4().hex[:8]
@@ -446,6 +500,51 @@ def test_modify_replication_group(ec):
ec.delete_replication_group(ReplicationGroupId=rg_id)
+def test_create_replication_group_missing_user_group_fails(ec):
+ """CreateReplicationGroup returns UserGroupNotFound for unknown UserGroupIds."""
+ rg_id = f"rg-missing-ug-{_uid()}"
+ with pytest.raises(ClientError) as exc:
+ ec.create_replication_group(
+ ReplicationGroupId=rg_id,
+ ReplicationGroupDescription="Missing user group",
+ CacheNodeType="cache.t3.micro",
+ UserGroupIds=["missing-user-group"],
+ )
+ err = exc.value.response["Error"]
+ assert err["Code"] == "UserGroupNotFound"
+ assert err["Message"] == "The user group was not found or does not exist"
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+ with pytest.raises(ClientError) as exc:
+ ec.describe_replication_groups(ReplicationGroupId=rg_id)
+ assert exc.value.response["Error"]["Code"] == "ReplicationGroupNotFoundFault"
+
+
+def test_modify_replication_group_missing_user_group_fails_before_mutation(ec):
+ """ModifyReplicationGroup validates user groups before applying other changes."""
+ rg_id = f"mod-rg-missing-ug-{_uid()}"
+ ec.create_replication_group(
+ ReplicationGroupId=rg_id,
+ ReplicationGroupDescription="Original desc",
+ CacheNodeType="cache.t3.micro",
+ )
+
+ with pytest.raises(ClientError) as exc:
+ ec.modify_replication_group(
+ ReplicationGroupId=rg_id,
+ ReplicationGroupDescription="Updated desc",
+ UserGroupIdsToAdd=["missing-user-group"],
+ )
+ err = exc.value.response["Error"]
+ assert err["Code"] == "UserGroupNotFound"
+ assert err["Message"] == "The user group was not found or does not exist"
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+ rg = ec.describe_replication_groups(ReplicationGroupId=rg_id)["ReplicationGroups"][0]
+ assert rg["Description"] == "Original desc"
+ ec.delete_replication_group(ReplicationGroupId=rg_id)
+
+
# ---------------------------------------------------------------------------
# 5. IncreaseReplicaCount
# ---------------------------------------------------------------------------
@@ -694,7 +793,117 @@ def test_describe_events_filter_source_id(ec):
# ---------------------------------------------------------------------------
-# 11. Serverless cache operations — not implemented in MiniStack
+# 11. Replication group member cluster lifecycle
+# ---------------------------------------------------------------------------
+
+def test_replication_group_creates_member_clusters(ec):
+ """CreateReplicationGroup should register member clusters visible via DescribeCacheClusters."""
+ rg_id = f"rg-members-{_uid()}"
+ ec.create_replication_group(
+ ReplicationGroupId=rg_id,
+ ReplicationGroupDescription="Member cluster test",
+ CacheNodeType="cache.t3.micro",
+ NumCacheClusters=2,
+ )
+ rg = ec.describe_replication_groups(ReplicationGroupId=rg_id)["ReplicationGroups"][0]
+ member_ids = rg["MemberClusters"]
+ assert len(member_ids) == 2
+
+ for cid in member_ids:
+ resp = ec.describe_cache_clusters(CacheClusterId=cid)
+ cluster = resp["CacheClusters"][0]
+ assert cluster["CacheClusterId"] == cid
+ assert cluster["ReplicationGroupId"] == rg_id
+
+ ec.delete_replication_group(ReplicationGroupId=rg_id)
+
+
+def test_delete_replication_group_removes_member_clusters(ec):
+ """DeleteReplicationGroup should also remove its member clusters."""
+ rg_id = f"rg-del-mem-{_uid()}"
+ ec.create_replication_group(
+ ReplicationGroupId=rg_id,
+ ReplicationGroupDescription="Delete members test",
+ CacheNodeType="cache.t3.micro",
+ NumCacheClusters=2,
+ )
+ member_ids = ec.describe_replication_groups(
+ ReplicationGroupId=rg_id
+ )["ReplicationGroups"][0]["MemberClusters"]
+
+ ec.delete_replication_group(ReplicationGroupId=rg_id)
+
+ for cid in member_ids:
+ with pytest.raises(ClientError) as exc:
+ ec.describe_cache_clusters(CacheClusterId=cid)
+ assert "CacheClusterNotFound" in str(exc.value)
+
+
+def test_replication_group_tags_on_create(ec):
+ """Tags passed at CreateReplicationGroup should be retrievable via ListTagsForResource."""
+ rg_id = f"rg-tags-{_uid()}"
+ ec.create_replication_group(
+ ReplicationGroupId=rg_id,
+ ReplicationGroupDescription="Tag on create",
+ CacheNodeType="cache.t3.micro",
+ Tags=[{"Key": "env", "Value": "test"}, {"Key": "team", "Value": "infra"}],
+ )
+ arn = ec.describe_replication_groups(
+ ReplicationGroupId=rg_id
+ )["ReplicationGroups"][0]["ARN"]
+
+ tags = ec.list_tags_for_resource(ResourceName=arn)
+ tag_map = {t["Key"]: t["Value"] for t in tags["TagList"]}
+ assert tag_map["env"] == "test"
+ assert tag_map["team"] == "infra"
+
+ ec.delete_replication_group(ReplicationGroupId=rg_id)
+
+
+def test_replication_group_cluster_mode_uses_cluster_on_default_group(ec):
+ """Cluster-mode-enabled replication groups use the .cluster.on default group."""
+ rg_id = f"rg-cluster-pg-{_uid()}"
+ ec.create_replication_group(
+ ReplicationGroupId=rg_id,
+ ReplicationGroupDescription="Cluster default parameter group",
+ CacheNodeType="cache.t3.micro",
+ NumNodeGroups=3,
+ ReplicasPerNodeGroup=0,
+ )
+ rg = ec.describe_replication_groups(ReplicationGroupId=rg_id)["ReplicationGroups"][0]
+ member_id = rg["MemberClusters"][0]
+ cluster = ec.describe_cache_clusters(CacheClusterId=member_id)["CacheClusters"][0]
+ assert cluster["CacheParameterGroup"]["CacheParameterGroupName"] == "default.redis7.cluster.on"
+ ec.delete_replication_group(ReplicationGroupId=rg_id)
+
+
+def test_replication_group_tag_updates_propagate_to_member_clusters(ec):
+ """AddTagsToResource/RemoveTagsFromResource on a replication group fan out to members."""
+ rg_id = f"rg-tag-fanout-{_uid()}"
+ ec.create_replication_group(
+ ReplicationGroupId=rg_id,
+ ReplicationGroupDescription="Tag fanout",
+ CacheNodeType="cache.t3.micro",
+ NumCacheClusters=2,
+ )
+ rg = ec.describe_replication_groups(ReplicationGroupId=rg_id)["ReplicationGroups"][0]
+ rg_arn = rg["ARN"]
+ member_id = rg["MemberClusters"][0]
+ member = ec.describe_cache_clusters(CacheClusterId=member_id)["CacheClusters"][0]
+ member_arn = member["ARN"]
+
+ ec.add_tags_to_resource(ResourceName=rg_arn, Tags=[{"Key": "env", "Value": "test"}])
+ member_tags = ec.list_tags_for_resource(ResourceName=member_arn)["TagList"]
+ assert {t["Key"]: t["Value"] for t in member_tags}["env"] == "test"
+
+ ec.remove_tags_from_resource(ResourceName=rg_arn, TagKeys=["env"])
+ member_tags = ec.list_tags_for_resource(ResourceName=member_arn)["TagList"]
+ assert not any(t["Key"] == "env" for t in member_tags)
+ ec.delete_replication_group(ReplicationGroupId=rg_id)
+
+
+# ---------------------------------------------------------------------------
+# 12. Serverless cache operations — not implemented in MiniStack
# ---------------------------------------------------------------------------
@requires_docker
diff --git a/tests/test_tagging.py b/tests/test_tagging.py
index eab338f6..924cf5b5 100644
--- a/tests/test_tagging.py
+++ b/tests/test_tagging.py
@@ -1,4 +1,5 @@
import os
+import uuid as _uuid_mod
import pytest
from botocore.exceptions import ClientError
@@ -9,6 +10,10 @@ from botocore.exceptions import ClientError
_TAG_KEY = "tagging-test"
+def _uid():
+ return _uuid_mod.uuid4().hex[:8]
+
+
# ========== S3 ==========
def test_tagging_get_resources_s3_basic(tagging, s3):
@@ -701,6 +706,152 @@ def test_tagging_tag_resources_cross_account_isolation(s3):
assert arn_a in arns_a
+# ========== ElastiCache ==========
+
+def test_tagging_get_resources_elasticache_tagged(tagging, ec):
+ """GetResources returns ElastiCache resources that have been tagged."""
+ ec.create_cache_cluster(
+ CacheClusterId="tg-ec-tagged",
+ Engine="redis",
+ CacheNodeType="cache.t3.micro",
+ NumCacheNodes=1,
+ )
+ arn = "arn:aws:elasticache:us-east-1:000000000000:cluster:tg-ec-tagged"
+ ec.add_tags_to_resource(
+ ResourceName=arn,
+ Tags=[{"Key": _TAG_KEY, "Value": "ec-tagged"}],
+ )
+
+ resp = tagging.get_resources(TagFilters=[{"Key": _TAG_KEY, "Values": ["ec-tagged"]}])
+ arns = [r["ResourceARN"] for r in resp["ResourceTagMappingList"]]
+ assert arn in arns
+
+
+def test_tagging_get_resources_elasticache_untagged(tagging, ec):
+ """GetResources with ResourceTypeFilters returns untagged ElastiCache resources."""
+ ec.create_cache_cluster(
+ CacheClusterId="tg-ec-untagged",
+ Engine="redis",
+ CacheNodeType="cache.t3.micro",
+ NumCacheNodes=1,
+ )
+ arn = "arn:aws:elasticache:us-east-1:000000000000:cluster:tg-ec-untagged"
+
+ resp = tagging.get_resources(ResourceTypeFilters=["elasticache"])
+ arns = [r["ResourceARN"] for r in resp["ResourceTagMappingList"]]
+ assert arn in arns
+
+
+def test_tagging_get_resources_elasticache_type_filter(tagging, ec, s3):
+ """ResourceTypeFilters=["elasticache"] excludes non-elasticache resources."""
+ ec.create_cache_cluster(
+ CacheClusterId="tg-ec-filter",
+ Engine="redis",
+ CacheNodeType="cache.t3.micro",
+ NumCacheNodes=1,
+ )
+ ec_arn = "arn:aws:elasticache:us-east-1:000000000000:cluster:tg-ec-filter"
+ ec.add_tags_to_resource(
+ ResourceName=ec_arn,
+ Tags=[{"Key": _TAG_KEY, "Value": "ec-filter"}],
+ )
+ s3.create_bucket(Bucket="tg-ec-filter-s3")
+ s3.put_bucket_tagging(Bucket="tg-ec-filter-s3", Tagging={
+ "TagSet": [{"Key": _TAG_KEY, "Value": "ec-filter"}]
+ })
+
+ resp = tagging.get_resources(
+ TagFilters=[{"Key": _TAG_KEY, "Values": ["ec-filter"]}],
+ ResourceTypeFilters=["elasticache"],
+ )
+ arns = [r["ResourceARN"] for r in resp["ResourceTagMappingList"]]
+ assert ec_arn in arns
+ assert "arn:aws:s3:::tg-ec-filter-s3" not in arns
+
+
+def test_tagging_tag_resources_elasticache(tagging, ec):
+ """TagResources on a valid ElastiCache ARN succeeds."""
+ ec.create_cache_cluster(
+ CacheClusterId="tg-ec-tr",
+ Engine="redis",
+ CacheNodeType="cache.t3.micro",
+ NumCacheNodes=1,
+ )
+ arn = "arn:aws:elasticache:us-east-1:000000000000:cluster:tg-ec-tr"
+ resp = tagging.tag_resources(ResourceARNList=[arn], Tags={_TAG_KEY: "ec-tr"})
+ assert resp["FailedResourcesMap"] == {}
+
+ check = tagging.get_resources(TagFilters=[{"Key": _TAG_KEY, "Values": ["ec-tr"]}])
+ assert any(r["ResourceARN"] == arn for r in check["ResourceTagMappingList"])
+
+
+def test_tagging_tag_resources_elasticache_replication_group_propagates_to_members(tagging, ec):
+ """TagResources/UntagResources on a replication group fan out to member clusters."""
+ rg_id = f"tg-ec-rg-{_uid()}"
+ ec.create_replication_group(
+ ReplicationGroupId=rg_id,
+ ReplicationGroupDescription="Tagging API fanout",
+ CacheNodeType="cache.t3.micro",
+ NumCacheClusters=2,
+ )
+ rg = ec.describe_replication_groups(ReplicationGroupId=rg_id)["ReplicationGroups"][0]
+ rg_arn = rg["ARN"]
+ member_id = rg["MemberClusters"][0]
+ member = ec.describe_cache_clusters(CacheClusterId=member_id)["CacheClusters"][0]
+ member_arn = member["ARN"]
+
+ resp = tagging.tag_resources(ResourceARNList=[rg_arn], Tags={_TAG_KEY: "ec-rg-tr"})
+ assert resp["FailedResourcesMap"] == {}
+ member_tags = ec.list_tags_for_resource(ResourceName=member_arn)["TagList"]
+ assert {t["Key"]: t["Value"] for t in member_tags}[_TAG_KEY] == "ec-rg-tr"
+
+ resp = tagging.untag_resources(ResourceARNList=[rg_arn], TagKeys=[_TAG_KEY])
+ assert resp["FailedResourcesMap"] == {}
+ member_tags = ec.list_tags_for_resource(ResourceName=member_arn)["TagList"]
+ assert not any(t["Key"] == _TAG_KEY for t in member_tags)
+
+ ec.delete_replication_group(ReplicationGroupId=rg_id)
+
+
+def test_tagging_tag_resources_elasticache_nonexistent(tagging):
+ """TagResources on a non-existent ElastiCache ARN returns InvalidParameterException."""
+ arn = "arn:aws:elasticache:us-east-1:000000000000:cluster:no-such-cluster"
+ resp = tagging.tag_resources(ResourceARNList=[arn], Tags={_TAG_KEY: "fail"})
+ assert arn in resp["FailedResourcesMap"]
+ entry = resp["FailedResourcesMap"][arn]
+ assert entry["ErrorCode"] == "InvalidParameterException"
+ assert entry["StatusCode"] == 400
+
+
+def test_tagging_untag_resources_elasticache_nonexistent(tagging):
+ """UntagResources on a non-existent ElastiCache ARN returns InvalidParameterException."""
+ arn = "arn:aws:elasticache:us-east-1:000000000000:replicationgroup:no-such-rg"
+ resp = tagging.untag_resources(ResourceARNList=[arn], TagKeys=[_TAG_KEY])
+ assert arn in resp["FailedResourcesMap"]
+ entry = resp["FailedResourcesMap"][arn]
+ assert entry["ErrorCode"] == "InvalidParameterException"
+ assert entry["StatusCode"] == 400
+
+
+def test_tagging_untag_resources_elasticache(tagging, ec):
+ """UntagResources removes tags from a valid ElastiCache resource."""
+ ec.create_cache_cluster(
+ CacheClusterId="tg-ec-utr",
+ Engine="redis",
+ CacheNodeType="cache.t3.micro",
+ NumCacheNodes=1,
+ )
+ arn = "arn:aws:elasticache:us-east-1:000000000000:cluster:tg-ec-utr"
+ tagging.tag_resources(ResourceARNList=[arn], Tags={_TAG_KEY: "ec-utr"})
+ resp = tagging.untag_resources(ResourceARNList=[arn], TagKeys=[_TAG_KEY])
+ assert resp["FailedResourcesMap"] == {}
+
+ check = tagging.get_resources(TagFilters=[{"Key": _TAG_KEY, "Values": ["ec-utr"]}])
+ assert not any(r["ResourceARN"] == arn for r in check["ResourceTagMappingList"])
+
+
+# ========== Module reset ==========
+
def test_tagging_module_exposes_no_op_reset():
"""Tag dispatcher is stateless (delegates to per-service tag stores), but
must expose `reset()` so the central `/_ministack/reset` doesn't log a