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
RDS: add FailoverDBCluster (metadata-only reader promotion) (#1430)
kiran01bm91bb8cc973bd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c6a9e1dd..4360f240 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Added+- **RDS — `FailoverDBCluster`** — forcing an Aurora cluster failover was `InvalidAction`. The operation now promotes a reader member to writer: an explicit `TargetDBInstanceIdentifier` must be an available reader belonging to the cluster (a non-member is `InvalidDBInstanceState`, an unknown instance `DBInstanceNotFound`); without a target the available reader with the lowest `PromotionTier` is chosen, as on AWS. The response reports the transitional `failing-over` status while a follow-up `DescribeDBClusters` sees `available` with the flipped `IsClusterWriter` flags, mirroring `FailoverGlobalCluster`. A missing cluster is `DBClusterNotFoundFault`, a non-available cluster or one with no promotable reader `InvalidDBClusterStateFault`. Metadata-only for now: cluster members share one container, so there is no reader data plane to re-point until per-instance replication (#1325) lands. Contributed by @kiran01bm.- **RDS — opt-in Aurora PostgreSQL reader instances backed by real streaming replication** — with `MINISTACK_RDS_PG_CLUSTER_REPLICATION=1`, the second and later members of an Aurora PostgreSQL cluster launch their own PostgreSQL containers, cloned from the writer with `pg_basebackup` and running as hot standbys that stream WAL from it. A reader is genuinely read-only (`pg_is_in_recovery()` is true, writes fail with `25006`), sees data written to the writer, and the cluster `ReaderEndpoint` resolves to an available reader instead of the writer — so read/write connection routing, replica-lag handling, and reader-endpoint pooling can be rehearsed locally. Off by default: without the flag (and for Aurora MySQL) members keep aliasing the writer's single shared container. Requires the shared Docker network (`DOCKER_NETWORK`); deleting a reader removes only its own container. Not yet modeled (follow-up slices of #1325): stopping a cluster with replicating readers is rejected with `InvalidDBClusterStateFault`, and a persisted reader demotes to a shared-container alias on warm boot. Contributed by @kiran01bm.- **CloudFormation — API Gateway (v1) API keys and usage plans** — `AWS::ApiGateway::ApiKey`, `AWS::ApiGateway::UsagePlan`, and `AWS::ApiGateway::UsagePlanKey` failed stack creation with `Unsupported resource type`, even though the runtime `CreateApiKey` / `CreateUsagePlan` APIs were already served. The three resource types now provision through those same stores: an `ApiKey` supports a pinned `Value`, `Enabled`, and `StageKeys`, updates `Name` / `Description` / `Enabled` in place, and exposes both `Ref` and `Fn::GetAtt APIKeyId` as the key id; a `UsagePlan` maps `Throttle` / `Quota` / `ApiStages` and returns its id via `Ref` and `Fn::GetAtt Id`; a `UsagePlanKey` associates a key with a plan and is torn down from the plan on delete. This unblocks CDK `RestApi` / `ApiKey` constructs and Terraform `aws_api_gateway_api_key` deployed through CloudFormation. Contributed by @ryan-bennett.diff --git a/README.md b/README.mdindex b4c0b2d7..bd541781 100644--- a/README.md+++ b/README.md@@ -561,7 +561,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i| Service | Operations | Notes ||---------|-----------|-------|| **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, 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 | `CreateDBInstance` spins up real Postgres/MySQL Docker container, returns actual `host:port` endpoint; 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 — the plugin rejects authentication (non-enforcing); disable with `MINISTACK_MYSQL_IAM_AUTH=off` |+| **RDS** | CreateDBInstance, DeleteDBInstance, DescribeDBInstances, ModifyDBInstance, StartDBInstance, StopDBInstance, RebootDBInstance, CreateDBInstanceReadReplica, RestoreDBInstanceFromDBSnapshot, CreateDBCluster, DeleteDBCluster, DescribeDBClusters, ModifyDBCluster, StartDBCluster, StopDBCluster, FailoverDBCluster, 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 | `CreateDBInstance` spins up real Postgres/MySQL Docker container, returns actual `host:port` endpoint; 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 — the plugin rejects authentication (non-enforcing); disable with `MINISTACK_MYSQL_IAM_AUTH=off` || **Aurora DSQL** | CreateCluster, GetCluster, UpdateCluster, DeleteCluster, ListClusters, PutClusterPolicy, GetClusterPolicy, DeleteClusterPolicy, 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`, foreign keys, extensions, ...), 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`) || **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` |diff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex 78e0e6ee..07ee791c 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -5491,6 +5491,129 @@ def _stop_db_cluster(p):f"<StopDBClusterResult><DBCluster>{_cluster_xml(cluster)}</DBCluster></StopDBClusterResult>")+def _failover_db_cluster(p):+ """Force an intra-cluster failover: promote a reader member to writer.++ Metadata-only for now, mirroring ``_failover_global_cluster``: the member+ ``IsClusterWriter`` flags flip and the response reports the transitional+ ``failing-over`` cluster status (the stored status stays ``available``,+ as a follow-up DescribeDBClusters observes on AWS once the failover+ completes). Data-plane promotion of a replicating reader container is a+ follow-up (#1325); with today's shared-container clusters every member+ already points at the same process, so there is nothing to re-point.++ Error fidelity notes (wire codes from the RDS service model):+ - unknown cluster: ``DBClusterNotFoundFault`` (404)+ - cluster not ``available`` / no reader to promote:+ ``InvalidDBClusterStateFault`` (400)+ - target problems: ``InvalidDBInstanceState`` (400) — the instance-level+ code omits the ``Fault`` suffix, like ``DBInstanceAlreadyExists``+ (#1297); a target that exists nowhere is ``DBInstanceNotFound`` (404).+ """+ cluster_id = _p(p, "DBClusterIdentifier")+ cluster = _resolve_cluster_in_request_region(cluster_id)+ if not cluster:+ wrong_region = _invalid_cluster_identifier_error(cluster_id)+ if wrong_region:+ return wrong_region+ return _error("DBClusterNotFoundFault", f"DBCluster {cluster_id} not found.", 404)+ cluster_id = cluster.get("DBClusterIdentifier", cluster_id)+ status = cluster.get("Status")+ if status != "available":+ return _error(+ "InvalidDBClusterStateFault",+ f"DbCluster {cluster_id} is in {status} state but expected it to "+ "be one of available.",+ 400,+ )+ if cluster.get("_shared_legacy_migration_in_progress") or cluster.get(+ "_shared_legacy_migration_blocked",+ ):+ # restore_state's one-time legacy-storage migration reads+ # IsClusterWriter to pick which member's volume becomes the+ # cluster's adopted shared state; flipping the flag mid-migration+ # could make it adopt a reader's volume. Same gate as+ # CreateDBInstance's cluster-member path.+ return _error(+ "InvalidDBClusterStateFault",+ f"Cannot failover DB cluster {cluster_id} while legacy shared-"+ "storage migration is in progress.",+ 400,+ )++ members = cluster.get("DBClusterMembers", [])+ readers = [m for m in members if not m.get("IsClusterWriter")]++ target_id = _p(p, "TargetDBInstanceIdentifier")+ if target_id:+ target = next(+ (m for m in members if m.get("DBInstanceIdentifier") == target_id),+ None,+ )+ if not target:+ if not _resolve_instance(target_id):+ return _error(+ "DBInstanceNotFound", f"DBInstance {target_id} not found.", 404)+ return _error(+ "InvalidDBInstanceState",+ f"DBInstance {target_id} is not a member of DB cluster "+ f"{cluster_id}.",+ 400,+ )+ if target.get("IsClusterWriter"):+ return _error(+ "InvalidDBInstanceState",+ f"DBInstance {target_id} is already the writer of DB cluster "+ f"{cluster_id}; specify a reader instance to promote.",+ 400,+ )+ target_instance = _resolve_instance(target_id)+ if target_instance is None:+ # A member with no backing instance record cannot happen today+ # (deletion unregisters the member synchronously), but promoting+ # a phantom would strand the cluster; refuse defensively.+ return _error(+ "DBInstanceNotFound", f"DBInstance {target_id} not found.", 404)+ if target_instance.get("DBInstanceStatus") != "available":+ return _error(+ "InvalidDBInstanceState",+ f"DBInstance {target_id} is in "+ f"{target_instance.get('DBInstanceStatus')} state but expected "+ "it to be one of available.",+ 400,+ )+ else:+ # AWS promotes the best candidate from the lowest promotion tier;+ # within a tier Ministack keeps member order (no instance sizing).+ def _promotable(member):+ inst = _resolve_instance(member.get("DBInstanceIdentifier", ""))+ return inst is not None and inst.get("DBInstanceStatus") == "available"++ candidates = sorted(+ (m for m in readers if _promotable(m)),+ key=lambda m: int(m.get("PromotionTier", 1)),+ )+ if not candidates:+ return _error(+ "InvalidDBClusterStateFault",+ f"Cannot failover DB cluster {cluster_id} because it has no "+ "available reader instance to promote.",+ 400,+ )+ target = candidates[0]+ target_id = target["DBInstanceIdentifier"]++ for member in members:+ member["IsClusterWriter"] = (+ member.get("DBInstanceIdentifier") == target_id+ )++ response_cluster = copy.deepcopy(cluster)+ response_cluster["Status"] = "failing-over"+ return _xml(200, "FailoverDBClusterResponse",+ f"<FailoverDBClusterResult><DBCluster>{_cluster_xml(response_cluster)}</DBCluster></FailoverDBClusterResult>")++# ---------------------------------------------------------------------------# Option Groups# ---------------------------------------------------------------------------@@ -6887,6 +7010,7 @@ _ACTION_MAP = {"ModifyDBCluster": _modify_db_cluster,"StartDBCluster": _start_db_cluster,"StopDBCluster": _stop_db_cluster,+ "FailoverDBCluster": _failover_db_cluster,"CreateDBSnapshot": _create_db_snapshot,"DeleteDBSnapshot": _delete_db_snapshot,"DescribeDBSnapshots": _describe_db_snapshots,diff --git a/tests/test_rds.py b/tests/test_rds.pyindex 747fb7b6..495ca6c7 100644--- a/tests/test_rds.py+++ b/tests/test_rds.py@@ -2595,6 +2595,265 @@ def test_rds_instance_ops_rejected_while_cluster_stopped(monkeypatch):m._clusters.clear()+def _build_failover_cluster(m, cluster_id, members):+ """Create a cluster and member instances (Docker-free) for failover tests.++ ``members`` is an iterable of ``(db_instance_id, promotion_tier)``; the+ first member becomes the writer, matching ``_register_instance_in_cluster``.+ """+ m._create_db_cluster({+ "DBClusterIdentifier": cluster_id,+ "Engine": "aurora-mysql",+ "MasterUsername": "admin",+ "MasterUserPassword": "password123",+ })+ for db_id, tier in members:+ m._create_db_instance({+ "DBInstanceIdentifier": db_id,+ "DBClusterIdentifier": cluster_id,+ "DBInstanceClass": "db.r6g.large",+ "Engine": "aurora-mysql",+ "PromotionTier": str(tier),+ })+++def _cluster_writer_flags(cluster):+ return {+ m["DBInstanceIdentifier"]: m["IsClusterWriter"]+ for m in cluster["DBClusterMembers"]+ }+++def test_rds_failover_db_cluster_promotes_lowest_tier_reader(monkeypatch):+ """Automatic failover promotes the available reader with the lowest tier."""+ from ministack.services import rds as m++ monkeypatch.setattr(m, "_get_docker", lambda: None)+ m._instances.clear()+ m._clusters.clear()+ try:+ _build_failover_cluster(m, "failover-auto-cluster", [+ ("failover-auto-writer", 1),+ ("failover-auto-tier2", 2),+ ("failover-auto-tier0", 0),+ ])+ cluster = m._clusters.get("failover-auto-cluster")+ assert _poll_until(lambda: cluster["Status"] == "available")++ status, _, body = m._failover_db_cluster({+ "DBClusterIdentifier": "failover-auto-cluster",+ })+ assert status == 200+ assert b"FailoverDBClusterResponse" in body+ # The response reports the transitional state; the stored cluster is+ # already through it, as a follow-up DescribeDBClusters observes.+ assert b"<Status>failing-over</Status>" in body+ assert cluster["Status"] == "available"++ flags = _cluster_writer_flags(cluster)+ assert flags == {+ "failover-auto-writer": False,+ "failover-auto-tier2": False,+ "failover-auto-tier0": True,+ }++ # An unavailable reader must never be promoted: with tier-1 stopped,+ # the next failover picks the remaining available reader.+ m._instances.get("failover-auto-writer")["DBInstanceStatus"] = "stopped"+ status, _, _body = m._failover_db_cluster({+ "DBClusterIdentifier": "failover-auto-cluster",+ })+ assert status == 200+ flags = _cluster_writer_flags(cluster)+ assert flags == {+ "failover-auto-writer": False,+ "failover-auto-tier2": True,+ "failover-auto-tier0": False,+ }+ assert sum(flags.values()) == 1+ finally:+ m._instances.clear()+ m._clusters.clear()+++def test_rds_failover_db_cluster_tier_tie_keeps_member_order(monkeypatch):+ """A same-tier tie promotes the earlier member, as documented.++ The automatic path relies on ``sorted()`` stability for the "within a+ tier Ministack keeps member order" contract; this pins it so a refactor+ to an unstable ordering (or a reordered candidates build) is caught.+ """+ from ministack.services import rds as m++ monkeypatch.setattr(m, "_get_docker", lambda: None)+ m._instances.clear()+ m._clusters.clear()+ try:+ _build_failover_cluster(m, "failover-tie-cluster", [+ ("failover-tie-writer", 0),+ ("failover-tie-reader-a", 1),+ ("failover-tie-reader-b", 1),+ ])+ cluster = m._clusters.get("failover-tie-cluster")+ assert _poll_until(lambda: cluster["Status"] == "available")++ status, _, _body = m._failover_db_cluster({+ "DBClusterIdentifier": "failover-tie-cluster",+ })+ assert status == 200+ flags = _cluster_writer_flags(cluster)+ assert flags == {+ "failover-tie-writer": False,+ "failover-tie-reader-a": True,+ "failover-tie-reader-b": False,+ }+ finally:+ m._instances.clear()+ m._clusters.clear()+++def test_rds_failover_db_cluster_explicit_target_validation(monkeypatch):+ """Explicit targets are validated: member, non-writer, and available."""+ from ministack.services import rds as m++ monkeypatch.setattr(m, "_get_docker", lambda: None)+ m._instances.clear()+ m._clusters.clear()+ try:+ _build_failover_cluster(m, "failover-target-cluster", [+ ("failover-target-writer", 1),+ ("failover-target-reader", 1),+ ])+ m._create_db_instance({+ "DBInstanceIdentifier": "failover-target-standalone",+ "DBInstanceClass": "db.t3.micro",+ "Engine": "mysql",+ "MasterUsername": "admin",+ "MasterUserPassword": "password123",+ })+ cluster = m._clusters.get("failover-target-cluster")+ assert _poll_until(lambda: cluster["Status"] == "available")++ status, _, body = m._failover_db_cluster({+ "DBClusterIdentifier": "failover-target-cluster",+ "TargetDBInstanceIdentifier": "failover-target-reader",+ })+ assert status == 200+ assert _cluster_writer_flags(cluster) == {+ "failover-target-writer": False,+ "failover-target-reader": True,+ }++ # The freshly promoted writer is not a valid target.+ status, _, body = m._failover_db_cluster({+ "DBClusterIdentifier": "failover-target-cluster",+ "TargetDBInstanceIdentifier": "failover-target-reader",+ })+ assert status == 400+ assert b"InvalidDBInstanceState" in body++ # An instance that exists but belongs to no cluster is not a target.+ status, _, body = m._failover_db_cluster({+ "DBClusterIdentifier": "failover-target-cluster",+ "TargetDBInstanceIdentifier": "failover-target-standalone",+ })+ assert status == 400+ assert b"InvalidDBInstanceState" in body++ # A target that exists nowhere is DBInstanceNotFound (404).+ status, _, body = m._failover_db_cluster({+ "DBClusterIdentifier": "failover-target-cluster",+ "TargetDBInstanceIdentifier": "failover-target-missing",+ })+ assert status == 404+ assert b"DBInstanceNotFound" in body++ # A member reader that is not available cannot be promoted.+ m._instances.get("failover-target-writer")["DBInstanceStatus"] = "rebooting"+ status, _, body = m._failover_db_cluster({+ "DBClusterIdentifier": "failover-target-cluster",+ "TargetDBInstanceIdentifier": "failover-target-writer",+ })+ assert status == 400+ assert b"InvalidDBInstanceState" in body+ # The failed attempts left the writer flags untouched.+ assert _cluster_writer_flags(cluster) == {+ "failover-target-writer": False,+ "failover-target-reader": True,+ }+ finally:+ m._instances.clear()+ m._clusters.clear()+++def test_rds_failover_db_cluster_cluster_state_errors(monkeypatch):+ """Missing, non-available, and reader-less clusters are rejected."""+ from ministack.services import rds as m++ monkeypatch.setattr(m, "_get_docker", lambda: None)+ m._instances.clear()+ m._clusters.clear()+ try:+ status, _, body = m._failover_db_cluster({+ "DBClusterIdentifier": "failover-missing-cluster",+ })+ assert status == 404+ assert b"DBClusterNotFoundFault" in body++ # A writer-only cluster has nothing to promote.+ _build_failover_cluster(m, "failover-solo-cluster", [+ ("failover-solo-writer", 1),+ ])+ cluster = m._clusters.get("failover-solo-cluster")+ assert _poll_until(lambda: cluster["Status"] == "available")+ status, _, body = m._failover_db_cluster({+ "DBClusterIdentifier": "failover-solo-cluster",+ })+ assert status == 400+ assert b"InvalidDBClusterStateFault" in body++ # All readers unavailable is the same fault.+ _build_failover_cluster(m, "failover-downed-cluster", [+ ("failover-downed-writer", 1),+ ("failover-downed-reader", 1),+ ])+ downed = m._clusters.get("failover-downed-cluster")+ assert _poll_until(lambda: downed["Status"] == "available")+ m._instances.get("failover-downed-reader")["DBInstanceStatus"] = "stopped"+ status, _, body = m._failover_db_cluster({+ "DBClusterIdentifier": "failover-downed-cluster",+ })+ assert status == 400+ assert b"InvalidDBClusterStateFault" in body++ # An in-flight legacy-storage migration is rejected: restore_state+ # reads IsClusterWriter to pick the adopted volume, so the flag must+ # not flip mid-migration.+ downed["_shared_legacy_migration_in_progress"] = True+ m._instances.get("failover-downed-reader")["DBInstanceStatus"] = (+ "available"+ )+ status, _, body = m._failover_db_cluster({+ "DBClusterIdentifier": "failover-downed-cluster",+ })+ assert status == 400+ assert b"InvalidDBClusterStateFault" in body+ assert b"legacy shared-storage migration" in body+ downed.pop("_shared_legacy_migration_in_progress", None)++ # A stopped cluster is rejected before member checks.+ m._stop_db_cluster({"DBClusterIdentifier": "failover-solo-cluster"})+ assert cluster["Status"] == "stopped"+ status, _, body = m._failover_db_cluster({+ "DBClusterIdentifier": "failover-solo-cluster",+ })+ assert status == 400+ assert b"InvalidDBClusterStateFault" in body+ finally:+ m._instances.clear()+ m._clusters.clear()++def test_rds_stop_db_cluster_docker_failure_surfaces_error(monkeypatch):"""A failed Docker stop must not report the cluster as stopped."""from ministack.services import rds as m@@ -6266,6 +6525,62 @@ def test_failover_global_cluster_missing_global_validated_before_parameter_comboassert exc.value.response["Error"]["Code"] == "GlobalClusterNotFoundFault"+def test_failover_db_cluster_promotes_reader_over_the_wire():+ """FailoverDBCluster is routable end to end and flips the writer flags."""+ east = _regional_rds("us-east-1")+ suffix = uuid.uuid4().hex[:8]+ cluster_id = f"failover-wire-{suffix}"+ writer_id = f"failover-wire-writer-{suffix}"+ reader_id = f"failover-wire-reader-{suffix}"++ try:+ east.create_db_cluster(+ DBClusterIdentifier=cluster_id,+ Engine="aurora-mysql",+ MasterUsername="admin",+ MasterUserPassword="password123",+ )+ for db_id in (writer_id, reader_id):+ east.create_db_instance(+ DBInstanceIdentifier=db_id,+ DBClusterIdentifier=cluster_id,+ DBInstanceClass="db.t3.micro",+ Engine="aurora-mysql",+ )+ _wait_for_rds(east, db_id)++ response = east.failover_db_cluster(+ DBClusterIdentifier=cluster_id,+ TargetDBInstanceIdentifier=reader_id,+ )["DBCluster"]+ assert response["Status"] == "failing-over"+ members = {+ m["DBInstanceIdentifier"]: m["IsClusterWriter"]+ for m in response["DBClusterMembers"]+ }+ assert members == {writer_id: False, reader_id: True}++ cluster = east.describe_db_clusters(+ DBClusterIdentifier=cluster_id,+ )["DBClusters"][0]+ assert cluster["Status"] == "available"+ members = {+ m["DBInstanceIdentifier"]: m["IsClusterWriter"]+ for m in cluster["DBClusterMembers"]+ }+ assert members == {writer_id: False, reader_id: True}++ with pytest.raises(ClientError) as exc:+ east.failover_db_cluster(+ DBClusterIdentifier=f"failover-wire-missing-{suffix}",+ )+ assert exc.value.response["Error"]["Code"] == "DBClusterNotFoundFault"+ finally:+ _delete_instance(east, reader_id)+ _delete_instance(east, writer_id)+ _delete_cluster(east, cluster_id)++def test_create_global_cluster_rejects_already_attached_source_cluster():east = _regional_rds("us-east-1")suffix = uuid.uuid4().hex[:8]