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
Scope ElastiCache state by region (#1071)
Ian Oberst44638282070a
diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.pyindex 1e0b0cf4..ad8b5937 100644--- a/ministack/services/elasticache.py+++ b/ministack/services/elasticache.py@@ -28,7 +28,14 @@ from urllib.parse import parse_qsfrom ministack.core.arn import ArnParseError, parse_arnfrom ministack.core.persistence import load_state-from ministack.core.responses import AccountScopedDict, apply_image_prefix, get_account_id, get_region, new_uuid+from ministack.core.responses import (+ AccountRegionScopedDict,+ AccountScopedDict,+ apply_image_prefix,+ get_account_id,+ get_region,+ new_uuid,+)logger = logging.getLogger("elasticache")@@ -70,18 +77,18 @@ _DEFAULT_PARAM_GROUP_FAMILIES = []_DEFAULT_PARAM_GROUP_NAMES = {name for name, _family, _desc in _DEFAULT_PARAM_GROUP_FAMILIES}-_clusters = AccountScopedDict()-_replication_groups = AccountScopedDict()-_subnet_groups = AccountScopedDict()-_param_groups = AccountScopedDict()-_param_group_params = AccountScopedDict() # group_name -> {param_name -> param_dict}+_clusters = AccountRegionScopedDict()+_replication_groups = AccountRegionScopedDict()+_subnet_groups = AccountRegionScopedDict()+_param_groups = AccountRegionScopedDict()+_param_group_params = AccountRegionScopedDict() # group_name -> {param_name -> param_dict}_tags = AccountScopedDict() # arn -> [{"Key": ..., "Value": ...}, ...]-_snapshots = AccountScopedDict()-_users = AccountScopedDict()-_user_groups = AccountScopedDict()-# Per-account event log. AccountScopedDict under key "entries" so the list-# manipulation stays simple and DescribeEvents never leaks cross-tenant rows.-_events = AccountScopedDict()+_snapshots = AccountRegionScopedDict()+_users = AccountRegionScopedDict()+_user_groups = 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()def _events_list() -> list:@@ -100,11 +107,11 @@ _docker = None# ── Persistence ────────────────────────────────────────────def get_state():- rgs = {}- for name, rg in _replication_groups.items():+ rgs = AccountRegionScopedDict()+ for (account_id, region, name), rg in _replication_groups.all_items():r = copy.deepcopy(rg)r.pop("_docker_container_ids", None)- rgs[name] = r+ rgs.set_scoped(account_id, region, name, r)state = {"replication_groups": rgs,"subnet_groups": copy.deepcopy(_subnet_groups),@@ -114,13 +121,14 @@ def get_state():"snapshots": copy.deepcopy(_snapshots),"users": copy.deepcopy(_users),"user_groups": copy.deepcopy(_user_groups),+ "events": copy.deepcopy(_events),"port_counter": _port_counter[0],}- clusters = {}- for name, cl in _clusters.items():+ clusters = AccountRegionScopedDict()+ for (account_id, region, name), cl in _clusters.all_items():c = copy.deepcopy(cl)c.pop("_docker_container_id", None)- clusters[name] = c+ clusters.set_scoped(account_id, region, name, c)state["clusters"] = clustersreturn state@@ -142,30 +150,77 @@ import threading as _threading_respawn_lock = _threading.Lock()+def _as_region_scoped(incoming):+ scoped = AccountRegionScopedDict()+ scoped.update({} if incoming is None else incoming)+ return scoped+++def _restore_replication_groups(incoming):+ restored = _as_region_scoped(incoming)+ for (account_id, region, name), rg in restored.all_items():+ # Wipe stale container ids — the old Docker containers are dead.+ # _ensure_live_containers will refill this list lazily.+ record = copy.deepcopy(rg)+ record["_docker_container_ids"] = []+ _replication_groups.set_scoped(account_id, region, name, record)+ _pending_rg_respawn.add((account_id, region, name))+++def _param_group_region(account_id, group_name):+ for (pg_account_id, pg_region, pg_name), _pg in _param_groups.all_items():+ if pg_account_id == account_id and pg_name == group_name:+ return pg_region+ return get_region()+++def _restore_param_group_params(incoming):+ if isinstance(incoming, AccountRegionScopedDict):+ _param_group_params.update(incoming)+ return++ if isinstance(incoming, AccountScopedDict):+ items = [+ (account_id, group_name, params)+ for (account_id, group_name), params in incoming._data.items()+ ]+ else:+ items = [+ (get_account_id(), group_name, params)+ for group_name, params in (incoming or {}).items()+ ]++ for account_id, group_name, params in items:+ region = _param_group_region(account_id, group_name)+ _param_group_params.set_scoped(account_id, region, group_name, params)+++def _restore_clusters(incoming):+ restored = _as_region_scoped(incoming)+ for (account_id, region, name), cl in restored.all_items():+ record = copy.deepcopy(cl)+ record["_docker_container_id"] = None+ record["CacheClusterStatus"] = "available"+ _clusters.set_scoped(account_id, region, name, record)+ _pending_cluster_respawn.add((account_id, region, name))++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.- # _ensure_live_containers will refill this list lazily.- rg["_docker_container_ids"] = []- _replication_groups[name] = rg- _pending_rg_respawn.add(name)+ _restore_replication_groups(data.get("replication_groups", {}))_subnet_groups.update(data.get("subnet_groups", {}))_param_groups.update(data.get("param_groups", {}))- _param_group_params.update(data.get("param_group_params", {}))+ _restore_param_group_params(data.get("param_group_params", {}))_tags.update(data.get("tags", {}))_snapshots.update(data.get("snapshots", {}))_users.update(data.get("users", {}))_user_groups.update(data.get("user_groups", {}))+ _events.update(data.get("events", {}))if "port_counter" in data:_port_counter[0] = data["port_counter"]- for name, cl in data.get("clusters", {}).items():- cl["_docker_container_id"] = None- cl["CacheClusterStatus"] = "available"- _clusters[name] = cl- _pending_cluster_respawn.add(name)+ _restore_clusters(data.get("clusters", {}))default_state()@@ -189,18 +244,24 @@ def _ensure_live_containers():def _ensure_live_containers_locked():import logginglog = logging.getLogger(__name__)- for name in list(_pending_cluster_respawn):- _pending_cluster_respawn.discard(name)- cl = _clusters.get(name)+ for pending in list(_pending_cluster_respawn):+ account_id, region, name = pending+ _pending_cluster_respawn.discard(pending)+ cl = _clusters.get_scoped(account_id, region, name)if cl is None:continuetry:engine = cl.get("Engine", "redis")version = cl.get("EngineVersion", "7.1")host, port, cid = _spawn_redis_container(- name=f"ministack-elasticache-{name}",+ name=f"ministack-elasticache-{account_id}-{region}-{name}",engine=engine, engine_version=version,- labels={"ministack": "elasticache", "cluster_id": name},+ labels={+ "ministack": "elasticache",+ "cluster_id": name,+ "account_id": account_id,+ "region": region,+ },)cl["_docker_container_id"] = cidfor node in cl.get("CacheNodes") or []:@@ -212,24 +273,25 @@ def _ensure_live_containers_locked():log.warning("elasticache: failed to respawn container for cluster %s on restart; ""endpoint will be unreachable", name, exc_info=True)- for rg_id in list(_pending_rg_respawn):- _pending_rg_respawn.discard(rg_id)- rg = _replication_groups.get(rg_id)+ for pending in list(_pending_rg_respawn):+ account_id, region, rg_id = pending+ _pending_rg_respawn.discard(pending)+ rg = _replication_groups.get_scoped(account_id, region, rg_id)if rg is None:continuetry:engine = rg.get("Engine", "redis")engine_version = rg.get("EngineVersion") or rg.get("CacheNodeType") or "7.1"- account_id = get_account_id()node_groups = rg.get("NodeGroups") or []for ng in node_groups:ng_id = ng.get("NodeGroupId", "0001")_, _, cid = _spawn_redis_container(- name=f"ministack-elasticache-rg-{account_id}-{rg_id}-{ng_id}",+ name=f"ministack-elasticache-rg-{account_id}-{region}-{rg_id}-{ng_id}",engine=engine, engine_version=engine_version,labels={"ministack": "elasticache", "rg_id": rg_id,"node_group": ng_id, "account_id": account_id,+ "region": region,},)if cid:@@ -542,6 +604,7 @@ def _build_real_cluster_rg(rg_id, engine_version, num_node_groups, replicas_per_"""docker_client = _get_docker()account_id = get_account_id()+ region = get_region()primaries = [] # list of {ng_id, ip, port, cid}replicas = [] # list of {ng_id, replica_idx, ip, port, cid}container_ids = []@@ -550,12 +613,13 @@ def _build_real_cluster_rg(rg_id, engine_version, num_node_groups, replicas_per_"ministack": "elasticache","rg_id": rg_id,"account_id": account_id,+ "region": region,}# Primary nodes firstfor ng_idx in range(1, num_node_groups + 1):ng_id = f"{ng_idx:04d}"- name = f"ministack-elasticache-rg-{account_id}-{rg_id}-{ng_id}-p"+ name = f"ministack-elasticache-rg-{account_id}-{region}-{rg_id}-{ng_id}-p"ip, port, cid = _spawn_redis_cluster_node(name=name,engine_version=engine_version,@@ -570,7 +634,7 @@ def _build_real_cluster_rg(rg_id, engine_version, num_node_groups, replicas_per_for ng_idx in range(1, num_node_groups + 1):ng_id = f"{ng_idx:04d}"for r in range(1, replicas_per_shard + 1):- name = f"ministack-elasticache-rg-{account_id}-{rg_id}-{ng_id}-r{r}"+ name = f"ministack-elasticache-rg-{account_id}-{region}-{rg_id}-{ng_id}-r{r}"ip, port, cid = _spawn_redis_cluster_node(name=name,engine_version=engine_version,@@ -737,6 +801,7 @@ async def handle_request(method, path, headers, body, query_params):# Lazy-respawn any clusters / replication groups that were restored# from disk (issue #853). Cheap fast-path when nothing's pending._ensure_live_containers()+ _seed_default_param_groups()params = dict(query_params)if method == "POST" and body:form_params = parse_qs(body.decode("utf-8", errors="replace"))@@ -804,11 +869,18 @@ def _create_cache_cluster(p):return _error("CacheClusterAlreadyExists", f"Cluster {cluster_id} already exists", 400)arn = _arn_cluster(cluster_id)+ account_id = get_account_id()+ region = get_region()endpoint_host, endpoint_port, docker_container_id = _spawn_redis_container(- name=f"ministack-elasticache-{cluster_id}",+ name=f"ministack-elasticache-{account_id}-{region}-{cluster_id}",engine=engine,engine_version=engine_version,- labels={"ministack": "elasticache", "cluster_id": cluster_id},+ labels={+ "ministack": "elasticache",+ "cluster_id": cluster_id,+ "account_id": account_id,+ "region": region,+ },)subnet_group = _p(p, "CacheSubnetGroupName") or "default"@@ -1015,10 +1087,11 @@ def _create_replication_group(p):if not node_groups:# Path (b) or (c): per-shard fan-out / fallback.account_id = get_account_id()+ region = get_region()for ng_idx in range(1, num_node_groups + 1):ng_id = f"{ng_idx:04d}"shard_host, shard_port, cid = _spawn_redis_container(- name=f"ministack-elasticache-rg-{account_id}-{rg_id}-{ng_id}",+ name=f"ministack-elasticache-rg-{account_id}-{region}-{rg_id}-{ng_id}",engine=engine,engine_version=engine_version,labels={@@ -1026,6 +1099,7 @@ def _create_replication_group(p):"rg_id": rg_id,"node_group": ng_id,"account_id": account_id,+ "region": region,},)if cid:@@ -2294,7 +2368,7 @@ def _error(code, message, status):def reset():docker_client = _get_docker()if docker_client:- for cluster in _clusters.values():+ for cluster in _clusters.all_values():cid = cluster.get("_docker_container_id")if cid:try:@@ -2303,7 +2377,7 @@ def reset():c.remove(v=True)except Exception as e:logger.warning("reset: failed to stop/remove container %s: %s", cid, e)- for rg in _replication_groups.values():+ for rg in _replication_groups.all_values():for cid in rg.get("_docker_container_ids") or []:try:c = docker_client.containers.get(cid)@@ -2321,5 +2395,7 @@ def reset():_user_groups.clear()_events.clear()_tags.clear() # was missing from reset() — HIGH-severity gap from audit+ _pending_cluster_respawn.clear()+ _pending_rg_respawn.clear()_port_counter[0] = BASE_PORTdefault_state()diff --git a/tests/test_elasticache.py b/tests/test_elasticache.pyindex 6ec93798..4499e2bf 100644--- a/tests/test_elasticache.py+++ b/tests/test_elasticache.py@@ -6,7 +6,9 @@ import uuid as _uuid_modimport zipfilefrom urllib.parse import urlparse+import boto3import pytest+from botocore.config import Configfrom botocore.exceptions import ClientErrorENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")@@ -20,6 +22,17 @@ requires_docker = pytest.mark.skipif(reason="DOCKER_NETWORK not set - skipping network connectivity test",)++def _ec_client(region):+ return boto3.client(+ "elasticache",+ endpoint_url=ENDPOINT,+ aws_access_key_id="test",+ aws_secret_access_key="test",+ region_name=region,+ config=Config(region_name=region, retries={"mode": "standard"}),+ )+@requires_dockerdef test_elasticache_create(ec):ec.create_cache_cluster(@@ -420,6 +433,372 @@ def _uid():return _uuid_mod.uuid4().hex[:8]+def test_elasticache_clusters_are_region_scoped_by_name():+ east = _ec_client("us-east-1")+ west = _ec_client("us-west-2")+ cid = f"scope-cluster-{_uid()}"++ east.create_cache_cluster(+ CacheClusterId=cid,+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,+ )+ west.create_cache_cluster(+ CacheClusterId=cid,+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,+ )++ try:+ east_cluster = east.describe_cache_clusters(CacheClusterId=cid)["CacheClusters"][0]+ west_cluster = west.describe_cache_clusters(CacheClusterId=cid)["CacheClusters"][0]++ assert east_cluster["ARN"] == f"arn:aws:elasticache:us-east-1:000000000000:cluster:{cid}"+ assert west_cluster["ARN"] == f"arn:aws:elasticache:us-west-2:000000000000:cluster:{cid}"+ assert east_cluster["PreferredAvailabilityZone"].startswith("us-east-1")+ assert west_cluster["PreferredAvailabilityZone"].startswith("us-west-2")++ west.delete_cache_cluster(CacheClusterId=cid)+ with pytest.raises(ClientError) as exc:+ west.describe_cache_clusters(CacheClusterId=cid)+ assert exc.value.response["Error"]["Code"] == "CacheClusterNotFound"+ assert east.describe_cache_clusters(CacheClusterId=cid)["CacheClusters"][0]["ARN"] == east_cluster["ARN"]+ finally:+ for client in (east, west):+ try:+ client.delete_cache_cluster(CacheClusterId=cid)+ except ClientError:+ pass+++def test_elasticache_replication_groups_are_region_scoped():+ east = _ec_client("us-east-1")+ west = _ec_client("us-west-2")+ rg_id = f"scope-rg-{_uid()}"++ east.create_replication_group(+ ReplicationGroupId=rg_id,+ ReplicationGroupDescription="east rg",+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ )+ west.create_replication_group(+ ReplicationGroupId=rg_id,+ ReplicationGroupDescription="west rg",+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ )++ try:+ east_rg = east.describe_replication_groups(ReplicationGroupId=rg_id)["ReplicationGroups"][0]+ west_rg = west.describe_replication_groups(ReplicationGroupId=rg_id)["ReplicationGroups"][0]++ assert east_rg["ARN"] == f"arn:aws:elasticache:us-east-1:000000000000:replicationgroup:{rg_id}"+ assert west_rg["ARN"] == f"arn:aws:elasticache:us-west-2:000000000000:replicationgroup:{rg_id}"+ assert east_rg["Description"] == "east rg"+ assert west_rg["Description"] == "west rg"++ east.delete_replication_group(ReplicationGroupId=rg_id)+ with pytest.raises(ClientError) as exc:+ east.describe_replication_groups(ReplicationGroupId=rg_id)+ assert exc.value.response["Error"]["Code"] == "ReplicationGroupNotFoundFault"+ assert west.describe_replication_groups(ReplicationGroupId=rg_id)["ReplicationGroups"][0]["ARN"] == west_rg["ARN"]+ finally:+ for client in (east, west):+ try:+ client.delete_replication_group(ReplicationGroupId=rg_id)+ except ClientError:+ pass+++def test_elasticache_users_and_user_groups_are_region_scoped():+ east = _ec_client("us-east-1")+ west = _ec_client("us-west-2")+ user_id = f"scope-user-{_uid()}"+ group_id = f"scope-group-{_uid()}"++ for client in (east, west):+ client.create_user(+ UserId=user_id,+ UserName=user_id,+ Engine="redis",+ AccessString="on ~* +@all",+ NoPasswordRequired=True,+ )+ client.create_user_group(UserGroupId=group_id, Engine="redis", UserIds=[user_id])++ try:+ east_user = east.describe_users(UserId=user_id)["Users"][0]+ west_user = west.describe_users(UserId=user_id)["Users"][0]+ east_group = east.describe_user_groups(UserGroupId=group_id)["UserGroups"][0]+ west_group = west.describe_user_groups(UserGroupId=group_id)["UserGroups"][0]++ assert east_user["ARN"] == f"arn:aws:elasticache:us-east-1:000000000000:user:{user_id}"+ assert west_user["ARN"] == f"arn:aws:elasticache:us-west-2:000000000000:user:{user_id}"+ assert east_group["ARN"] == f"arn:aws:elasticache:us-east-1:000000000000:usergroup:{group_id}"+ assert west_group["ARN"] == f"arn:aws:elasticache:us-west-2:000000000000:usergroup:{group_id}"++ east.delete_user_group(UserGroupId=group_id)+ east.delete_user(UserId=user_id)+ with pytest.raises(ClientError) as exc:+ east.describe_users(UserId=user_id)+ assert exc.value.response["Error"]["Code"] == "UserNotFound"+ assert west.describe_users(UserId=user_id)["Users"][0]["ARN"] == west_user["ARN"]+ finally:+ for client in (east, west):+ try:+ client.delete_user_group(UserGroupId=group_id)+ except ClientError:+ pass+ try:+ client.delete_user(UserId=user_id)+ except ClientError:+ pass+++def test_elasticache_subnet_and_param_groups_are_region_scoped():+ east = _ec_client("us-east-1")+ west = _ec_client("us-west-2")+ subnet_name = f"scope-subnet-{_uid()}"+ param_name = f"scope-param-{_uid()}"++ east.create_cache_subnet_group(+ CacheSubnetGroupName=subnet_name,+ CacheSubnetGroupDescription="east subnet",+ SubnetIds=["subnet-east"],+ )+ west.create_cache_subnet_group(+ CacheSubnetGroupName=subnet_name,+ CacheSubnetGroupDescription="west subnet",+ SubnetIds=["subnet-west"],+ )+ east.create_cache_parameter_group(+ CacheParameterGroupName=param_name,+ CacheParameterGroupFamily="redis7",+ Description="east param",+ )+ west.create_cache_parameter_group(+ CacheParameterGroupName=param_name,+ CacheParameterGroupFamily="redis7",+ Description="west param",+ )++ try:+ east_subnet = east.describe_cache_subnet_groups(CacheSubnetGroupName=subnet_name)["CacheSubnetGroups"][0]+ west_subnet = west.describe_cache_subnet_groups(CacheSubnetGroupName=subnet_name)["CacheSubnetGroups"][0]+ east_param = east.describe_cache_parameter_groups(CacheParameterGroupName=param_name)["CacheParameterGroups"][0]+ west_param = west.describe_cache_parameter_groups(CacheParameterGroupName=param_name)["CacheParameterGroups"][0]++ assert east_subnet["ARN"] == f"arn:aws:elasticache:us-east-1:000000000000:subnetgroup:{subnet_name}"+ assert west_subnet["ARN"] == f"arn:aws:elasticache:us-west-2:000000000000:subnetgroup:{subnet_name}"+ assert east_param["ARN"] == f"arn:aws:elasticache:us-east-1:000000000000:parametergroup:{param_name}"+ assert west_param["ARN"] == f"arn:aws:elasticache:us-west-2:000000000000:parametergroup:{param_name}"++ west.delete_cache_subnet_group(CacheSubnetGroupName=subnet_name)+ west.delete_cache_parameter_group(CacheParameterGroupName=param_name)+ with pytest.raises(ClientError) as exc:+ west.describe_cache_subnet_groups(CacheSubnetGroupName=subnet_name)+ assert exc.value.response["Error"]["Code"] == "CacheSubnetGroupNotFoundFault"+ with pytest.raises(ClientError) as exc:+ west.describe_cache_parameter_groups(CacheParameterGroupName=param_name)+ assert exc.value.response["Error"]["Code"] == "CacheParameterGroupNotFound"+ assert east.describe_cache_subnet_groups(CacheSubnetGroupName=subnet_name)["CacheSubnetGroups"][0]["ARN"] == east_subnet["ARN"]+ assert east.describe_cache_parameter_groups(CacheParameterGroupName=param_name)["CacheParameterGroups"][0]["ARN"] == east_param["ARN"]+ finally:+ for client in (east, west):+ try:+ client.delete_cache_subnet_group(CacheSubnetGroupName=subnet_name)+ except ClientError:+ pass+ try:+ client.delete_cache_parameter_group(CacheParameterGroupName=param_name)+ except ClientError:+ pass+++def test_elasticache_default_param_groups_seed_per_region():+ east = _ec_client("us-east-1")+ west = _ec_client("us-west-2")++ east_group = east.describe_cache_parameter_groups(+ CacheParameterGroupName="default.redis7",+ )["CacheParameterGroups"][0]+ west_group = west.describe_cache_parameter_groups(+ CacheParameterGroupName="default.redis7",+ )["CacheParameterGroups"][0]++ assert east_group["ARN"] == "arn:aws:elasticache:us-east-1:000000000000:parametergroup:default.redis7"+ assert west_group["ARN"] == "arn:aws:elasticache:us-west-2:000000000000:parametergroup:default.redis7"+++def test_elasticache_tags_stay_arn_keyed_and_request_region_validated():+ east = _ec_client("us-east-1")+ west = _ec_client("us-west-2")+ name = f"tag-scope-{_uid()}"++ east.create_cache_parameter_group(+ CacheParameterGroupName=name,+ CacheParameterGroupFamily="redis7",+ Description="tag scope",+ )+ arn = f"arn:aws:elasticache:us-east-1:000000000000:parametergroup:{name}"+ try:+ east.add_tags_to_resource(ResourceName=arn, Tags=[{"Key": "env", "Value": "east"}])+ assert east.list_tags_for_resource(ResourceName=arn)["TagList"] == [+ {"Key": "env", "Value": "east"},+ ]++ with pytest.raises(ClientError) as exc:+ west.list_tags_for_resource(ResourceName=arn)+ assert exc.value.response["Error"]["Code"] == "InvalidParameterValue"+ finally:+ try:+ east.delete_cache_parameter_group(CacheParameterGroupName=name)+ except ClientError:+ pass+++def test_elasticache_events_are_region_scoped():+ east = _ec_client("us-east-1")+ west = _ec_client("us-west-2")+ cid = f"event-scope-{_uid()}"++ east.create_cache_cluster(+ CacheClusterId=cid,+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,+ )+ west.create_cache_cluster(+ CacheClusterId=cid,+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,+ )++ try:+ east_events = east.describe_events(SourceIdentifier=cid)["Events"]+ west_events = west.describe_events(SourceIdentifier=cid)["Events"]++ assert len(east_events) == 1+ assert len(west_events) == 1+ assert east_events[0]["Message"] == "Cache cluster created"+ assert west_events[0]["Message"] == "Cache cluster created"++ east.delete_cache_cluster(CacheClusterId=cid)+ east_events = east.describe_events(SourceIdentifier=cid)["Events"]+ west_events = west.describe_events(SourceIdentifier=cid)["Events"]+ assert [e["Message"] for e in east_events] == [+ "Cache cluster created",+ "Cache cluster deleted",+ ]+ assert [e["Message"] for e in west_events] == ["Cache cluster created"]+ finally:+ for client in (east, west):+ try:+ client.delete_cache_cluster(CacheClusterId=cid)+ except ClientError:+ pass+++def test_elasticache_restore_legacy_account_scoped_state_adopts_record_arn_region():+ from ministack.core.responses import (+ AccountScopedDict,+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,+ )+ from ministack.services import elasticache as _ec++ original_account = get_account_id()+ original_region = get_region()+ account_id = "000000000000"+ region = "us-west-2"+ name = f"legacy-{_uid()}"++ legacy_clusters = AccountScopedDict()+ legacy_clusters._data[(account_id, name)] = {+ "CacheClusterId": name,+ "CacheClusterArn": f"arn:aws:elasticache:{region}:{account_id}:cluster:{name}",+ "CacheClusterStatus": "available",+ "Engine": "redis",+ "EngineVersion": "7.1",+ "CacheNodes": [],+ }+ legacy_rgs = AccountScopedDict()+ legacy_rgs._data[(account_id, name)] = {+ "ReplicationGroupId": name,+ "ARN": f"arn:aws:elasticache:{region}:{account_id}:replicationgroup:{name}",+ "Status": "available",+ "Engine": "redis",+ "NodeGroups": [],+ }+ legacy_subnets = AccountScopedDict()+ legacy_subnets._data[(account_id, name)] = {+ "CacheSubnetGroupName": name,+ "ARN": f"arn:aws:elasticache:{region}:{account_id}:subnetgroup:{name}",+ }+ legacy_params = AccountScopedDict()+ legacy_params._data[(account_id, name)] = {+ "CacheParameterGroupName": name,+ "CacheParameterGroupFamily": "redis7",+ "ARN": f"arn:aws:elasticache:{region}:{account_id}:parametergroup:{name}",+ }+ legacy_param_values = AccountScopedDict()+ legacy_param_values._data[(account_id, name)] = {+ "maxmemory-policy": {"Value": "allkeys-lru"},+ }+ legacy_snapshots = AccountScopedDict()+ legacy_snapshots._data[(account_id, name)] = {+ "SnapshotName": name,+ "SnapshotStatus": "available",+ "ARN": f"arn:aws:elasticache:{region}:{account_id}:snapshot:{name}",+ }+ legacy_users = AccountScopedDict()+ legacy_users._data[(account_id, name)] = {+ "UserId": name,+ "ARN": f"arn:aws:elasticache:{region}:{account_id}:user:{name}",+ }+ legacy_groups = AccountScopedDict()+ legacy_groups._data[(account_id, name)] = {+ "UserGroupId": name,+ "ARN": f"arn:aws:elasticache:{region}:{account_id}:usergroup:{name}",+ }++ _ec.reset()+ try:+ set_request_account_id(account_id)+ set_request_region("us-east-1")+ _ec.restore_state({+ "clusters": legacy_clusters,+ "replication_groups": legacy_rgs,+ "subnet_groups": legacy_subnets,+ "param_groups": legacy_params,+ "param_group_params": legacy_param_values,+ "snapshots": legacy_snapshots,+ "users": legacy_users,+ "user_groups": legacy_groups,+ })++ assert _ec._clusters.get_scoped(account_id, region, name)["CacheClusterArn"].endswith(f":cluster:{name}")+ assert _ec._clusters.get_scoped(account_id, "us-east-1", name) is None+ assert _ec._replication_groups.get_scoped(account_id, region, name)["ARN"].endswith(f":replicationgroup:{name}")+ assert _ec._subnet_groups.get_scoped(account_id, region, name)["ARN"].endswith(f":subnetgroup:{name}")+ assert _ec._param_groups.get_scoped(account_id, region, name)["ARN"].endswith(f":parametergroup:{name}")+ assert _ec._param_group_params.get_scoped(account_id, region, name)["maxmemory-policy"]["Value"] == "allkeys-lru"+ assert _ec._param_group_params.get_scoped(account_id, "us-east-1", name) is None+ assert _ec._snapshots.get_scoped(account_id, region, name)["ARN"].endswith(f":snapshot:{name}")+ assert _ec._users.get_scoped(account_id, region, name)["ARN"].endswith(f":user:{name}")+ assert _ec._user_groups.get_scoped(account_id, region, name)["ARN"].endswith(f":usergroup:{name}")+ finally:+ _ec.reset()+ set_request_account_id(original_account)+ set_request_region(original_region)++# ---------------------------------------------------------------------------# 1. ModifyCacheCluster# ---------------------------------------------------------------------------@@ -966,14 +1345,6 @@ def test_serverless_cache_not_implemented(ec):# ========== from test_elasticache_lambda_network.py ==========# ElastiCache+Lambda network reachability via DOCKER_NETWORK auto-detect.-import io-import json-import os-import time-import zipfile--import pytest-_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"@@ -1138,16 +1509,16 @@ def test_elasticache_restore_state_marks_clusters_for_respawn(monkeypatch):})assert spawned == [] # respawn deferred — _spawn_redis_container not yet bound at import time- assert "clustertest" in _ec._pending_cluster_respawn+ assert ("000000000000", "us-east-1", "clustertest") in _ec._pending_cluster_respawn_ec._ensure_live_containers()- assert any(s["name"] == "ministack-elasticache-clustertest" for s in spawned)+ assert any(s["name"] == "ministack-elasticache-000000000000-us-east-1-clustertest" for s in spawned)cl = _ec._clusters["clustertest"]- assert cl["_docker_container_id"] == "cid-ministack-elasticache-clustertest"+ assert cl["_docker_container_id"] == "cid-ministack-elasticache-000000000000-us-east-1-clustertest"assert cl["CacheNodes"][0]["Endpoint"]["Address"] == "ministack-elasticache"assert cl["CacheNodes"][0]["Endpoint"]["Port"] == 6379- assert "clustertest" not in _ec._pending_cluster_respawn+ assert ("000000000000", "us-east-1", "clustertest") not in _ec._pending_cluster_respawnspawned.clear()_ec._ensure_live_containers()@@ -1173,17 +1544,92 @@ def test_elasticache_restore_state_wipes_stale_replication_group_container_ids(m},})assert _ec._replication_groups["rg-1"]["_docker_container_ids"] == []- assert "rg-1" in _ec._pending_rg_respawn+ assert ("000000000000", "us-east-1", "rg-1") in _ec._pending_rg_respawn_ec._ensure_live_containers()cids = _ec._replication_groups["rg-1"]["_docker_container_ids"]- assert cids == ["cid-ministack-elasticache-rg-000000000000-rg-1-0001"]- assert "rg-1" not in _ec._pending_rg_respawn+ assert cids == ["cid-ministack-elasticache-rg-000000000000-us-east-1-rg-1-0001"]+ assert ("000000000000", "us-east-1", "rg-1") not in _ec._pending_rg_respawn+++def test_elasticache_restore_state_respawns_same_names_per_region(monkeypatch):+ from ministack.core.responses import AccountRegionScopedDict+ from ministack.services import elasticache as _ec++ _ec.reset()+ spawned = []++ def fake_spawn(name, engine, engine_version, labels):+ spawned.append({"name": name, "labels": labels})+ return (f"{labels['region']}-host", 6379, f"cid-{name}")++ monkeypatch.setattr(_ec, "_spawn_redis_container", fake_spawn)++ clusters = AccountRegionScopedDict()+ replication_groups = AccountRegionScopedDict()+ account_id = "000000000000"+ for region in ("us-east-1", "us-west-2"):+ clusters.set_scoped(account_id, region, "same-cache", {+ "CacheClusterId": "same-cache",+ "CacheClusterStatus": "available",+ "Engine": "redis",+ "EngineVersion": "7.1",+ "CacheNodes": [{"CacheNodeId": "0001", "Endpoint": {"Address": "stale", "Port": 1}}],+ "_docker_container_id": f"dead-{region}",+ })+ replication_groups.set_scoped(account_id, region, "same-rg", {+ "ReplicationGroupId": "same-rg",+ "Engine": "redis",+ "EngineVersion": "7.1",+ "NodeGroups": [{"NodeGroupId": "0001"}],+ "_docker_container_ids": [f"dead-rg-{region}"],+ })++ _ec.restore_state({+ "clusters": clusters,+ "replication_groups": replication_groups,+ })++ assert _ec._pending_cluster_respawn == {+ (account_id, "us-east-1", "same-cache"),+ (account_id, "us-west-2", "same-cache"),+ }+ assert _ec._pending_rg_respawn == {+ (account_id, "us-east-1", "same-rg"),+ (account_id, "us-west-2", "same-rg"),+ }++ _ec._ensure_live_containers()++ names = {entry["name"] for entry in spawned}+ assert names == {+ "ministack-elasticache-000000000000-us-east-1-same-cache",+ "ministack-elasticache-000000000000-us-west-2-same-cache",+ "ministack-elasticache-rg-000000000000-us-east-1-same-rg-0001",+ "ministack-elasticache-rg-000000000000-us-west-2-same-rg-0001",+ }+ assert {entry["labels"]["region"] for entry in spawned} == {"us-east-1", "us-west-2"}+ assert _ec._clusters.get_scoped(account_id, "us-east-1", "same-cache")["_docker_container_id"] == (+ "cid-ministack-elasticache-000000000000-us-east-1-same-cache"+ )+ assert _ec._clusters.get_scoped(account_id, "us-west-2", "same-cache")["_docker_container_id"] == (+ "cid-ministack-elasticache-000000000000-us-west-2-same-cache"+ )+ assert _ec._replication_groups.get_scoped(account_id, "us-east-1", "same-rg")["_docker_container_ids"] == [+ "cid-ministack-elasticache-rg-000000000000-us-east-1-same-rg-0001",+ ]+ assert _ec._replication_groups.get_scoped(account_id, "us-west-2", "same-rg")["_docker_container_ids"] == [+ "cid-ministack-elasticache-rg-000000000000-us-west-2-same-rg-0001",+ ]+ assert _ec._pending_cluster_respawn == set()+ assert _ec._pending_rg_respawn == set()def test_elasticache_respawn_failure_is_logged_and_does_not_block_requests(monkeypatch, caplog):import logging+from ministack.services import elasticache as _ec+_ec.reset()def boom(*a, **kw):@@ -1202,5 +1648,5 @@ def test_elasticache_respawn_failure_is_logged_and_does_not_block_requests(monke})with caplog.at_level(logging.WARNING):_ec._ensure_live_containers()- assert "c1" not in _ec._pending_cluster_respawn # cleared even on failure (no retry storm)+ assert ("000000000000", "us-east-1", "c1") not in _ec._pending_cluster_respawn # cleared even on failure (no retry storm)assert any("failed to respawn" in r.message for r in caplog.records)diff --git a/tests/test_persistence.py b/tests/test_persistence.pyindex 8d153909..81a2bddb 100644--- a/tests/test_persistence.py+++ b/tests/test_persistence.py@@ -728,6 +728,165 @@ def test_kinesis_consumers_survive_warm_boot():mod.reset()+def test_elasticache_region_scoped_stores_survive_warm_boot_in_original_scope():+ """ElastiCache region-scoped stores must serialize every account+region."""+ from ministack.core.responses import (+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,+ )++ mod = _get_module("elasticache")+ original_account = get_account_id()+ original_region = get_region()+ account_id = "000000000000"++ mod.reset()+ try:+ set_request_account_id(account_id)+ set_request_region("us-east-1")+ mod._clusters["same-cache"] = {+ "CacheClusterId": "same-cache",+ "CacheClusterArn": f"arn:aws:elasticache:us-east-1:{account_id}:cluster:same-cache",+ "CacheClusterStatus": "available",+ "Engine": "redis",+ "EngineVersion": "7.1",+ "CacheNodes": [],+ "_docker_container_id": "stale-east",+ }+ mod._replication_groups["same-rg"] = {+ "ReplicationGroupId": "same-rg",+ "ARN": f"arn:aws:elasticache:us-east-1:{account_id}:replicationgroup:same-rg",+ "Status": "available",+ "Engine": "redis",+ "NodeGroups": [],+ "_docker_container_ids": ["stale-east-rg"],+ }+ mod._subnet_groups["same-subnet"] = {+ "CacheSubnetGroupName": "same-subnet",+ "ARN": f"arn:aws:elasticache:us-east-1:{account_id}:subnetgroup:same-subnet",+ }+ mod._param_groups["same-param"] = {+ "CacheParameterGroupName": "same-param",+ "CacheParameterGroupFamily": "redis7",+ "ARN": f"arn:aws:elasticache:us-east-1:{account_id}:parametergroup:same-param",+ }+ mod._param_group_params["same-param"] = {"timeout": {"Value": "1"}}+ mod._snapshots["same-snap"] = {+ "SnapshotName": "same-snap",+ "SnapshotStatus": "available",+ "ARN": f"arn:aws:elasticache:us-east-1:{account_id}:snapshot:same-snap",+ }+ mod._users["same-user"] = {+ "UserId": "same-user",+ "ARN": f"arn:aws:elasticache:us-east-1:{account_id}:user:same-user",+ }+ mod._user_groups["same-group"] = {+ "UserGroupId": "same-group",+ "ARN": f"arn:aws:elasticache:us-east-1:{account_id}:usergroup:same-group",+ }+ mod._events["entries"] = [{"SourceIdentifier": "same-cache", "Message": "east"}]+ mod._tags[f"arn:aws:elasticache:us-east-1:{account_id}:cluster:same-cache"] = [+ {"Key": "region", "Value": "east"},+ ]++ set_request_region("us-west-2")+ mod._clusters["same-cache"] = {+ "CacheClusterId": "same-cache",+ "CacheClusterArn": f"arn:aws:elasticache:us-west-2:{account_id}:cluster:same-cache",+ "CacheClusterStatus": "available",+ "Engine": "redis",+ "EngineVersion": "7.1",+ "CacheNodes": [],+ "_docker_container_id": "stale-west",+ }+ mod._replication_groups["same-rg"] = {+ "ReplicationGroupId": "same-rg",+ "ARN": f"arn:aws:elasticache:us-west-2:{account_id}:replicationgroup:same-rg",+ "Status": "available",+ "Engine": "redis",+ "NodeGroups": [],+ "_docker_container_ids": ["stale-west-rg"],+ }+ mod._subnet_groups["same-subnet"] = {+ "CacheSubnetGroupName": "same-subnet",+ "ARN": f"arn:aws:elasticache:us-west-2:{account_id}:subnetgroup:same-subnet",+ }+ mod._param_groups["same-param"] = {+ "CacheParameterGroupName": "same-param",+ "CacheParameterGroupFamily": "redis7",+ "ARN": f"arn:aws:elasticache:us-west-2:{account_id}:parametergroup:same-param",+ }+ mod._param_group_params["same-param"] = {"timeout": {"Value": "2"}}+ mod._snapshots["same-snap"] = {+ "SnapshotName": "same-snap",+ "SnapshotStatus": "available",+ "ARN": f"arn:aws:elasticache:us-west-2:{account_id}:snapshot:same-snap",+ }+ mod._users["same-user"] = {+ "UserId": "same-user",+ "ARN": f"arn:aws:elasticache:us-west-2:{account_id}:user:same-user",+ }+ mod._user_groups["same-group"] = {+ "UserGroupId": "same-group",+ "ARN": f"arn:aws:elasticache:us-west-2:{account_id}:usergroup:same-group",+ }+ mod._events["entries"] = [{"SourceIdentifier": "same-cache", "Message": "west"}]+ mod._tags[f"arn:aws:elasticache:us-west-2:{account_id}:cluster:same-cache"] = [+ {"Key": "region", "Value": "west"},+ ]++ _round_trip_dict(mod, "elasticache")++ set_request_region("us-east-1")+ assert mod._clusters["same-cache"]["CacheClusterArn"].startswith(+ "arn:aws:elasticache:us-east-1:"+ )+ assert mod._clusters["same-cache"]["_docker_container_id"] is None+ assert mod._replication_groups["same-rg"]["ARN"].startswith(+ "arn:aws:elasticache:us-east-1:"+ )+ assert mod._replication_groups["same-rg"]["_docker_container_ids"] == []+ assert mod._subnet_groups["same-subnet"]["ARN"].startswith(+ "arn:aws:elasticache:us-east-1:"+ )+ assert mod._param_groups["same-param"]["ARN"].startswith(+ "arn:aws:elasticache:us-east-1:"+ )+ assert mod._param_group_params["same-param"]["timeout"]["Value"] == "1"+ assert mod._snapshots["same-snap"]["ARN"].startswith(+ "arn:aws:elasticache:us-east-1:"+ )+ assert mod._users["same-user"]["ARN"].startswith(+ "arn:aws:elasticache:us-east-1:"+ )+ assert mod._user_groups["same-group"]["ARN"].startswith(+ "arn:aws:elasticache:us-east-1:"+ )+ assert mod._events["entries"] == [{"SourceIdentifier": "same-cache", "Message": "east"}]++ set_request_region("us-west-2")+ assert mod._clusters["same-cache"]["CacheClusterArn"].startswith(+ "arn:aws:elasticache:us-west-2:"+ )+ assert mod._replication_groups["same-rg"]["ARN"].startswith(+ "arn:aws:elasticache:us-west-2:"+ )+ assert mod._param_group_params["same-param"]["timeout"]["Value"] == "2"+ assert mod._events["entries"] == [{"SourceIdentifier": "same-cache", "Message": "west"}]+ assert mod._tags[+ f"arn:aws:elasticache:us-east-1:{account_id}:cluster:same-cache"+ ] == [{"Key": "region", "Value": "east"}]+ assert mod._tags[+ f"arn:aws:elasticache:us-west-2:{account_id}:cluster:same-cache"+ ] == [{"Key": "region", "Value": "west"}]+ finally:+ mod.reset()+ set_request_account_id(original_account)+ set_request_region(original_region)++# ── ecs._attributes ────────────────────────────────────────────────────def test_ecs_attributes_survive_warm_boot():