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
fix(docdb): modifying shape, error codes, strings, etc (#2124)
Nahuel Nucerace7b3a8eb7d1
diff --git a/.gitignore b/.gitignoreindex 44fe1efe..ea30cd45 100644--- a/.gitignore+++ b/.gitignore@@ -42,7 +42,6 @@ htmlcov/*.swo.DS_Store.kiro/-.kilo/# Dockerdata/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9b6176b8..a66fcd47 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,9 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]-- **DocumentDB — data plane runs the real DocumentDB container** — cluster and standalone-instance compute now uses the official `documentdb-local` image (`ghcr.io/documentdb/documentdb/documentdb-local:latest`, MIT licensed, replacing the MongoDB images) for both engine versions 5.0.0 and 8.0.0; credentials move to the container's `USERNAME`/`PASSWORD` env, the wire port stays 27017 (via `DOCUMENTDB_PORT`) and storage moves to `/data`. The gateway serves TLS with a self-signed certificate (`tls=true&tlsAllowInvalidCertificates=true`) while its `allowTLS` default also accepts plaintext, so existing pymongo clients keep working. Readiness waits after container start extend from 60 s to 300 s because first boot initializes a PostgreSQL data directory. Tags actions (`AddTagsToResource`, `ListTagsForResource`, `RemoveTagsFromResource`) now resolve `ResourceName` against live records and return the documented 404 faults (`DBClusterNotFoundFault`, `DBInstanceNotFound`, `DBSnapshotNotFound`) for unknown ARNs; a missing `ResourceName` returns `MissingParameter` for all three. DocumentDB state restores only through the registry's `load_persisted_state` contract, matching every other service.-### Added+- **DocumentDB** — the `docdb` API runs on the RDS control plane as it does on AWS: `CreateDBCluster` and `CreateDBInstance` with `Engine=docdb` default to engine `8.0.0`, port `27017`, the `default.docdb8.0` parameter group and `docdb.amazonaws.com` endpoints, and each cluster runs a `documentdb-local` container serving the MongoDB protocol over TLS. The `rds` client lists the same clusters, and the `engine=docdb` filter selects them. CloudFormation provisions `AWS::DocDB::DBCluster`, `DBInstance`, `DBSubnetGroup` and `DBClusterParameterGroup`, and `AWS::SecretsManager::SecretTargetAttachment` accepts DocumentDB targets. Contributed by @xPTM1219.- **CloudFormation — `AWS::Logs::MetricFilter`** — templates with a metric filter failed with `Unrecognized resource types`; the filter now provisions, updates in place and is replaced on a `FilterName` or `LogGroupName` change. Contributed by @iot-rocket.- **DynamoDB — vector search** — `CreateTable` accepts `VectorIndexes`, `UpdateTable` takes `VectorIndexUpdates` (resource allocation, then backfilling, then `ACTIVE`), and `DescribeTable` reports them. `SearchVectors` scores with `COSINE`, `EUCLIDEAN` or `DOT_PRODUCT` at 32-bit float precision and filters on the `SearchSchema`. Writes are checked against each vector index, `INDEXES` capacity reports `VectorWriteRequestBytes` on single, batch and transactional writes, and a PartiQL `SELECT` or `Scan` on a vector index returns "Scan operation not supported on this index type". Backups record the indexes in `SourceTableFeatureDetails`, `RestoreTableFromBackup` and `RestoreTableToPointInTime` restore them or apply `VectorIndexOverride`, and `ImportTable` creates them from `TableCreationParameters`. Reported by @hicksy and the paritysuite.org project.@@ -766,19 +765,6 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **IoT Core — an unresolvable action role fails `CreateTopicRule` instead of silently dropping the rule (`AUTH=true`)** — the role-check error was discarded and the API answered `200 {}` while storing nothing. `CreateTopicRule` / `ReplaceTopicRule` now answer `400 InvalidRequestException` (`Unable to assume role: {arn}`) as real IoT does, and the CloudFormation provisioner fails the resource. Contributed by @iot-rocket.- **RDS — Aurora PostgreSQL major-version selectors return the matching catalog** — `DescribeDBEngineVersions` treated `EngineVersion=16` as an exact version and returned nothing; major-only selectors now return every advertised minor in that family, and `DefaultOnly=true` narrows to AWS's configured default minor for that major. Contributed by @jayjanssen.-### Added--- **DocumentDB (docdb) service**: full repair and expansion of `ministack/services/documentdb.py`.- - Engine versions **5.0.0** and **8.0.0** (`DOCDB_ENGINE_VERSIONS`, families `docdb5.0`/`docdb8.0`), backed by wire-compatible `mongo:5.0` / `mongo:8.0` containers honoring `MINISTACK_IMAGE_PREFIX`; unsupported versions are rejected with `InvalidParameterCombination` everywhere.- - One **shared mongo container per DB cluster** (rds.py Aurora pattern): the first member starts it, later members alias its endpoint; `StopDBCluster`/`StartDBCluster` stop/restart the real container; deleting the final member stops it while keeping the volume (`DOCDB_PERSIST=1`), and only `DeleteDBCluster` removes container + storage.- - New IaC-complete control-plane actions: `CreateDBClusterSnapshot` / `DescribeDBClusterSnapshots` / `DeleteDBClusterSnapshot` (metadata-only snapshots with tags), `ModifyDBClusterSnapshotAttribute` / `DescribeDBClusterSnapshotAttributes` (share/restore attributes), cluster parameter groups (`Create/Describe/Delete/Modify/ResetDBClusterParameterGroup`, `DescribeDBClusterParameters` with engine-default overlay), `FailoverDBCluster` (writer rotation by lowest `PromotionTier`, stable endpoints), `RestoreDBClusterFromSnapshot`, `ApplyPendingMaintenanceAction` / `DescribePendingMaintenanceActions`, `DescribeCertificates`, `DescribeEvents`.- - Warm-boot respawn: persisted clusters/instances come back `creating` and daemon threads restart their containers (reusing saved host ports when free) before flipping to `available`; state stores switched to `AccountRegionScopedDict` for per-account/per-region isolation.- - Routing fix in `core/router.py`: repaired a broken `SERVICE_PATTERNS` entry and taught credential-scope dispatch that DocDB signs as `rds` — `docdb.*` / `documentdb.*` endpoint hosts now route to DocumentDB instead of RDS.--### Changed--- `tests/test_docdb.py`: rewritten against the boto3 `docdb` client (the previous suite could not run — the module failed at import and several calls used parameters/actions the real API rejects). Adds Docker-gated pymongo integration tests proving shared-endpoint visibility across members and real 8.0.0 connections.-## [1.5.0] — 2026-08-23### Addeddiff --git a/README.md b/README.mdindex e72dcd68..b753cb88 100644--- a/README.md+++ b/README.md@@ -623,9 +623,9 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i|---------|-----------|-------|| **ECS** | CreateCluster, DeleteCluster, DescribeClusters, ListClusters, UpdateCluster, UpdateClusterSettings, PutClusterCapacityProviders, RegisterTaskDefinition, DeregisterTaskDefinition, DescribeTaskDefinition, ListTaskDefinitions, ListTaskDefinitionFamilies, DeleteTaskDefinitions, CreateService, DeleteService, DescribeServices, UpdateService, ListServices, ListServicesByNamespace, RunTask, StopTask, DescribeTasks, ListTasks, ExecuteCommand, UpdateTaskProtection, GetTaskProtection, CreateCapacityProvider, UpdateCapacityProvider, DeleteCapacityProvider, DescribeCapacityProviders, TagResource, UntagResource, ListTagsForResource, ListAccountSettings, PutAccountSetting, PutAccountSettingDefault, DeleteAccountSetting, PutAttributes, DeleteAttributes, ListAttributes, DescribeServiceDeployments, ListServiceDeployments, DescribeServiceRevisions, SubmitTaskStateChange, SubmitContainerStateChange, SubmitAttachmentStateChanges, DiscoverPollEndpoint | 47 actions; `RunTask` starts real Docker containers via Docker socket; full Terraform ECS coverage || **RDS** | CreateDBInstance, DeleteDBInstance, DescribeDBInstances, ModifyDBInstance, StartDBInstance, StopDBInstance, RebootDBInstance, CreateDBInstanceReadReplica, RestoreDBInstanceFromDBSnapshot, CreateDBCluster, DeleteDBCluster, DescribeDBClusters, ModifyDBCluster, StartDBCluster, StopDBCluster, FailoverDBCluster, SwitchoverGlobalCluster, FailoverGlobalCluster, CreateDBSnapshot, DeleteDBSnapshot, DescribeDBSnapshots, CreateDBClusterSnapshot, DescribeDBClusterSnapshots, DescribeDBClusterSnapshotAttributes, DeleteDBClusterSnapshot, CreateDBSubnetGroup, DeleteDBSubnetGroup, DescribeDBSubnetGroups, ModifyDBSubnetGroup, CreateDBParameterGroup, DeleteDBParameterGroup, DescribeDBParameterGroups, DescribeDBParameters, ModifyDBParameterGroup, CreateDBClusterParameterGroup, DescribeDBClusterParameterGroups, DeleteDBClusterParameterGroup, DescribeDBClusterParameters, ModifyDBClusterParameterGroup, CreateOptionGroup, DeleteOptionGroup, DescribeOptionGroups, DescribeOptionGroupOptions, ListTagsForResource, AddTagsToResource, RemoveTagsFromResource, DescribeDBEngineVersions, DescribeOrderableDBInstanceOptions, CreateGlobalCluster, DescribeGlobalClusters, DeleteGlobalCluster, RemoveFromGlobalCluster, ModifyGlobalCluster, CreateDBProxy, DescribeDBProxies, ModifyDBProxy, DeleteDBProxy, CreateDBProxyEndpoint, DescribeDBProxyEndpoints, ModifyDBProxyEndpoint, DeleteDBProxyEndpoint, DescribeDBProxyTargetGroups, ModifyDBProxyTargetGroup, RegisterDBProxyTargets, DeregisterDBProxyTargets, DescribeDBProxyTargets | `CreateDBInstance` spins up real Postgres/MySQL Docker container, returns actual `host:port` endpoint; a standalone MySQL or MariaDB instance starts with its DB parameter group's set values, `immediate` changes to dynamic parameters reach running instances, and `BackupRetentionPeriod=0` turns binary logging off; a cluster's endpoint is its stable AWS-shaped name, registered as a Docker network alias on the backing container (on user-defined networks; the default bridge keeps the address form), so a stored endpoint keeps resolving after the container is replaced; Aurora MySQL 8.0/8.4 compatibility objects (`AWSAuthenticationPlugin`, RDS/Aurora stored procedures, predefined S3 roles) install automatically for supported MySQL images so Aurora provisioning workflows run. IAM database authentication on MySQL and Aurora MySQL 8.0/8.4 (not MariaDB): a user created `IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS'` logs in with an SDK-generated auth token over `mysql_clear_password` when the instance or cluster has `IAMDatabaseAuthenticationEnabled`; with `AUTH=true` the token and the `rds-db:connect` policy are verified too. Planned Aurora MySQL switchover (`SwitchoverGlobalCluster`, and `FailoverGlobalCluster` without data loss allowed) performs a coordinated no-data-loss writer exchange on provisioned two-member MySQL 8 global clusters; other configurations keep the metadata-only path. RDS Proxy is control plane only — proxies, proxy endpoints, the default target group and registered targets are stored and returned with the AWS shapes, but nothing listens on the proxy endpoint hostname; clients keep connecting to the instance or cluster endpoint |+| **DocumentDB** | CreateDBCluster, CreateDBInstance, DeleteDBCluster, DeleteDBInstance, DescribeDBClusters, DescribeDBInstances, StartDBCluster, StopDBCluster, ModifyDBCluster, AddTagsToResource, ListTagsForResource, CreateDBSubnetGroup, CreateDBClusterParameterGroup | Same control plane as RDS (`Engine=docdb`): the `docdb` and `rds` clients see the same clusters. Each cluster runs a `documentdb-local` container speaking the MongoDB protocol over TLS on its endpoint; engine versions 3.6.0, 4.0.0, 5.0.x and 8.0.x (default 8.0.0) || **Aurora DSQL** | CreateCluster, GetCluster, UpdateCluster, DeleteCluster, ListClusters, PutClusterPolicy, GetClusterPolicy, DeleteClusterPolicy, CreateStream, GetStream, ListStreams, DeleteStream, GetVpcEndpointServiceName, TagResource, UntagResource, ListTagsForResource | `CreateCluster` spins up a real `postgres:16-alpine` Docker container fronted by a validating PG wire-protocol proxy that **fails like real DSQL** — rejects unsupported SQL (`serial`, extensions, temp tables, ...), accepts `CREATE INDEX ASYNC` + `sys.jobs`; endpoint is `localhost:<port>`; any password accepted |-| **ElastiCache** | CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters, ModifyCacheCluster, RebootCacheCluster, CreateReplicationGroup, DeleteReplicationGroup, DescribeReplicationGroups, ModifyReplicationGroup, IncreaseReplicaCount, DecreaseReplicaCount, CreateCacheSubnetGroup, DescribeCacheSubnetGroups, ModifyCacheSubnetGroup, DeleteCacheSubnetGroup, CreateCacheParameterGroup, DescribeCacheParameterGroups, ModifyCacheParameterGroup, ResetCacheParameterGroup, DeleteCacheParameterGroup, DescribeCacheParameters, DescribeCacheEngineVersions, CreateUser, DescribeUsers, DeleteUser, ModifyUser, CreateUserGroup, DescribeUserGroups, DeleteUserGroup, ModifyUserGroup, ListTagsForResource, AddTagsToResource, RemoveTagsFromResource, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, CreateServerlessCache, DescribeServerlessCaches, ModifyServerlessCache, DeleteServerlessCache, DescribeEvents | `CreateCacheCluster` spins up a real Redis, Valkey, or Memcached Docker container (`Engine=redis`/`valkey`/`memcached`); a serverless cache gets a TLS-only Valkey/Redis container whose certificate chains to the CA at `GET /_ministack/elasticache/ca.pem` |-| **DocumentDB** | CreateDBInstance, DeleteDBInstance, DescribeDBInstances, ModifyDBInstance, StartDBInstance, StopDBInstance, RebootDBInstance, CreateDBCluster, DeleteDBCluster, DescribeDBClusters, ModifyDBCluster, StartDBCluster, StopDBCluster, FailoverDBCluster, RestoreDBClusterFromSnapshot, CreateDBSubnetGroup, DeleteDBSubnetGroup, DescribeDBSubnetGroups, CreateDBClusterSnapshot, DescribeDBClusterSnapshots, DeleteDBClusterSnapshot, ModifyDBClusterSnapshotAttribute, DescribeDBClusterSnapshotAttributes, CreateDBClusterParameterGroup, DescribeDBClusterParameterGroups, DeleteDBClusterParameterGroup, ModifyDBClusterParameterGroup, ResetDBClusterParameterGroup, DescribeDBClusterParameters, ListTagsForResource, AddTagsToResource, RemoveTagsFromResource, DescribeDBEngineVersions, DescribeOrderableDBInstanceOptions, ApplyPendingMaintenanceAction, DescribePendingMaintenanceActions, DescribeCertificates, DescribeEvents | 41 actions; engine versions 5.0.0 and 8.0.0 (families `docdb5.0`/`docdb8.0`) both backed by the official `documentdb-local` container (`ghcr.io/documentdb/documentdb/documentdb-local:latest`, MIT — no MongoDB license concern) — one shared DocumentDB container per cluster, started with its first member; every member (and both cluster endpoints) resolves to it, so pymongo writes through one member are visible through all; the gateway serves TLS with a self-signed certificate (`tls=true&tlsAllowInvalidCertificates=true`) and its `allowTLS` default also accepts plaintext; cold start is slower than mongod (PostgreSQL init on a fresh volume — readiness waits run up to 300 s); container usernames must not start with `documentdb`/`citus`/`pg`/`internal_role`; `FailoverDBCluster` rotates the writer flag, snapshots are metadata-only (`RestoreDBClusterFromSnapshot` yields an empty database); tags actions validate `ResourceName` against live records and return the documented 404 faults; reachable via any `docdb.*` endpoint host since DocDB shares RDS's SigV4 scope |+| **ElastiCache** | CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters, ModifyCacheCluster, RebootCacheCluster, CreateReplicationGroup, DeleteReplicationGroup, DescribeReplicationGroups, ModifyReplicationGroup, IncreaseReplicaCount, DecreaseReplicaCount, CreateCacheSubnetGroup, DescribeCacheSubnetGroups, ModifyCacheSubnetGroup, DeleteCacheSubnetGroup, CreateCacheParameterGroup, DescribeCacheParameterGroups, ModifyCacheParameterGroup, ResetCacheParameterGroup, DeleteCacheParameterGroup, DescribeCacheParameters, DescribeCacheEngineVersions, CreateUser, DescribeUsers, DeleteUser, ModifyUser, CreateUserGroup, DescribeUserGroups, DeleteUserGroup, ModifyUserGroup, ListTagsForResource, AddTagsToResource, RemoveTagsFromResource, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, CreateServerlessCache, DescribeServerlessCaches, ModifyServerlessCache, DeleteServerlessCache, DescribeEvents | `CreateCacheCluster` spins up a real Redis, Valkey, or Memcached Docker container (`Engine=redis`/`valkey`/`memcached`); a serverless cache gets a TLS-only, single-shard cluster-mode Valkey/Redis container whose certificate chains to the CA at `GET /_ministack/elasticache/ca.pem` || **Glue** | CreateDatabase, DeleteDatabase, GetDatabase, GetDatabases, UpdateDatabase, CreateTable, DeleteTable, GetTable, GetTables, UpdateTable, BatchDeleteTable, CreatePartition, DeletePartition, GetPartition, GetPartitions, BatchCreatePartition, BatchGetPartition, CreatePartitionIndex, GetPartitionIndexes, GetColumnStatisticsForTable, UpdateColumnStatisticsForTable, DeleteColumnStatisticsForTable, GetColumnStatisticsForPartition, UpdateColumnStatisticsForPartition, DeleteColumnStatisticsForPartition, CreateConnection, DeleteConnection, GetConnection, GetConnections, CreateCrawler, DeleteCrawler, GetCrawler, GetCrawlers, UpdateCrawler, StartCrawler, StopCrawler, GetCrawlerMetrics, CreateJob, DeleteJob, GetJob, GetJobs, UpdateJob, StartJobRun, GetJobRun, GetJobRuns, BatchStopJobRun, CreateTrigger, GetTrigger, DeleteTrigger, UpdateTrigger, StartTrigger, StopTrigger, ListTriggers, BatchGetTriggers, GetTriggers, CreateWorkflow, GetWorkflow, DeleteWorkflow, UpdateWorkflow, StartWorkflowRun, CreateUserDefinedFunction, UpdateUserDefinedFunction, DeleteUserDefinedFunction, GetUserDefinedFunction, GetUserDefinedFunctions, CreateSecurityConfiguration, DeleteSecurityConfiguration, GetSecurityConfiguration, GetSecurityConfigurations, CreateClassifier, GetClassifier, GetClassifiers, DeleteClassifier, TagResource, UntagResource, GetTags | Python shell jobs actually execute via subprocess; Spark jobs run on the official `amazon/aws-glue-libs` PySpark image (`GlueVersion: 4.0` / `3.0`) on MiniStack's Docker network; Glue-backed Iceberg REST catalog at `/iceberg` (signed with the `glue` credential scope, prefix `catalogs/{catalog}`) — read path for tables whose `metadata_location` parameter points at a metadata.json on MiniStack S3, e.g. DuckDB `ATTACH ... (TYPE iceberg, ENDPOINT 'localhost:4566/iceberg', AUTHORIZATION_TYPE 'sigv4')` with `USE_SSL=1` || **S3 Tables** | CreateTableBucket, ListTableBuckets, GetTableBucket, DeleteTableBucket, CreateNamespace, ListNamespaces, GetNamespace, DeleteNamespace, CreateTable, ListTables, GetTable, DeleteTable, GetTableMetadataLocation, UpdateTableMetadataLocation | Iceberg-format tables; embedded Iceberg REST catalog at `/iceberg` so Spark jobs (`spark.sql.catalog.*.type=rest`) can create / load / commit without an external catalog, each catalog scoped to the table bucket ARN in its prefix and commits checked against their update requirements; data files in S3, metadata in memory || **Athena** | StartQueryExecution, GetQueryExecution, GetQueryResults, StopQueryExecution, ListQueryExecutions, BatchGetQueryExecution, CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, UpdateWorkGroup, CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries, BatchGetNamedQuery, CreateDataCatalog, GetDataCatalog, ListDataCatalogs, DeleteDataCatalog, UpdateDataCatalog, CreatePreparedStatement, GetPreparedStatement, DeletePreparedStatement, ListPreparedStatements, GetDatabase, ListDatabases, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; databases and tables come from the Glue Data Catalog, and `CREATE EXTERNAL TABLE` / `DROP TABLE` change it; result pagination; column type metadata |@@ -896,9 +896,6 @@ come from `repositoryCredentials.credentialsParameter` (a Secrets Manager secret| `DSQL_BASE_PORT` | `25432` | Starting host port for Aurora DSQL cluster proxies (one port per cluster) || `DSQL_STRICT` | `0` | Set `1` to run a real Postgres container per DSQL cluster (requires Docker; capped by a fixed port window off `DSQL_BASE_PORT`, default 30 — further clusters are metadata-only stubs). Default `0` is control-plane-only || `DSQL_PG_IMAGE` | `postgres:16-alpine` | Image used for per-cluster DSQL backend containers |-| `DOCDB_BASE_PORT` | `27117` | Starting host port for DocumentDB containers (one shared DocumentDB container per DB cluster) |-| `DOCDB_PERSIST` | `0` | Set `1` to use Docker named volumes for DocumentDB cluster containers instead of tmpfs. Deleting the final member stops the container but keeps its volume; only `DeleteDBCluster` removes storage. Note `DOCDB_TMPFS_SIZE` (default `256m`) — a DocumentDB data directory is a full PostgreSQL cluster, so raise the tmpfs size for larger datasets |-| `DOCDB_TMPFS_SIZE` | `256m` | Size of the tmpfs mount backing DocumentDB storage when `DOCDB_PERSIST=0`; raise for larger datasets || `DSQL_PERSIST` | `0` | Set `1` to use Docker named volumes for DSQL backend containers instead of tmpfs || `DOCKER_NETWORK` | _(unset)_ | Docker network for all container-backed services (RDS, DSQL, EKS, ElastiCache, Lambda). Set to your Docker Compose network name so containers can reach each other. Replaces `LAMBDA_DOCKER_NETWORK` || `ELASTICACHE_BASE_PORT` | `16379` | Starting host port for ElastiCache containers |diff --git a/ministack/core/router.py b/ministack/core/router.pyindex d50e522b..7b2937b8 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -124,13 +124,8 @@ SERVICE_PATTERNS = {"path_patterns": [r"^/2025-09-09/microvm"],"host_patterns": [r"lambda-microvms\."],},- # DocumentDB shares RDS's signing name (`rds`) and Query API version, so- # credential-scope routing cannot tell the two apart (real AWS serves both- # from one control plane). detect_service() therefore dispatches- # `rds`-scoped requests on the endpoint host: docdb.*/documentdb.* hosts- # are DocumentDB, everything else is RDS.+ # DocumentDB signs as `rds`; detect_service() claims its requests by host or content."documentdb": {- "target_prefixes": ["AmazonRDS", "DocDB"],"host_patterns": [r"docdb\.", r"documentdb\."],},"lambda": {@@ -690,6 +685,12 @@ _LIST_SIGNING_JOBS_PARAMS = frozenset({_UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")+def _documentdb_claims(params):+ from ministack.services.documentdb import claims_request++ return claims_request(params)++def detect_service(method: str, path: str, headers: dict, query_params: dict) -> str:"""Detect which AWS service a request is targeting."""host = headers.get("host", "")@@ -790,10 +791,10 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->if svc_name == "lambda" and _LAMBDA_CORE_PATH_RE.match(path):return "lambda-core"if svc_name in SERVICE_PATTERNS:- # DocDB signs as `rds` (shared signing name and Query API- # version), so before returning RDS give DocumentDB's host- # patterns first claim — see the SERVICE_PATTERNS note above.- if svc_name == "rds" and re.search(r"^(docdb|documentdb)\.", host):+ # DocumentDB signs as `rds`: a docdb host, Engine=docdb, or a+ # DocumentDB cluster or instance named in the request is DocumentDB's.+ if svc_name == "rds" and (re.search(r"^(docdb|documentdb)\.", host)+ or _documentdb_claims(query_params)):return "documentdb"return svc_name# Map common credential scope namesdiff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 7ba69d64..bb7c560b 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -825,6 +825,10 @@ _CUSTOM_NAME_REPLACEMENT = {},"AWS::RDS::DBParameterGroup": {"name": "DBParameterGroupName"},"AWS::RDS::DBClusterParameterGroup": {"name": "DBClusterParameterGroupName"},+ "AWS::DocDB::DBCluster": {"name": "DBClusterIdentifier"},+ "AWS::DocDB::DBInstance": {"name": "DBInstanceIdentifier"},+ "AWS::DocDB::DBSubnetGroup": {"name": "DBSubnetGroupName"},+ "AWS::DocDB::DBClusterParameterGroup": {"name": "Name"},# Type and WorkflowName are "Update requires: Replacement" in the# aws-resource-glue-trigger reference."AWS::Glue::Trigger": {@@ -1138,11 +1142,13 @@ _STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {"AWS::Logs::LogGroup": ("Tags", "list"),"AWS::OpenSearchService::Domain": ("Tags", "list"),"AWS::RDS::DBInstance": ("Tags", "list"),- "AWS::DocDB::DBCluster": ("Tags", "list"),- "AWS::DocDB::DBInstance": ("Tags", "list"),"AWS::RDS::DBClusterParameterGroup": ("Tags", "list"),"AWS::RDS::DBParameterGroup": ("Tags", "list"),"AWS::RDS::DBSubnetGroup": ("Tags", "list"),+ "AWS::DocDB::DBCluster": ("Tags", "list"),+ "AWS::DocDB::DBInstance": ("Tags", "list"),+ "AWS::DocDB::DBSubnetGroup": ("Tags", "list"),+ "AWS::DocDB::DBClusterParameterGroup": ("Tags", "list"),"AWS::SNS::Topic": ("Tags", "list"),"AWS::SQS::Queue": ("Tags", "list"),"AWS::SSM::Parameter": ("Tags", "map"),@@ -11205,205 +11211,6 @@ def _rds_db_instance_delete(physical_id, props):# ----------------------------------------------------------------------------# DocumentDB (AWS::DocDB::*)-# -----------------------------------------------------------------------------def _docdb_extract_error(resp):- """Pull (code, message) out of a documentdb service XML error tuple."""- body = resp[2]- if isinstance(body, bytes):- body = body.decode("utf-8", errors="replace")- code_m = re.search(r"<Code>([^<]+)</Code>", body)- msg_m = re.search(r"<Message>([^<]+)</Message>", body)- return (- code_m.group(1) if code_m else "Unknown",- msg_m.group(1) if msg_m else repr(body),- )---def _docdb_dbsubnetgroup_create(logical_id, props, stack_name):- name = props.get("DBSubnetGroupName") or _physical_name(- stack_name, logical_id, lowercase=True, max_len=255)- params = {- "DBSubnetGroupName": name,- "DBSubnetGroupDescription": props.get(- "DBSubnetGroupDescription", "Managed by CloudFormation"),- }- subnet_ids = props.get("SubnetIds") or []- if isinstance(subnet_ids, str):- subnet_ids = [subnet_ids]- for i, sid in enumerate(subnet_ids, 1):- params[f"SubnetIds.member.{i}"] = sid- resp = _docdb._create_subnet_group(params)- if resp[0] >= 400:- code, msg = _docdb_extract_error(resp)- raise ValueError(f"AWS::DocDB::DBSubnetGroup create failed: {code}: {msg}")- sg = _docdb._subnet_groups[name]- return name, {"DBSubnetGroup.Arn": sg["DBSubnetGroupArn"]}---def _docdb_dbsubnetgroup_delete(physical_id, props):- _docdb._delete_subnet_group({"DBSubnetGroupName": physical_id})---def _docdb_dbcluster_create(logical_id, props, stack_name):- cluster_id = props.get("DBClusterIdentifier") or _physical_name(- stack_name, logical_id, lowercase=True, max_len=63)- params = {- "DBClusterIdentifier": cluster_id,- "EngineVersion": props.get("EngineVersion") or "",- "MasterUsername": props.get("MasterUsername") or "",- "MasterUserPassword": props.get("MasterUserPassword") or "",- "DBSubnetGroupName": props.get("DBSubnetGroupName") or "",- "PreferredMaintenanceWindow": props.get("PreferredMaintenanceWindow") or "",- "BackupRetentionPeriod": str(props.get("BackupRetentionPeriod", "")),- "DeletionProtection": "true" if props.get("DeletionProtection") else "false",- "StorageEncrypted": "true" if props.get("StorageEncrypted") else "false",- "KmsKeyId": props.get("KmsKeyId") or "",- "Port": str(props.get("Port") or ""),- }- for i, az in enumerate(props.get("AvailabilityZones") or [], 1):- params[f"AvailabilityZones.member.{i}"] = az- resp = _docdb._create_db_cluster(params)- if resp[0] >= 400:- code, msg = _docdb_extract_error(resp)- raise ValueError(f"AWS::DocDB::DBCluster create failed: {code}: {msg}")- cluster = _docdb._clusters[cluster_id]- # CDK L2 sets ManageMasterUserPassword with the credentials in a- # Secrets Manager secret the template Fn::Join-dynamic-references into- # MasterUsername/MasterUserPassword; surface the linked secret the way- # the real API does (MasterUserSecretArn passthrough as well).- secret_arn = props.get("MasterUserSecretArn") or (- props.get("MasterUserSecret", {}).get("SecretArn")- if isinstance(props.get("MasterUserSecret"), dict) else None)- if secret_arn:- cluster["MasterUserSecret"] = {"SecretArn": secret_arn, "SecretStatus": "active"}- return cluster_id, {- "Endpoint": cluster["Endpoint"],- "Port": str(cluster["Port"]),- "Endpoint.Address": cluster["Endpoint"],- "Endpoint.Port": str(cluster["Port"]),- "ReadEndpoint.Address": cluster["ReaderEndpoint"],- "ClusterResourceId": cluster["DbClusterResourceId"],- "Arn": cluster["DBClusterArn"],- }---def _docdb_dbcluster_delete(physical_id, props):- resp = _docdb._delete_db_cluster({"DBClusterIdentifier": physical_id})- if resp[0] >= 400:- code, msg = _docdb_extract_error(resp)- if code == "DBClusterNotFoundFault":- return- raise ValueError(f"AWS::DocDB::DBCluster delete failed: {code}: {msg}")---def _docdb_dbinstance_create(logical_id, props, stack_name):- db_id = props.get("DBInstanceIdentifier") or _physical_name(- stack_name, logical_id, lowercase=True, max_len=63)- params = {- "DBInstanceIdentifier": db_id,- "DBInstanceClass": props.get("DBInstanceClass") or "db.t3.medium",- "Engine": "docdb",- "DBClusterIdentifier": props.get("DBClusterIdentifier") or "",- "EngineVersion": props.get("EngineVersion") or "",- "AvailabilityZone": props.get("AvailabilityZone") or "",- "AutoMinorVersionUpgrade": (- "false" if props.get("AutoMinorVersionUpgrade") is False else "true"),- "PreferredMaintenanceWindow": props.get("PreferredMaintenanceWindow") or "",- "PromotionTier": str(props.get("PromotionTier", "")),- }- resp = _docdb._create_db_instance(params)- if resp[0] >= 400:- code, msg = _docdb_extract_error(resp)- raise ValueError(f"AWS::DocDB::DBInstance create failed: {code}: {msg}")- inst = _docdb._instances[db_id]- endpoint = inst.get("Endpoint") or {}- return db_id, {- "Endpoint.Address": endpoint.get("Address", ""),- "Endpoint.Port": str(endpoint.get("Port", "")),- "DBInstanceArn": inst["DBInstanceArn"],- }---def _docdb_dbinstance_delete(physical_id, props):- resp = _docdb._delete_db_instance({"DBInstanceIdentifier": physical_id})- if resp[0] >= 400:- code, msg = _docdb_extract_error(resp)- if code == "DBInstanceNotFound":- return- raise ValueError(f"AWS::DocDB::DBInstance delete failed: {code}: {msg}")---def _docdb_dbclusterparametergroup_create(logical_id, props, stack_name):- name = props.get("DBClusterParameterGroupName") or _physical_name(- stack_name, logical_id, lowercase=True, max_len=255)- params = {- "DBClusterParameterGroupName": name,- "DBParameterGroupFamily": props.get("Family") or "docdb5.0",- "Description": props.get("Description")- or f"Managed by CloudFormation for stack {stack_name}",- }- resp = _docdb._create_db_cluster_parameter_group(params)- if resp[0] >= 400:- code, msg = _docdb_extract_error(resp)- raise ValueError(- f"AWS::DocDB::DBClusterParameterGroup create failed: {code}: {msg}")- for i, param in enumerate(props.get("Parameters") or [], 1):- if not isinstance(param, dict) or not param.get("ParameterName"):- continue- modify = {- "DBClusterParameterGroupName": name,- f"Parameters.member.{i}.ParameterName": param["ParameterName"],- f"Parameters.member.{i}.ParameterValue": param.get("ParameterValue", ""),- f"Parameters.member.{i}.ApplyMethod": param.get("ApplyMethod", "immediate"),- }- _docdb._modify_db_cluster_parameter_group(modify)- return name, {"DBClusterParameterGroup.Arn":- _docdb._db_cluster_param_groups[name]["DBClusterParameterGroupArn"]}---def _docdb_dbclusterparametergroup_delete(physical_id, props):- _docdb._delete_db_cluster_parameter_group(- {"DBClusterParameterGroupName": physical_id})---def _sm_secret_target_attachment_create(logical_id, props, stack_name):- """AWS::SecretsManager::SecretTargetAttachment.-- Links a secret to a provisioned target (DocumentDB cluster here); on AWS- this injects the target's connection info into the secret payload. The- secret and the DocDB cluster already hold their records, so the link- stamps the target's details onto the secret record and reports the- secret's ARN, matching what CDK reads back.- """- secret_id = props.get("SecretId") or ""- target_id = props.get("TargetId") or ""- target_type = props.get("TargetType") or ""- secret = _sm._secrets.get(secret_id)- cluster = _docdb._clusters.get(target_id)- if secret is not None and cluster is not None:- secret.setdefault("Versions", {})- current = None- for ver in secret["Versions"].values():- if "AWSCURRENT" in ver.get("Stages", []):- current = ver- break- if current is not None:- try:- payload = json.loads(current.get("SecretString") or "{}")- except ValueError:- payload = {}- payload.setdefault("engine", "docdb")- payload.setdefault("host", cluster.get("Endpoint", ""))- payload.setdefault("port", cluster.get("Port", 27017))- payload.setdefault("dbClusterIdentifier", target_id)- current["SecretString"] = json.dumps(payload)- return f"{secret_id}-{target_type}", {"SecretArn": secret_id}---def _sm_secret_target_attachment_delete(physical_id, props):- pass # the link record is stateless; the secret and target delete separately# RDS DBSubnetGroup / DBParameterGroup / DBClusterParameterGroup# ---------------------------------------------------------------------------@@ -11575,6 +11382,138 @@ def _rds_cluster_param_group_delete(physical_id, props):_rds._delete_db_cluster_param_group({"DBClusterParameterGroupName": physical_id})+# ---------------------------------------------------------------------------+# DocumentDB (AWS::DocDB::*): RDS clusters and instances with Engine docdb+# ---------------------------------------------------------------------------++_DOCDB_CLUSTER_PROPS = (+ "EngineVersion", "MasterUsername", "MasterUserPassword", "DBSubnetGroupName",+ "DBClusterParameterGroupName", "PreferredBackupWindow", "PreferredMaintenanceWindow", "KmsKeyId",+ "StorageType", "NetworkType", "BackupRetentionPeriod", "Port", "DeletionProtection",+ "StorageEncrypted", "CopyTagsToSnapshot", "ManageMasterUserPassword", "MasterUserSecretKmsKeyId",+ "AvailabilityZones", "VpcSecurityGroupIds", "EnableCloudwatchLogsExports",+)+_DOCDB_CLUSTER_MODIFIABLE = (+ "EngineVersion", "MasterUserPassword", "DBClusterParameterGroupName", "PreferredBackupWindow",+ "PreferredMaintenanceWindow", "BackupRetentionPeriod", "Port", "DeletionProtection",+ "CopyTagsToSnapshot", "VpcSecurityGroupIds", "StorageType", "ManageMasterUserPassword",+ "MasterUserSecretKmsKeyId",+)+_DOCDB_INSTANCE_PROPS = (+ "DBInstanceClass", "AvailabilityZone", "PreferredMaintenanceWindow", "AutoMinorVersionUpgrade",+ "CACertificateIdentifier", "EnablePerformanceInsights",+)+_DOCDB_INSTANCE_MODIFIABLE = (+ "DBInstanceClass", "PreferredMaintenanceWindow", "AutoMinorVersionUpgrade",+ "CACertificateIdentifier", "EnablePerformanceInsights",+)+++def _docdb_sync_tags(arn, old_props, new_props, resource_type):+ old_tags = _tag_map(old_props.get("Tags"))+ new_tags = _tag_map(new_props.get("Tags"))+ removed = sorted(old_tags.keys() - new_tags.keys())+ if removed:+ _rds_call(_docdb._remove_tags, {"ResourceName": arn, **_ec_query({"TagKeys": removed})},+ resource_type, "untag")+ changed = {k: v for k, v in new_tags.items() if old_tags.get(k) != v}+ if changed:+ _rds_call(_docdb._add_tags, {"ResourceName": arn, **_ec_query({+ "Tags": [{"Key": k, "Value": v} for k, v in changed.items()]})}, resource_type, "tag")+++def _docdb_cluster_attrs(cluster):+ return {+ "ClusterResourceId": cluster["DbClusterResourceId"],+ "Endpoint": cluster["Endpoint"],+ "Port": str(cluster["Port"]),+ "ReadEndpoint": cluster["ReaderEndpoint"],+ }+++def _docdb_cluster_create(logical_id, props, stack_name):+ cluster_id = props.get("DBClusterIdentifier") or _physical_name(+ stack_name, logical_id, lowercase=True, max_len=63)+ _rds_call(_docdb._create_db_cluster, {+ "DBClusterIdentifier": cluster_id, "Engine": "docdb",+ **_ec_query({k: props[k] for k in _DOCDB_CLUSTER_PROPS if props.get(k) not in (None, "")}),+ **_ec_query({"Tags": props.get("Tags") or []}),+ }, "AWS::DocDB::DBCluster", "create")+ return cluster_id, _docdb_cluster_attrs(_docdb._clusters[cluster_id])+++def _docdb_cluster_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ cluster = _docdb._clusters.get(physical_id)+ if cluster is None:+ return _docdb_cluster_create(logical_id or physical_id, new_props, stack_name)+ changed = {k: new_props.get(k) for k in _DOCDB_CLUSTER_MODIFIABLE+ if old_props.get(k) != new_props.get(k) and new_props.get(k) not in (None, "")}+ if changed:+ _rds_call(_docdb._modify_db_cluster, {+ "DBClusterIdentifier": physical_id, "ApplyImmediately": "true", **_ec_query(changed),+ }, "AWS::DocDB::DBCluster", "update")+ _docdb_sync_tags(cluster["DBClusterArn"], old_props, new_props, "AWS::DocDB::DBCluster")+ return physical_id, _docdb_cluster_attrs(cluster)+++def _docdb_cluster_delete(physical_id, props):+ if physical_id in _docdb._clusters:+ _rds_call(_docdb._delete_db_cluster, {"DBClusterIdentifier": physical_id, "SkipFinalSnapshot": "true"},+ "AWS::DocDB::DBCluster", "delete")+++def _docdb_instance_attrs(instance):+ endpoint = instance.get("Endpoint") or {}+ return {"Endpoint": endpoint.get("Address", ""), "Port": str(endpoint.get("Port", ""))}+++def _docdb_instance_create(logical_id, props, stack_name):+ db_id = props.get("DBInstanceIdentifier") or _physical_name(+ stack_name, logical_id, lowercase=True, max_len=63)+ _rds_call(_docdb._create_db_instance, {+ "DBInstanceIdentifier": db_id, "Engine": "docdb",+ "DBClusterIdentifier": props.get("DBClusterIdentifier", ""),+ **_ec_query({k: props[k] for k in _DOCDB_INSTANCE_PROPS if props.get(k) not in (None, "")}),+ **_ec_query({"Tags": props.get("Tags") or []}),+ }, "AWS::DocDB::DBInstance", "create")+ return db_id, _docdb_instance_attrs(_docdb._instances[db_id])+++def _docdb_instance_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ instance = _docdb._instances.get(physical_id)+ if instance is None:+ return _docdb_instance_create(logical_id or physical_id, new_props, stack_name)+ changed = {k: new_props.get(k) for k in _DOCDB_INSTANCE_MODIFIABLE+ if old_props.get(k) != new_props.get(k) and new_props.get(k) not in (None, "")}+ if changed:+ _rds_call(_docdb._modify_db_instance, {+ "DBInstanceIdentifier": physical_id, "ApplyImmediately": "true", **_ec_query(changed),+ }, "AWS::DocDB::DBInstance", "update")+ _docdb_sync_tags(instance["DBInstanceArn"], old_props, new_props, "AWS::DocDB::DBInstance")+ return physical_id, _docdb_instance_attrs(instance)+++def _docdb_instance_delete(physical_id, props):+ if physical_id in _docdb._instances:+ _rds_call(_docdb._delete_db_instance, {"DBInstanceIdentifier": physical_id},+ "AWS::DocDB::DBInstance", "delete")+++def _docdb_param_group_props(props):+ """AWS::DocDB::DBClusterParameterGroup names the group ``Name``."""+ return {**{k: v for k, v in props.items() if k != "Name"},+ "DBClusterParameterGroupName": props.get("Name")}+++def _docdb_cluster_param_group_create(logical_id, props, stack_name):+ return _rds_cluster_param_group_create(logical_id, _docdb_param_group_props(props), stack_name)+++def _docdb_cluster_param_group_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ return _rds_cluster_param_group_update(physical_id, _docdb_param_group_props(old_props),+ _docdb_param_group_props(new_props), stack_name, logical_id)++# ---------------------------------------------------------------------------# SecretsManager SecretTargetAttachment# ---------------------------------------------------------------------------@@ -11584,13 +11523,15 @@ _SM_TARGET_KEYS = ("engine", "host", "port", "dbname")def _sm_target_connection(target_type, target_id):"""The connection keys the attachment writes into the secret JSON."""- if target_type == "AWS::RDS::DBInstance":- record = _rds._instances.get(target_id)+ if target_type in ("AWS::RDS::DBInstance", "AWS::DocDB::DBInstance"):+ store = _docdb._instances if target_type == "AWS::DocDB::DBInstance" else _rds._instances+ record = store.get(target_id)if record:endpoint = record.get("Endpoint") or {}host, port, dbname = endpoint.get("Address"), endpoint.get("Port"), record.get("DBName")- elif target_type == "AWS::RDS::DBCluster":- record = _rds._clusters.get(target_id)+ elif target_type in ("AWS::RDS::DBCluster", "AWS::DocDB::DBCluster"):+ store = _docdb._clusters if target_type == "AWS::DocDB::DBCluster" else _rds._clusters+ record = store.get(target_id)if record:host, port, dbname = record.get("Endpoint"), record.get("Port"), record.get("DatabaseName")else:@@ -11600,7 +11541,7 @@ def _sm_target_connection(target_type, target_id):raise ValueError(f"AWS::SecretsManager::SecretTargetAttachment: {target_type} "f"{target_id} not found")engine = record.get("Engine", "")- for prefix, name in (("aurora-postgresql", "postgres"), ("aurora", "mysql"),+ for prefix, name in (("docdb", "mongo"), ("aurora-postgresql", "postgres"), ("aurora", "mysql"),("oracle", "oracle"), ("sqlserver", "sqlserver")):if engine.startswith(prefix):engine = name@@ -14078,6 +14019,12 @@ def _location_tracker_delete(physical_id, props):# Per type, the create-only properties (Always): a change replaces the resource._REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {+ "AWS::DocDB::DBCluster": ("AvailabilityZones", "DBClusterIdentifier", "DBSubnetGroupName", "KmsKeyId",+ "MasterUsername", "SnapshotIdentifier", "SourceDBClusterIdentifier",+ "StorageEncrypted"),+ "AWS::DocDB::DBInstance": ("AvailabilityZone", "DBClusterIdentifier", "DBInstanceIdentifier"),+ "AWS::DocDB::DBSubnetGroup": ("DBSubnetGroupName",),+ "AWS::DocDB::DBClusterParameterGroup": ("Description", "Family", "Name"),"AWS::DynamoDB::Table": ("TableName", "ImportSourceSpecification"),"AWS::StepFunctions::StateMachine": ("StateMachineName", "StateMachineType"),"AWS::Cognito::UserPoolGroup": ("GroupName", "UserPoolId"),@@ -14965,18 +14912,6 @@ _RESOURCE_HANDLERS = {"AWS::RDS::DBInstance": {"create": _rds_db_instance_create, "update": _rds_db_instance_update,"update_with_logical_id": True, "delete": _rds_db_instance_delete,"snapshot": _rds_db_instance_snapshot},- "AWS::DocDB::DBSubnetGroup": {- "create": _docdb_dbsubnetgroup_create, "delete": _docdb_dbsubnetgroup_delete,- },- "AWS::DocDB::DBCluster": {"create": _docdb_dbcluster_create, "delete": _docdb_dbcluster_delete},- "AWS::DocDB::DBInstance": {"create": _docdb_dbinstance_create, "delete": _docdb_dbinstance_delete},- "AWS::DocDB::DBClusterParameterGroup": {- "create": _docdb_dbclusterparametergroup_create,- "delete": _docdb_dbclusterparametergroup_delete,- },- "AWS::SecretsManager::SecretTargetAttachment": {- "create": _sm_secret_target_attachment_create,- "delete": _sm_secret_target_attachment_delete,"AWS::RDS::DBSubnetGroup": {"create": _rds_subnet_group_create,"update": _rds_subnet_group_update,@@ -14995,6 +14930,22 @@ _RESOURCE_HANDLERS = {"update_with_logical_id": True,"delete": _rds_cluster_param_group_delete,},+ "AWS::DocDB::DBCluster": {"create": _docdb_cluster_create, "update": _docdb_cluster_update,+ "update_with_logical_id": True, "delete": _docdb_cluster_delete},+ "AWS::DocDB::DBInstance": {"create": _docdb_instance_create, "update": _docdb_instance_update,+ "update_with_logical_id": True, "delete": _docdb_instance_delete},+ "AWS::DocDB::DBSubnetGroup": {+ "create": _rds_subnet_group_create,+ "update": _rds_subnet_group_update,+ "update_with_logical_id": True,+ "delete": _rds_subnet_group_delete,+ },+ "AWS::DocDB::DBClusterParameterGroup": {+ "create": _docdb_cluster_param_group_create,+ "update": _docdb_cluster_param_group_update,+ "update_with_logical_id": True,+ "delete": _rds_cluster_param_group_delete,+ },"AWS::SecretsManager::SecretTargetAttachment": {"create": _sm_target_attachment_create,"update": _sm_target_attachment_update,diff --git a/ministack/services/documentdb.py b/ministack/services/documentdb.pyindex d1bee6b0..4741b2e2 100644--- a/ministack/services/documentdb.py+++ b/ministack/services/documentdb.py@@ -1,78 +1,9 @@-# One file per CONTRIBUTING.md, so pylint's file-shape limits and the-# defensive Docker-boundary catches are suppressed here only.-# pylint: disable=too-many-lines,broad-exception-caught,too-many-locals-# pylint: disable=too-many-branches,too-many-statements,too-many-return-statements-# pylint: disable=too-many-arguments,too-many-positional-arguments-"""Amazon DocumentDB (DocDB) service emulator.--Control plane emulated in-process (Query API ``Action=`` form bodies plus-``application/x-amz-json-1.*`` JSON bodies for the same actions); data plane is-a real DocumentDB engine — when Docker is available, cluster compute runs in-the official ``documentdb-local`` container (``ghcr.io/documentdb/-documentdb/documentdb-local:latest``, MIT licensed) and every response-endpoint is wire-connectable with pymongo or any MongoDB driver. There is no-in-process emulation of Mongo commands.--The container's gateway always serves TLS (self-signed certificate; connect-with ``tls=true&tlsAllowInvalidCertificates=true``) but the default-``tlsMode`` is ``allowTLS``, so plaintext connections are accepted too. The-gateway additionally accepts plaintext in ``disabled`` mode.--Engine versions (single source of truth: ``DOCDB_ENGINE_VERSIONS``):- - 5.0.0 → family ``docdb5.0``- - 8.0.0 → family ``docdb8.0``-Both map to the same backing image — the image tracks DocumentDB releases and-speaks MongoDB 3.6-8.0 API. 5.0.0 is the default, matching the AWS SDK-default. Images honor ``MINISTACK_IMAGE_PREFIX``.--Cold start is slower than mongod: first boot initializes a PostgreSQL data-directory and the entrypoint can wait up to 600 s, so readiness waits run up-to 300 s.--Container usernames must not start (case-insensitive) with ``documentdb``,-``citus``, ``pg`` or ``internal_role`` — the container refuses to come up-otherwise and the instance ends ``failed``.--Cluster model mirrors RDS/Aurora: one shared DocumentDB container per DB-cluster. The first member created on a cluster starts it; later members are-control-plane records aliasing the same endpoint, so data written through one-member is visible through all members and through both cluster endpoints.-Deleting the last member removes its container but keeps the named volume-(under ``DOCDB_PERSIST=1``), so a later member restarts onto preserved data;-only ``DeleteDBCluster`` removes container and storage. Standalone instances-(created without ``DBClusterIdentifier`` over raw HTTP) keep their own-per-instance container.--Supported actions (aligned with ``_ACTION_MAP``):- CreateDBInstance, DeleteDBInstance, DescribeDBInstances, ModifyDBInstance,- StartDBInstance, StopDBInstance, RebootDBInstance,- CreateDBCluster, DeleteDBCluster, DescribeDBClusters, ModifyDBCluster,- StartDBCluster, StopDBCluster, FailoverDBCluster, RestoreDBClusterFromSnapshot,- CreateDBSubnetGroup, DeleteDBSubnetGroup, DescribeDBSubnetGroups,- CreateDBSnapshot*, DeleteDBSnapshot*, DescribeDBSnapshots*,- CreateDBClusterSnapshot, DescribeDBClusterSnapshots, DeleteDBClusterSnapshot,- ModifyDBClusterSnapshotAttribute, DescribeDBClusterSnapshotAttributes,- CreateDBClusterParameterGroup, DescribeDBClusterParameterGroups,- DeleteDBClusterParameterGroup, ModifyDBClusterParameterGroup,- ResetDBClusterParameterGroup, DescribeDBClusterParameters,- ListTagsForResource, AddTagsToResource, RemoveTagsFromResource,- DescribeDBEngineVersions, DescribeOrderableDBInstanceOptions,- ApplyPendingMaintenanceAction, DescribePendingMaintenanceActions,- DescribeCertificates, DescribeEvents.-- * Create/Delete/DescribeDBSnapshots do not exist in the real DocumentDB API- (DocDB has only cluster snapshots). They are served for legacy direct-HTTP- callers but cannot be reached through the boto3 ``docdb`` client.--Snapshots are metadata-only: they record the cluster/instance configuration-and tags but contain no database dump, so ``RestoreDBClusterFromSnapshot``-yields an empty database.--Env vars: DOCDB_BASE_PORT (default 27117), DOCDB_PERSIST, DOCDB_TMPFS_SIZE,-DOCKER_NETWORK.--References:-- AWS DocDB API: https://docs.aws.amazon.com/documentdb/latest/APIReference/+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).+"""Amazon DocumentDB: DB clusters and instances, each cluster backed by a documentdb-local container.++DocumentDB requests arrive signed for ``rds``; the router hands this module the ones that create or+name a DocumentDB cluster or instance. Subnet and parameter groups are shared with RDS."""import copy@@ -99,6 +30,7 @@ from ministack.core.responses import (get_region,new_uuid,)+from ministack.services import rds as _rdslogger = logging.getLogger("documentdb")@@ -109,27 +41,18 @@ DOCDB_TMPFS_SIZE = os.environ.get("DOCDB_TMPFS_SIZE", "256m")DOCDB_PERSIST = os.environ.get("DOCDB_PERSIST", "0").lower() in ("1", "true", "yes")DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "")-# Single source of truth for DocumentDB engine versions: (version, parameter-# group family). 5.0.0 stays the default per the AWS SDK default.-DOCDB_ENGINE_VERSIONS = [("5.0.0", "docdb5.0"), ("8.0.0", "docdb8.0")]-_DOCDB_ENGINE_VERSION_SET = {version for version, _ in DOCDB_ENGINE_VERSIONS}-DEFAULT_ENGINE_VERSION = "5.0.0"+# Creatable versions; minor versions exist from 5.0 on. The default is the latest major.+DOCDB_ENGINE_VERSIONS = ["3.6.0", "4.0.0", "5.0.0", "5.0.1", "5.0.2", "8.0.0", "8.0.1", "8.0.2"]+_DOCDB_ENGINE_VERSION_SET = set(DOCDB_ENGINE_VERSIONS)+DEFAULT_ENGINE_VERSION = "8.0.0"_instances = AccountRegionScopedDict()_clusters = AccountRegionScopedDict()-_subnet_groups = AccountRegionScopedDict()-_snapshots = AccountRegionScopedDict()-_db_cluster_snapshots = AccountRegionScopedDict()-_db_cluster_param_groups = AccountRegionScopedDict()_tags = AccountScopedDict()_port_counter = [BASE_PORT]-# Recorded by ApplyPendingMaintenanceAction, returned by-# DescribePendingMaintenanceActions. In-memory only (not persisted).-_pending_maintenance_actions: list = []--_docker = None # pylint: disable=invalid-name # module-level cache placeholder-_ministack_network = None # pylint: disable=invalid-name # module-level cache placeholder+_docker = None+_ministack_network = None_shared_container_lock = threading.RLock()_port_lock = threading.Lock()@@ -140,55 +63,25 @@ _port_lock = threading.Lock()# ---------------------------------------------------------------------------def get_state():- """- Return a persistable snapshot of all DocumentDB state.-- [1] Reaches into the scoped-dict ``_data`` maps on purpose: non-restorable- Docker container ids must be stripped from the copies.-- Returns:- dict: Store name → record mapping, plus the port counter. Non-- restorable fields (Docker container ids) are stripped; clusters- keep their endpoint/port/volume metadata so warm boot can reattach- to surviving containers and volumes.- """+ """Return a persistable snapshot of all DocumentDB state."""with _shared_container_lock:- # See note [1] in the docstring: the strip below is deliberate.instances = copy.deepcopy(_instances)clusters = copy.deepcopy(_clusters)state = {"instances": instances,"clusters": clusters,- "subnet_groups": copy.deepcopy(_subnet_groups),- "snapshots": copy.deepcopy(_snapshots),- "db_cluster_snapshots": copy.deepcopy(_db_cluster_snapshots),- "db_cluster_param_groups": copy.deepcopy(_db_cluster_param_groups),"tags": copy.deepcopy(_tags),"port_counter": _port_counter[0],}- for key in list(instances._data): # pylint: disable=protected-access # see note [1]- instances._data[key].pop("_docker_container_id", None) # pylint: disable=protected-access # see note [1]- for key in list(clusters._data): # pylint: disable=protected-access # see note [1]- clusters._data[key].pop("_shared_container_id", None) # pylint: disable=protected-access # see note [1]+ for key in list(instances._data):+ instances._data[key].pop("_docker_container_id", None)+ for key in list(clusters._data):+ clusters._data[key].pop("_shared_container_id", None)return statedef load_persisted_state(data):- """- Load persisted state and respawn backing containers.-- Instances and clusters come back marked ``creating`` while daemon threads- restart their DocumentDB containers (reusing persisted host ports when- still free), then flip to ``available`` once TCP-ready. Stopped resources- stay stopped. Accepts the current ``(account, region, key)``-keyed layout- plus older account-scoped and plain-dict layouts defensively.-- [1] Reaches into the scoped-dict ``_data`` map on purpose: the three- persisted layouts are keyed differently and need record rewrites in- place.-- :param data: Persisted payload produced by :func:`get_state`; may be empty.- """+ """Load persisted state and respawn backing containers."""if not data:return_clusters.update(data.get("clusters", {}))@@ -200,12 +93,8 @@ def load_persisted_state(data):cluster["_shared_container_ready"] = Falseif DOCDB_PERSIST:cluster.setdefault("_shared_volume_name", _cluster_volume_name(cluster_id))- _clusters._data[key] = cluster # pylint: disable=protected-access # see note [1]+ _clusters._data[key] = cluster- _subnet_groups.update(data.get("subnet_groups", {}))- _snapshots.update(data.get("snapshots", {}))- _db_cluster_snapshots.update(data.get("db_cluster_snapshots", {}))- _db_cluster_param_groups.update(data.get("db_cluster_param_groups", {}))_tags.update(data.get("tags", {}))if "port_counter" in data:_port_counter[0] = data["port_counter"]@@ -220,16 +109,16 @@ def load_persisted_state(data):inst["DBInstanceStatus"] = "creating"if DOCDB_PERSIST:inst.setdefault("_docker_volume_name", _instance_volume_name(db_id))- _instances._data[(account_id, region, db_id)] = inst # pylint: disable=protected-access # see note [1]+ _instances._data[(account_id, region, db_id)] = instto_respawn.append((account_id, region, db_id, inst))elif hasattr(instances_data, "_data"):# Legacy account-scoped layout: (account_id, instance_id) keys.- for key, inst in instances_data._data.items(): # pylint: disable=protected-access # see note [1]+ for key, inst in instances_data._data.items():account_id, db_id = keyregion = _record_region(inst)inst["_docker_container_id"] = Noneinst["DBInstanceStatus"] = "creating"- _instances._data[(account_id, region, db_id)] = inst # pylint: disable=protected-access # see note [1]+ _instances._data[(account_id, region, db_id)] = instto_respawn.append((account_id, region, db_id, inst))else:# Legacy plain-dict layout: name → record.@@ -271,9 +160,7 @@ def load_persisted_state(data):def _record_region(record):- """- Store region from an ``arn:aws:rds:<region>:...`` record field.- """+ """Store region from an ``arn:aws:rds:<region>:...`` record field."""for field in ("DBInstanceArn", "DBClusterArn"):parts = (record.get(field) or "").split(":")if len(parts) > 3 and parts[3]:@@ -282,9 +169,7 @@ def _record_region(record):def _record_account(record):- """- Store account id from an ARN-shaped record field.- """+ """Store account id from an ARN-shaped record field."""for field in ("DBInstanceArn", "DBClusterArn"):parts = (record.get(field) or "").split(":")if len(parts) > 4 and parts[4]:@@ -293,12 +178,7 @@ def _record_account(record):def _respawn_cluster_members(account_id, region, cluster_id, members):- """- Restart one cluster's shared container after a warm boot.-- Reuses the persisted host port when it is free, waits for TCP readiness on- the chosen address, then publishes every member ``available``.- """+ """Restart one cluster's shared container after a warm boot."""if account_id:_request_account_id.set(account_id)if region:@@ -356,9 +236,7 @@ def _respawn_cluster_members(account_id, region, cluster_id, members):def _respawn_standalone_instance(account_id, region, db_id, instance):- """- Restart one standalone instance's own container after a warm boot.- """+ """Restart one standalone instance's own container after a warm boot."""if account_id:_request_account_id.set(account_id)if region:@@ -406,9 +284,7 @@ def _respawn_standalone_instance(account_id, region, db_id, instance):def _readiness_target(cluster, start_result):- """- Pick the host:port to probe for a freshly (re)started shared container.- """+ """Pick the host:port to probe for a freshly (re)started shared container."""if start_result.get("readiness_port"):return start_result.get("readiness_host"), start_result.get("readiness_port")endpoint = cluster.get("_shared_endpoint") or {}@@ -422,13 +298,11 @@ def _readiness_target(cluster, start_result):# ---------------------------------------------------------------------------def _get_docker():- """- Return a cached Docker client, or None when Docker is unavailable.- """- global _docker # pylint: disable=global-statement # module-level client cache+ """Return a cached Docker client, or None when Docker is unavailable."""+ global _dockerif _docker is None:try:- import docker # pylint: disable=import-outside-toplevel # optional [full] dep+ import docker_docker = docker.from_env()except Exception:pass@@ -436,10 +310,8 @@ def _get_docker():def _get_ministack_network(docker_client):- """- Detect the Docker network MiniStack itself runs on (if containerized).- """- global _ministack_network # pylint: disable=global-statement # module-level network cache+ """Detect the Docker network MiniStack itself runs on (if containerized)."""+ global _ministack_networkif _ministack_network is not None:return _ministack_network or Noneif DOCKER_NETWORK:@@ -460,14 +332,7 @@ def _get_ministack_network(docker_client):def _wait_for_port(host, port, timeout=300):- """- Block until a TCP connection to host:port succeeds.-- Defaults to 300 s: the DocumentDB container initializes a PostgreSQL data- directory on a cold volume and its entrypoint can wait minutes for the- database, so mongod-style 60 s timeouts stop short. The gateway's listener- accepts TCP in every ``tlsMode``, so TCP probing stays valid.- """+ """Block until a TCP connection to host:port succeeds."""deadline = time.time() + timeoutwhile time.time() < deadline:try:@@ -479,9 +344,7 @@ def _wait_for_port(host, port, timeout=300):def _is_host_port_free(port):- """- True when no listener currently holds the given localhost port.- """+ """True when no listener currently holds the given localhost port."""try:with socket.create_connection(("127.0.0.1", int(port)), timeout=0.5):return False@@ -490,9 +353,7 @@ def _is_host_port_free(port):def _next_port():- """- Allocate the next host port for published containers.- """+ """Allocate the next host port for published containers."""with _port_lock:port = _port_counter[0]_port_counter[0] += 1@@ -500,25 +361,17 @@ def _next_port():def _cluster_docker_name(cluster_id):- """- Get- s the Docker container name for a cluster's shared DocumentDB contain- er.- """+ """Get s the Docker container name for a cluster's shared DocumentDB contain er."""return f"ministack-docdb-cluster-{cluster_id}"def _cluster_volume_name(cluster_id):- """- Gets the Docker volume name for a cluster's persistent storage.- """+ """Gets the Docker volume name for a cluster's persistent storage."""return f"ministack-docdb-cluster-{cluster_id}-data"def _instance_volume_name(db_id):- """- Gets the Docker volume name for a standalone instance's storage.- """+ """Gets the Docker volume name for a standalone instance's storage."""return f"ministack-docdb-{db_id}-data"@@ -530,15 +383,7 @@ def _launch_documentdb_container(name,data_path,labels,volume_name=None):- """- Run one DocumentDB container and derive its endpoint addresses.-- Returns:- tuple: ``(container_id, internal_address, internal_port,- endpoint_address, endpoint_port)``, or None when the run failed. On the- MiniStack Docker network the endpoint resolves to the container IP and- native port; otherwise to localhost and the published host port.- """+ """Run one DocumentDB container and derive its endpoint addresses."""docker_client = _get_docker()if not docker_client:return None@@ -578,9 +423,7 @@ def _launch_documentdb_container(name,def _remove_stale_owned_container(docker_client, name):- """- Remove a leftover same-name container only when our labels prove ownership.- """+ """Remove a leftover same-name container only when our labels prove ownership."""try:stale = docker_client.containers.get(name)except Exception:@@ -598,28 +441,14 @@ def _remove_stale_owned_container(docker_client, name):# ---------------------------------------------------------------------------def _start_cluster_shared_container(cluster_id, cluster, remove_stale=False):- """- Start (or recreate) the single DocumentDB container owned by a DocDB cluster.-- Cluster members are control-plane records that all point at this- container's endpoint. Shared by first-member creation and warm boot.-- :param cluster_id: Cluster identifier; also names the container and volume.- :param cluster: Cluster record; updated in place with ``_shared_*`` fields.- :param remove_stale: Remove an existing same-name container first.-- Returns:- dict: ``started`` / ``failed`` flags plus readiness host/port.- """+ """Start (or recreate) the single DocumentDB container owned by a DocDB cluster."""engine_version = cluster.get("EngineVersion") or DEFAULT_ENGINE_VERSIONmaster_user = cluster.get("MasterUsername", "root")master_pass = cluster.get("_MasterUserPassword", "password")db_name = cluster.get("DatabaseName") or "admin"def _fallback_endpoint():- """- Returns default endpoint if needed.- """+ """Returns default endpoint if needed."""return {"Address": "localhost","Port": int(cluster.get("Port") or 27017),@@ -703,9 +532,7 @@ def _start_cluster_shared_container(cluster_id, cluster, remove_stale=False):def _restart_cluster_shared_container(cluster_id, cluster):- """- Start a preserved (stopped) shared container without recreating it.- """+ """Start a preserved (stopped) shared container without recreating it."""docker_client = _get_docker()container_id = cluster.get("_shared_container_id")if not docker_client or not container_id:@@ -758,9 +585,7 @@ def _restart_cluster_shared_container(cluster_id, cluster):def _stop_cluster_shared_container(cluster_id, cluster):- """- Stop a cluster's shared DocumentDB container, preserving it and its volume.- """+ """Stop a cluster's shared DocumentDB container, preserving it and its volume."""docker_client = _get_docker()container_id = cluster.get("_shared_container_id")if not docker_client or not container_id:@@ -778,12 +603,7 @@ def _stop_cluster_shared_container(cluster_id, cluster):def _remove_cluster_shared_resources(cluster_id, cluster, timeout=5):- """- Stop and remove a cluster's shared container and its named volume.-- Called by ``DeleteDBCluster`` and ``reset``; the last place cluster-owned- storage can be reclaimed.- """+ """Stop and remove a cluster's shared container and its named volume."""docker_client = _get_docker()if not docker_client:return@@ -806,9 +626,7 @@ def _remove_cluster_shared_resources(cluster_id, cluster, timeout=5):def _attach_instance_to_shared_cluster(instance, cluster):- """- Point a member instance's endpoint at the cluster's shared container.- """+ """Point a member instance's endpoint at the cluster's shared container."""endpoint = cluster.get("_shared_endpoint")if not endpoint:return@@ -825,9 +643,7 @@ def _attach_instance_to_shared_cluster(instance, cluster):def _sync_cluster_endpoints(cluster):- """- Publish the shared container's endpoint as the cluster Endpoint/Port.- """+ """Publish the shared container's endpoint as the cluster Endpoint/Port."""endpoint = cluster.get("_shared_endpoint")if not endpoint:return@@ -836,12 +652,7 @@ def _sync_cluster_endpoints(cluster):def _register_instance_in_cluster(instance):- """- Append the instance to its parent cluster's ``DBClusterMembers``.-- The first member becomes the writer; subsequent members register as- readers with their ``PromotionTier``.- """+ """Append the instance to its parent cluster's ``DBClusterMembers``."""cid = instance.get("DBClusterIdentifier")if not cid:return@@ -860,9 +671,7 @@ def _register_instance_in_cluster(instance):def _unregister_instance_from_clusters(db_id):- """- Remove an instance from any cluster member list it belongs to.- """+ """Remove an instance from any cluster member list it belongs to."""for cluster in _clusters.values():mem = cluster.get("DBClusterMembers") or []remaining = [m for m in mem if m.get("DBInstanceIdentifier") != db_id]@@ -885,9 +694,7 @@ def _unregister_instance_from_clusters(db_id):def _teardown_cluster_compute(cluster):- """- Clear a cluster's live-compute fields after its container went away.- """+ """Clear a cluster's live-compute fields after its container went away."""cluster["_shared_container_id"] = Nonecluster["_shared_container_ready"] = Truecluster["_shared_endpoint"] = None@@ -899,54 +706,24 @@ def _teardown_cluster_compute(cluster):# Engine versions & Docker images# ----------------------------------------------------------------------------def _default_engine_version(engine): # pylint: disable=unused-argument # RDS parity- """- Return the default DocumentDB engine version (5.0.0, per AWS SDK).- """+def _default_engine_version(engine):+ """Return the default DocumentDB engine version (the latest major)."""return DEFAULT_ENGINE_VERSION-def _engine_version_error(engine_version):- """- Build an InvalidParameterCombination error for unsupported versions.+def _default_parameter_group(engine_version):+ return "default.docdb" + ".".join(str(engine_version).split(".")[:2])- Returns:- tuple | None: Error response, or None when the version is cataloged.- """++def _engine_version_error(engine_version):+ """Build an InvalidParameterCombination error for unsupported versions."""if engine_version in _DOCDB_ENGINE_VERSION_SET:return None- supported = ", ".join(sorted(_DOCDB_ENGINE_VERSION_SET))- return _error(- "InvalidParameterCombination",- f"The engine version {engine_version} is not supported for docdb. "- f"Supported engine versions: {supported}.",- 400,- )+ return _error("InvalidParameterCombination", f"Cannot find version {engine_version} for docdb", 400)-def _docker_image_for_docdb(engine_version, user, password, db_name=""): # pylint: disable=unused-argument # tuple contract kept- """- Return the DocumentDB container configuration for any engine version.-- Every cataloged version runs the official ``documentdb-local`` image (MIT;- it tracks DocumentDB releases and speaks MongoDB 3.6 - 8.0 API), so one image- backs engine versions 5.0.0 and 8.0.0. Engine-version validation is the- control plane's job (:func:`_engine_version_error`), so unknown versions- return the same image without a warning. Honors ``MINISTACK_IMAGE_PREFIX``- via :func:`apply_image_prefix`.-- :param engine_version: Requested DocDB engine version (not for image selection).- :param user: Master username injected via the container's ``USERNAME`` env- (the container refuses names starting with ``documentdb``,- ``citus``, ``pg`` or ``internal_role``).- :param password: Master password injected via the container's ``PASSWORD`` env.- :param db_name: Ignored; clients ``use <db>`` after connecting.-- Returns:- tuple: ``(image, env_dict, container_port, data_path)``. The container- serves the MongoDB wire protocol on port 27017 (``DOCUMENTDB_PORT``);- data lives under ``/data`` (``DATA_PATH``).- """+def _docker_image_for_docdb(engine_version, user, password, db_name=""):+ """Return the DocumentDB container configuration for any engine version."""env = {"USERNAME": user,"PASSWORD": password,@@ -965,9 +742,7 @@ def _docker_image_for_docdb(engine_version, user, password, db_name=""): # pyli# ---------------------------------------------------------------------------def _json_key_to_query_param_name(key):- """- Map JSON / Smithy body keys to Query-API parameter names.- """+ """Map JSON / Smithy body keys to Query-API parameter names."""lk = key.lower()if lk == "dbinstanceidentifier":return "DBInstanceIdentifier"@@ -979,9 +754,7 @@ def _json_key_to_query_param_name(key):def _flatten_json_request_params(params, data):- """- Merge SigV4 JSON (``application/x-amz-json-1.*``) bodies into query-style params.- """+ """Merge SigV4 JSON (``application/x-amz-json-1.*``) bodies into query-style params."""if not isinstance(data, dict):returnfor key, val in data.items():@@ -1008,9 +781,7 @@ def _flatten_json_request_params(params, data):def _parse_request_params(body, headers, query_params):- """- Merge query-string, form-encoded, and JSON-body parameters into one map.- """+ """Merge query-string, form-encoded, and JSON-body parameters into one map."""params = dict(query_params)if not body:return params@@ -1032,32 +803,14 @@ def _parse_request_params(body, headers, query_params):return params-async def handle_request(method, path, headers, body, query_params): # pylint: disable=unused-argument # fixed service contract- """- Dispatch a DocumentDB request off the event loop.-- Handler paths reach the Docker daemon (container create/start/stop), which- blocks for as long as the daemon takes; like rds.py this must not hold the- event loop. The containers started here never call back into MiniStack, so- the shared non-reentrant pool is safe.-- :param method: HTTP method.- :param path: Request path (ignored; Query API lives on POST /).- :param headers: Lower-cased request headers.- :param body: Raw request body bytes.- :param query_params: Parsed query string ({name: [values]}).-- Returns:- tuple: ``(status, headers, body)`` XML response.- """+async def handle_request(method, path, headers, body, query_params):+ """Dispatch a DocumentDB request off the event loop."""params = _parse_request_params(body, headers, query_params)return await run_offloop(_handle_request_sync, headers, params)def _handle_request_sync(headers, params):- """- Resolve the requested action and invoke its handler synchronously.- """+ """Resolve the requested action and invoke its handler synchronously."""target = headers.get("x-amz-target", "") or headers.get("X-Amz-Target", "")if target:action = target.split(".")[-1]@@ -1069,29 +822,41 @@ def _handle_request_sync(headers, params):return handler(params)-# ----------------------------------------------------------------------------# DB Instances-# ---------------------------------------------------------------------------+def claims_request(params):+ """Whether an rds-signed request creates or names a DocumentDB cluster or instance."""+ if _evaluate_params(params, "Action") not in _ACTION_MAP:+ return False+ if _evaluate_params(params, "Engine") == "docdb":+ return True+ cluster_id = _evaluate_params(params, "DBClusterIdentifier")+ if cluster_id and cluster_id in _clusters:+ return True+ instance_id = _evaluate_params(params, "DBInstanceIdentifier")+ if instance_id and _resolve_instance(instance_id):+ return True+ arn = _evaluate_params(params, "ResourceName")+ return bool(arn) and (any(c.get("DBClusterArn") == arn for c in _clusters.values())+ or any(i.get("DBInstanceArn") == arn for i in _instances.values()))-def _create_db_instance(params):- """- Create a DB instance, optionally as a member of a DB cluster.- Members alias the parent cluster's shared DocumentDB container; the first- member starts it. Instances created without ``DBClusterIdentifier`` (raw- HTTP callers only — the boto3 client requires a cluster) run their own- per-instance container.+def cluster_members_xml(filters):+ """``<DBCluster>`` elements for RDS's unfiltered DescribeDBClusters, which lists every engine."""+ clusters = _apply_cluster_filters(list(_clusters.values()), filters) if filters else _clusters.values()+ return "".join(f"<DBCluster>{_cluster_xml(c)}</DBCluster>" for c in clusters)- :param params: Merged query/form/JSON request parameters.- Returns:- tuple: XML CreateDBInstanceResponse with the instance record.+def instance_members_xml(filters):+ """``<DBInstance>`` elements for RDS's unfiltered DescribeDBInstances, which lists every engine."""+ instances = _apply_instance_filters(list(_instances.values()), filters) if filters else _instances.values()+ return "".join(f"<DBInstance>{_instance_xml(i)}</DBInstance>" for i in instances)- Raises:- DBInstanceAlreadyExistsFault: Same-name instance exists (400).- DBClusterNotFoundFault: Named parent cluster missing (404).- InvalidParameterCombination: Unsupported EngineVersion (400).- """++# ---------------------------------------------------------------------------+# DB Instances+# ---------------------------------------------------------------------------++def _create_db_instance(params):+ """Create a DB instance, optionally as a member of a DB cluster."""db_id = _evaluate_params(params, "DBInstanceIdentifier")if not db_id:return _error("MissingParameter", "DBInstanceIdentifier is required", 400)@@ -1163,11 +928,11 @@ def _create_db_instance(params):for sg in _parse_member_list(params, "VpcSecurityGroupIds")],"DBParameterGroups": [{- "DBParameterGroupName": f"default.docdb{str(engine_version).split('.', maxsplit=1)[0]}",+ "DBParameterGroupName": _default_parameter_group(engine_version),"ParameterApplyStatus": "in-sync",}],"AvailabilityZone": _evaluate_params(params, "AvailabilityZone") or f"{get_region()}a",- "DBSubnetGroup": _subnet_groups.get(subnet_group_name, {+ "DBSubnetGroup": _rds._subnet_groups.get(subnet_group_name, {"DBSubnetGroupName": subnet_group_name,"DBSubnetGroupDescription": "default","SubnetGroupStatus": "Complete",@@ -1265,12 +1030,7 @@ def _create_db_instance(params):def _ensure_cluster_compute(cluster):- """- Guarantee a running shared container behind a cluster before use.-- Restarts the preserved container when present, otherwise starts a fresh- one (removing any stale same-name leftover we own).- """+ """Guarantee a running shared container behind a cluster before use."""with _shared_container_lock:if cluster.get("_shared_container_ready") and cluster.get("_shared_container_id"):return@@ -1282,11 +1042,7 @@ def _ensure_cluster_compute(cluster):def _start_instance_container(db_id, instance):- """- Start the per-instance DocumentDB container backing a standalone instance.-- No-op without Docker: the record keeps its placeholder localhost endpoint.- """+ """Start the per-instance DocumentDB container backing a standalone instance."""docker_client = _get_docker()if not docker_client:return@@ -1325,9 +1081,7 @@ def _start_instance_container(db_id, instance):def _log_readiness_async(host, port, label):- """- Spawn a daemon thread that waits for the port and logs readiness.- """+ """Spawn a daemon thread that waits for the port and logs readiness."""def _bg_wait(h=host, p=int(port or 0), lbl=label):if not p:return@@ -1342,22 +1096,7 @@ def _log_readiness_async(host, port, label):def _delete_db_instance(params):- """- elete a DB instance and release its backing compute.-- Member deletion unregisters the instance from its cluster; removing the- final member stops the shared container but keeps its volume. Deletion- protection is honored before any state changes.-- :param params: Request parameters (DBInstanceIdentifier required).-- Returns:- tuple: XML DeleteDBInstanceResponse with the deleted instance record.-- Raises:- DBInstanceNotFound: Unknown identifier (404).- InvalidParameterCombination: Deletion protection enabled (400).- """+ """elete a DB instance and release its backing compute."""db_id = _evaluate_params(params, "DBInstanceIdentifier")instance = _resolve_instance(db_id)if not instance:@@ -1388,11 +1127,6 @@ def _delete_db_instance(params):else:_remove_instance_container(db_id, instance)- skip_snapshot = _evaluate_params(params, "SkipFinalSnapshot") == "true"- final_snap_id = _evaluate_params(params, "FinalDBSnapshotIdentifier")- if not skip_snapshot and final_snap_id:- _create_snapshot_internal(final_snap_id, instance)-arn = instance["DBInstanceArn"]_tags.pop(arn, None)del _instances[db_id]@@ -1400,9 +1134,7 @@ def _delete_db_instance(params):def _will_be_last_member(cluster_id, db_id):- """- True when deleting db_id would leave its parent cluster with no members.- """+ """True when deleting db_id would leave its parent cluster with no members."""cluster = _clusters.get(cluster_id)if not cluster:return False@@ -1412,9 +1144,7 @@ def _will_be_last_member(cluster_id, db_id):def _remove_instance_container(db_id, instance):- """- Stop and remove the container owned by a standalone instance.- """+ """Stop and remove the container owned by a standalone instance."""container_id = instance.get("_docker_container_id")if not container_id:return@@ -1431,9 +1161,7 @@ def _remove_instance_container(db_id, instance):def _log_readiness_teardown(cluster_id):- """- Log that the last member of a cluster went away (compute taken down).- """+ """Log that the last member of a cluster went away (compute taken down)."""logger.info("docdb: last member of cluster %s deleted; shared container stopped ""(volume retained until DeleteDBCluster)", cluster_id,@@ -1441,9 +1169,7 @@ def _log_readiness_teardown(cluster_id):def _describe_db_instances(params):- """- Describe DB instances, optionally filtered by identifier or Filters.- """+ """Describe DB instances, optionally filtered by identifier or Filters."""db_id = _evaluate_params(params, "DBInstanceIdentifier")if db_id:instance = _resolve_instance(db_id)@@ -1463,23 +1189,7 @@ def _describe_db_instances(params):def _modify_db_instance(params):- """- Apply modifyable fields to a DB instance directly (no pending staging).-- Accepted: DBInstanceClass, AllocatedStorage, EngineVersion, MasterUserPassword,- DeletionProtection, BackupRetentionPeriod, PreferredMaintenanceWindow,- MultiAZ, AutoMinorVersionUpgrade, CopyTagsToSnapshot. ApplyImmediately is- accepted for SDK compatibility; changes always apply immediately.-- :param params: Request parameters (DBInstanceIdentifier required).-- Returns:- tuple: XML ModifyDBInstanceResponse with the updated record.-- Raises:- DBInstanceNotFound: Unknown identifier (404).- InvalidParameterCombination: Unsupported EngineVersion (400).- """+ """Apply modifyable fields to a DB instance directly (no pending staging)."""db_id = _evaluate_params(params, "DBInstanceIdentifier")instance = _resolve_instance(db_id)if not instance:@@ -1492,7 +1202,7 @@ def _modify_db_instance(params):return version_errorinstance["EngineVersion"] = new_versioninstance["DBParameterGroups"] = [{- "DBParameterGroupName": f"default.docdb{str(new_version).split('.', maxsplit=1)[0]}",+ "DBParameterGroupName": _default_parameter_group(new_version),"ParameterApplyStatus": "in-sync",}]simple_fields = (@@ -1512,10 +1222,8 @@ def _modify_db_instance(params):return _single_instance_response("ModifyDBInstanceResponse", "ModifyDBInstanceResult", instance)-def _coerce_scalar(field, value, current): # pylint: disable=unused-argument # field kept for call-site readability- """- Cast a request string to the stored field's existing type when known.- """+def _coerce_scalar(field, value, current):+ """Cast a request string to the stored field's existing type when known."""if isinstance(current, bool):return str(value).lower() == "true"if isinstance(current, int) and not isinstance(current, bool):@@ -1526,34 +1234,8 @@ def _coerce_scalar(field, value, current): # pylint: disable=unused-argument #return value-def _start_db_instance(params):- """- Mark a DB instance available (metadata-only; compute is always up).- """- db_id = _evaluate_params(params, "DBInstanceIdentifier")- instance = _resolve_instance(db_id)- if not instance:- return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)- instance["DBInstanceStatus"] = "available"- return _single_instance_response("StartDBInstanceResponse", "StartDBInstanceResult", instance)---def _stop_db_instance(params):- """- Mark a DB instance stopped (control-plane status only).- """- db_id = _evaluate_params(params, "DBInstanceIdentifier")- instance = _resolve_instance(db_id)- if not instance:- return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)- instance["DBInstanceStatus"] = "stopped"- return _single_instance_response("StopDBInstanceResponse", "StopDBInstanceResult", instance)--def _reboot_db_instance(params):- """- Reboot a DB instance (status returns to available immediately).- """+ """Reboot a DB instance (status returns to available immediately)."""db_id = _evaluate_params(params, "DBInstanceIdentifier")instance = _resolve_instance(db_id)if not instance:@@ -1567,18 +1249,7 @@ def _reboot_db_instance(params):# ---------------------------------------------------------------------------def _create_db_cluster(params):- """- Create a DB cluster record; compute starts with its first member.-- :param params: Request parameters (DBClusterIdentifier required).-- Returns:- tuple: XML CreateDBClusterResponse with the cluster record.-- Raises:- DBClusterAlreadyExistsFault: Same-name cluster exists (400).- InvalidParameterCombination: Unsupported EngineVersion (400).- """+ """Create a DB cluster record; compute starts with its first member."""cluster_id = _evaluate_params(params, "DBClusterIdentifier")if not cluster_id:return _error("MissingParameter", "DBClusterIdentifier is required", 400)@@ -1592,6 +1263,11 @@ def _create_db_cluster(params):version_error = _engine_version_error(engine_version)if version_error:return version_error+ parameter_group = _evaluate_params(params, "DBClusterParameterGroupName")+ if (parameter_group and not parameter_group.startswith("default.")+ and parameter_group not in _rds._db_cluster_param_groups):+ return _error("DBClusterParameterGroupNotFound",+ f"DBClusterParameterGroup {parameter_group} not found.", 404)port = int(_evaluate_params(params, "Port") or "27017")master_user = _evaluate_params(params, "MasterUsername") or "root"@@ -1632,7 +1308,7 @@ def _create_db_cluster(params):],"DBSubnetGroup": _evaluate_params(params, "DBSubnetGroupName") or "default","DBClusterParameterGroup": (- _evaluate_params(params, "DBClusterParameterGroupName") or "default.docdb"),+ _evaluate_params(params, "DBClusterParameterGroupName") or _default_parameter_group(engine_version)),"BackupRetentionPeriod": int(_evaluate_params(params, "BackupRetentionPeriod") or "1"),"PreferredBackupWindow": _evaluate_params(params, "PreferredBackupWindow") or "03:00-04:00","PreferredMaintenanceWindow": (@@ -1678,23 +1354,7 @@ def _create_db_cluster(params):def _delete_db_cluster(params):- """- Delete a DB cluster along with its shared container and volume.-- Refuses while instances remain attached, mirroring AWS ordering (delete- the members first); an empty cluster's compute and storage are always- removed.-- :param params: Request parameters (DBClusterIdentifier required).-- Returns:- tuple: XML DeleteDBClusterResponse with the deleted cluster record.-- Raises:- DBClusterNotFoundFault: Unknown cluster (404).- InvalidDBClusterStateFault: Cluster still has members (400).- InvalidParameterCombination: Deletion protection enabled (400).- """+ """Delete a DB cluster along with its shared container and volume."""cluster_id = _evaluate_params(params, "DBClusterIdentifier")cluster = _clusters.get(cluster_id)if not cluster:@@ -1724,9 +1384,7 @@ def _delete_db_cluster(params):def _describe_db_clusters(params):- """- Describe DB clusters, optionally filtered by identifier or Filters.- """+ """Describe DB clusters, optionally filtered by identifier or Filters."""cluster_id = _evaluate_params(params, "DBClusterIdentifier")if cluster_id:cluster = _clusters.get(cluster_id)@@ -1746,9 +1404,7 @@ def _describe_db_clusters(params):def _modify_db_cluster(params):- """- Modify cluster settings; MasterUserPassword also rotates container creds.- """+ """Modify cluster settings; MasterUserPassword also rotates container creds."""cluster_id = _evaluate_params(params, "DBClusterIdentifier")cluster = _clusters.get(cluster_id)if not cluster:@@ -1789,9 +1445,7 @@ def _modify_db_cluster(params):def _start_db_cluster(params):- """- Start a stopped cluster's compute (restart/recreate the container).- """+ """Start a stopped cluster's compute (restart/recreate the container)."""cluster_id = _evaluate_params(params, "DBClusterIdentifier")cluster = _clusters.get(cluster_id)if not cluster:@@ -1849,9 +1503,7 @@ def _start_db_cluster(params):def _stop_db_cluster(params):- """- Stop a cluster's shared DocumentDB container, preserving it and its volume.- """+ """Stop a cluster's shared DocumentDB container, preserving it and its volume."""cluster_id = _evaluate_params(params, "DBClusterIdentifier")cluster = _clusters.get(cluster_id)if not cluster:@@ -1874,22 +1526,7 @@ def _stop_db_cluster(params):def _failover_db_cluster(params):- """- Rotate IsClusterWriter to the next member (lowest PromotionTier).-- Endpoints stay unchanged, matching real DocDB where cluster endpoints are- stable across failover. Zero-member clusters succeed as a no-op.-- :param params: Request parameters; TargetDBInstanceIdentifier optional.-- Returns:- tuple: XML FailoverDBClusterResponse reporting transitional status- ``failing-over`` (the stored status stays ``available``).-- Raises:- DBClusterNotFoundFault: Unknown cluster (404).- InvalidDBInstanceStateFault: Named target is not a reader member (400).- """+ """Rotate IsClusterWriter to the next member (lowest PromotionTier)."""cluster_id = _evaluate_params(params, "DBClusterIdentifier")cluster = _clusters.get(cluster_id)if not cluster:@@ -1925,879 +1562,44 @@ def _failover_db_cluster(params):f"</DBCluster></FailoverDBClusterResult>")-def _restore_db_cluster_from_snapshot(params):- """Restore a cluster from a cluster snapshot's recorded metadata.-- Snapshots are metadata-only (configuration + tags, no data dump), so the- restored cluster comes up empty against fresh storage.- :param params: Request parameters (DBClusterIdentifier, Engine,- SnapshotIdentifier required).-- Returns:- tuple: XML RestoreDBClusterFromSnapshotResponse with the new cluster.+# ---------------------------------------------------------------------------+# Tags+# ---------------------------------------------------------------------------- Raises:- DBClusterAlreadyExistsFault: Target name already used (400).- DBClusterSnapshotNotFoundFault: Snapshot missing (404).- InvalidParameterCombination: Unsupported EngineVersion (400).- """- cluster_id = _evaluate_params(params, "DBClusterIdentifier")- if not cluster_id:- return _error("MissingParameter", "DBClusterIdentifier is required", 400)- if cluster_id in _clusters:+def _tags_resource_not_found(arn):+ """Build the documented not-found fault for an unknown tags target ARN."""+ for cl in _clusters.values():+ if cl.get("DBClusterArn") == arn:+ return None+ for inst in _instances.values():+ if inst.get("DBInstanceArn") == arn:+ return None+ parts = arn.split(":")+ kind = parts[5] if len(parts) >= 7 and parts[0] == "arn" else ""+ if kind == "db":+ return _error("DBInstanceNotFound", f"DBInstance {arn} not found.", 404)+ if kind in ("snapshot", "cluster-snapshot"):+ return _error("DBSnapshotNotFound", f"DBSnapshot {arn} not found.", 404)+ if kind == "subgrp":return _error(- "DBClusterAlreadyExistsFault", f"DB cluster {cluster_id} already exists.", 400)-- snap_id = _evaluate_params(params, "SnapshotIdentifier")- snapshot = _db_cluster_snapshots.get(snap_id) if snap_id else None- if not snapshot:+ "DBSubnetGroupNotFoundFault", f"Subnet group {arn} not found.", 404)+ if kind in ("cluster-pg", "pg"):return _error(- "DBClusterSnapshotNotFoundFault",- f"DBClusterSnapshot {snap_id} not found."- if snap_id else "SnapshotIdentifier is required",- 404 if snap_id else 400,+ "DBParameterGroupNotFound",+ f"DB cluster parameter group {arn} not found.",+ 404,)+ return _error("DBClusterNotFoundFault", f"DBCluster {arn} not found.", 404)- engine_version = _evaluate_params(params, "EngineVersion") or snapshot.get("EngineVersion")- version_error = _engine_version_error(engine_version)- if version_error:- return version_error- source_cluster = _clusters.get(snapshot.get("DBClusterIdentifier"))- master_pass = (- source_cluster.get("_MasterUserPassword", "password")- if source_cluster else "password"- )- now_ts = time.time()- unique_suffix = new_uuid()[:8]- arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:cluster:{cluster_id}"-- cluster = {- "DBClusterIdentifier": cluster_id,- "DBClusterArn": arn,- "Engine": "docdb",- "EngineVersion": engine_version,- "EngineMode": "provisioned",- "Status": "available",- "MasterUsername": snapshot.get("MasterUsername", "root"),- "_MasterUserPassword": master_pass,- "DatabaseName": None,- "NetworkType": _evaluate_params(params, "NetworkType") or "IPV4",- "EngineLifecycleSupport": "open-source-rds-extended-support",- "Endpoint": (- f"{cluster_id}.cluster-{unique_suffix}.{get_region()}.docdb.amazonaws.com"),- "ReaderEndpoint": (- f"{cluster_id}.cluster-ro-{unique_suffix}.{get_region()}.docdb.amazonaws.com"),- "Port": int(_evaluate_params(params, "Port") or snapshot.get("Port") or "27017"),- "MultiAZ": False,- "AvailabilityZones": (- _parse_member_list(params, "AvailabilityZones")- or snapshot.get("AvailabilityZones", [])),- "DBClusterMembers": [],- "VpcSecurityGroups": [- {"VpcSecurityGroupId": sg, "Status": "active"}- for sg in _parse_member_list(params, "VpcSecurityGroupIds")- ],- "DBSubnetGroup": _evaluate_params(params, "DBSubnetGroupName") or "default",- "DBClusterParameterGroup": (- _evaluate_params(params, "DBClusterParameterGroupName") or "default.docdb"),- "BackupRetentionPeriod": 1,- "PreferredBackupWindow": "03:00-04:00",- "PreferredMaintenanceWindow": "sun:05:00-sun:06:00",- "ClusterCreateTime": _format_time(now_ts),- "EarliestRestorableTime": _format_time(now_ts),- "LatestRestorableTime": _format_time(now_ts),- "StorageEncrypted": snapshot.get("StorageEncrypted", False),- "KmsKeyId": _evaluate_params(params, "KmsKeyId") or snapshot.get("KmsKeyId", ""),- "DeletionProtection": _evaluate_params(params, "DeletionProtection") == "true",- "IAMDatabaseAuthenticationEnabled": False,- "EnabledCloudwatchLogsExports": [],- "HttpEndpointEnabled": False,- "CopyTagsToSnapshot": False,- "CrossAccountClone": False,- "DbClusterResourceId": f"cluster-{new_uuid().replace('-', '')[:20].upper()}",- "TagList": [],- "HostedZoneId": "Z2R2ITUGPM61AM",- "AssociatedRoles": [],- "ActivityStreamStatus": "stopped",- "AllocatedStorage": 1,- "Capacity": 0,- "ClusterScalabilityType": "standard",- "_shared_container_id": None,- "_shared_endpoint": None,- "_shared_host_port": None,- "_shared_volume_name": _cluster_volume_name(cluster_id) if DOCDB_PERSIST else None,- "_shared_storage_initialized": False,- "_shared_container_epoch": 0,- }- _clusters[cluster_id] = cluster-- req_tags = _parse_tags(params)- if req_tags:- _tags[arn] = req_tags- cluster["TagList"] = req_tags-- return _xml(200, "RestoreDBClusterFromSnapshotResponse",- f"<RestoreDBClusterFromSnapshotResult>"- f"<DBCluster>{_cluster_xml(cluster)}</DBCluster>"- f"</RestoreDBClusterFromSnapshotResult>")---# ----------------------------------------------------------------------------# Instance snapshots (legacy direct-HTTP surface; not in the real DocDB API)-# -----------------------------------------------------------------------------def _create_snapshot_internal(snap_id, instance):- """- Record an instance snapshot copying the instance's configuration.- """- if snap_id in _snapshots:- return None- now_ts = time.time()- snap = {- "DBSnapshotIdentifier": snap_id,- "DBInstanceIdentifier": instance["DBInstanceIdentifier"],- "DBSnapshotArn": f"arn:aws:rds:{get_region()}:{get_account_id()}:snapshot:{snap_id}",- "Engine": instance.get("Engine", "docdb"),- "EngineVersion": instance.get("EngineVersion", ""),- "SnapshotCreateTime": _format_time(now_ts),- "InstanceCreateTime": instance.get("InstanceCreateTime", ""),- "Status": "available",- "AllocatedStorage": instance.get("AllocatedStorage", 20),- "AvailabilityZone": instance.get("AvailabilityZone", f"{get_region()}a"),- "VpcId": "vpc-00000000",- "Port": (instance.get("Endpoint") or {}).get("Port", 27017),- "MasterUsername": instance.get("MasterUsername", "root"),- "DBName": instance.get("DBName", ""),- "SnapshotType": "manual",- "LicenseModel": "docdb",- "StorageType": instance.get("StorageType", "gp2"),- "DBInstanceClass": instance.get("DBInstanceClass", ""),- "StorageEncrypted": instance.get("StorageEncrypted", False),- "KmsKeyId": instance.get("KmsKeyId", ""),- "Encrypted": instance.get("StorageEncrypted", False),- "IAMDatabaseAuthenticationEnabled": instance.get(- "IAMDatabaseAuthenticationEnabled", False),- "PercentProgress": 100,- "DbiResourceId": instance.get("DbiResourceId", ""),- "TagList": list(instance.get("TagList", [])) if instance.get("CopyTagsToSnapshot") else [],- "SnapshotTarget": "region",- "_master_password": instance.get("_MasterUserPassword", "password"),- }- _snapshots[snap_id] = snap- return snap---def _create_db_snapshot(params):- """- Create a manual snapshot of a DB instance (metadata-only).-- :param params: Request parameters (DBSnapshotIdentifier, DBInstanceIdentifier).-- Returns:- tuple: XML CreateDBSnapshotResponse with the snapshot record.-- Raises:- DBSnapshotAlreadyExistsFault: Same-name snapshot exists (400).- DBInstanceNotFound: Source instance missing (404).- """- snap_id = _evaluate_params(params, "DBSnapshotIdentifier")- if not snap_id:- return _error("MissingParameter", "DBSnapshotIdentifier is required", 400)- if snap_id in _snapshots:- return _error(- "DBSnapshotAlreadyExistsFault",- f"Snapshot {snap_id} already exists.",- 400,- )- db_id = _evaluate_params(params, "DBInstanceIdentifier")- instance = _resolve_instance(db_id) if db_id else None- if not instance:- return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)-- snap = _create_snapshot_internal(snap_id, instance)- arn = snap["DBSnapshotArn"]- req_tags = _parse_tags(params)- if req_tags:- _tags[arn] = req_tags- snap["TagList"] = req_tags- return _xml(200, "CreateDBSnapshotResponse",- f"<CreateDBSnapshotResult>"- f"<DBSnapshot>{_snapshot_xml(snap)}</DBSnapshot></CreateDBSnapshotResult>")---def _describe_db_snapshots(params):- """- Describe instance snapshots, optionally filtered or listed by source.- """- snap_id = _evaluate_params(params, "DBSnapshotIdentifier")- if snap_id:- snap = _snapshots.get(snap_id)- if not snap:- return _error("DBSnapshotNotFound", f"DBSnapshot {snap_id} not found.", 404)- snaps = [snap]- else:- snaps = list(_snapshots.values())- db_id = _evaluate_params(params, "DBInstanceIdentifier")- if db_id:- snaps = [s for s in snaps if s.get("DBInstanceIdentifier") == db_id]-- members = "".join(f"<DBSnapshot>{_snapshot_xml(s)}</DBSnapshot>" for s in snaps)- return _xml(200, "DescribeDBSnapshotsResponse",- f"<DescribeDBSnapshotsResult><DBSnapshots>{members}"- f"</DBSnapshots></DescribeDBSnapshotsResult>")---def _delete_db_snapshot(params):- """- Delete an instance snapshot and its tags.-- Raises:- DBSnapshotNotFound: Unknown snapshot identifier (404).- """- snap_id = _evaluate_params(params, "DBSnapshotIdentifier")- snap = _snapshots.pop(snap_id, None)- if not snap:- return _error("DBSnapshotNotFound", f"DBSnapshot {snap_id} not found.", 404)- _tags.pop(snap.get("DBSnapshotArn", ""), None)- snap["Status"] = "deleted"- return _xml(200, "DeleteDBSnapshotResponse",- f"<DeleteDBSnapshotResult>"- f"<DBSnapshot>{_snapshot_xml(snap)}</DBSnapshot></DeleteDBSnapshotResult>")---# ----------------------------------------------------------------------------# DB Cluster Snapshots (metadata-only: config + tags, no data dump)-# -----------------------------------------------------------------------------def _create_db_cluster_snapshot(params):- """- Create a manual snapshot of a DB cluster (metadata-only).-- Records the cluster configuration, tags (honoring CopyTagsToSnapshot),- and the restore attribute defaults; contains no database dump.-- :param params: Request parameters (DBClusterSnapshotIdentifier,- DBClusterIdentifier required).-- Returns:- tuple: XML CreateDBClusterSnapshotResponse with the snapshot record.-- Raises:- DBClusterNotFoundFault: Source cluster missing (404).- DBClusterSnapshotAlreadyExistsFault: Same-name snapshot exists (400).- """- snap_id = _evaluate_params(params, "DBClusterSnapshotIdentifier")- if not snap_id:- return _error("MissingParameter", "DBClusterSnapshotIdentifier is required", 400)- if snap_id in _db_cluster_snapshots:- return _error(- "DBClusterSnapshotAlreadyExistsFault",- f"DB cluster snapshot {snap_id} already exists.",- 400,- )-- cluster_id = _evaluate_params(params, "DBClusterIdentifier")- cluster = _clusters.get(cluster_id) if cluster_id else None- if not cluster:- return _error("DBClusterNotFoundFault", f"DBCluster {cluster_id} not found.", 404)-- arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:cluster-snapshot:{snap_id}"- snap = {- "DBClusterSnapshotIdentifier": snap_id,- "DBClusterIdentifier": cluster["DBClusterIdentifier"],- "DBClusterSnapshotArn": arn,- "Engine": cluster["Engine"],- "EngineVersion": cluster["EngineVersion"],- "SnapshotCreateTime": _format_time(time.time()),- "ClusterCreateTime": cluster.get("ClusterCreateTime", ""),- "Status": "available",- "Port": cluster.get("Port", 27017),- "VpcId": "vpc-00000000",- "MasterUsername": cluster.get("MasterUsername", "root"),- "SnapshotType": "manual",- "PercentProgress": 100,- "StorageEncrypted": cluster.get("StorageEncrypted", False),- "KmsKeyId": cluster.get("KmsKeyId", ""),- "AvailabilityZones": cluster.get("AvailabilityZones", []),- "LicenseModel": "docdb",- "StorageType": "gp2",- "DbClusterResourceId": cluster.get("DbClusterResourceId", ""),- "IAMDatabaseAuthenticationEnabled": cluster.get("IAMDatabaseAuthenticationEnabled", False),- "AllocatedStorage": cluster.get("AllocatedStorage", 1),- "SourceDBClusterSnapshotArn": "",- "TagList": list(_tags.get(cluster.get("DBClusterArn", ""), []))- if cluster.get("CopyTagsToSnapshot") else [],- "_attributes": {"restore": [get_account_id()]},- "_MasterUserPassword": cluster.get("_MasterUserPassword", "password"),- "_DBSubnetGroup": cluster.get("DBSubnetGroup", "default"),- }- _db_cluster_snapshots[snap_id] = snap-- req_tags = _parse_tags(params)- if req_tags:- _tags[arn] = req_tags- snap["TagList"] = req_tags-- return _xml(200, "CreateDBClusterSnapshotResponse",- "<CreateDBClusterSnapshotResult><DBClusterSnapshot>"- f"{_cluster_snapshot_xml(snap)}"- "</DBClusterSnapshot></CreateDBClusterSnapshotResult>")---def _describe_db_cluster_snapshots(params):- """- Describe cluster snapshots, optionally filtered by snapshot or cluster.- """- snap_id = _evaluate_params(params, "DBClusterSnapshotIdentifier")- if snap_id:- snap = _db_cluster_snapshots.get(snap_id)- if not snap:- return _error(- "DBClusterSnapshotNotFoundFault",- f"DB cluster snapshot {snap_id} not found.",- 404,- )- snaps = [snap]- else:- snaps = list(_db_cluster_snapshots.values())- cluster_id = _evaluate_params(params, "DBClusterIdentifier")- if cluster_id:- snaps = [s for s in snaps if s.get("DBClusterIdentifier") == cluster_id]- snap_type = _evaluate_params(params, "SnapshotType")- if snap_type:- snaps = [s for s in snaps if s.get("SnapshotType") == snap_type]-- members = "".join(- f"<DBClusterSnapshot>{_cluster_snapshot_xml(s)}</DBClusterSnapshot>" for s in snaps)- return _xml(200, "DescribeDBClusterSnapshotsResponse",- "<DescribeDBClusterSnapshotsResult><DBClusterSnapshots>"- f"{members}</DBClusterSnapshots></DescribeDBClusterSnapshotsResult>")---def _delete_db_cluster_snapshot(params):- """- Delete a cluster snapshot and its tags.-- Raises:- DBClusterSnapshotNotFoundFault: Unknown snapshot identifier (404).- """- snap_id = _evaluate_params(params, "DBClusterSnapshotIdentifier")- snap = _db_cluster_snapshots.pop(snap_id, None)- if not snap:- return _error(- "DBClusterSnapshotNotFoundFault",- f"DB cluster snapshot {snap_id} not found.",- 404,- )- _tags.pop(snap.get("DBClusterSnapshotArn", ""), None)- snap["Status"] = "deleted"- return _xml(200, "DeleteDBClusterSnapshotResponse",- "<DeleteDBClusterSnapshotResult><DBClusterSnapshot>"- f"{_cluster_snapshot_xml(snap)}"- "</DBClusterSnapshot></DeleteDBClusterSnapshotResult>")---def _describe_db_cluster_snapshot_attributes(params):- """- Return a cluster snapshot's share/restore attribute values.- """- snap = _resolve_cluster_snapshot(params)- if isinstance(snap, tuple):- return snap- return _snapshot_attributes_response(- "DescribeDBClusterSnapshotAttributesResponse",- "DescribeDBClusterSnapshotAttributesResult", snap,- )---def _modify_db_cluster_snapshot_attribute(params):- """- Add or remove values for a cluster snapshot attribute (share/restore).-- :param params: Request parameters; AttributeName (default ``restore``),- ValuesToAdd / ValuesToRemove lists of account ids.-- Returns:- tuple: XML ModifyDBClusterSnapshotAttributeResponse with the updated- attributes.-- Raises:- DBClusterSnapshotNotFoundFault: Unknown snapshot identifier (404).- """- snap = _resolve_cluster_snapshot(params)- if isinstance(snap, tuple):- return snap- attr_name = _evaluate_params(params, "AttributeName") or "restore"- attributes = snap.setdefault("_attributes", {})- values = list(attributes.get(attr_name, []))- for val in _parse_member_list(params, "ValuesToAdd"):- if val not in values:- values.append(val)- remove = set(_parse_member_list(params, "ValuesToRemove"))- attributes[attr_name] = [v for v in values if v not in remove]- return _snapshot_attributes_response(- "ModifyDBClusterSnapshotAttributeResponse",- "ModifyDBClusterSnapshotAttributeResult", snap,- )---def _resolve_cluster_snapshot(params):- """- Fetch the snapshot named by DBClusterSnapshotIdentifier or an error tuple.- """- snap_id = _evaluate_params(params, "DBClusterSnapshotIdentifier")- snap = _db_cluster_snapshots.get(snap_id)- if not snap:- return _error(- "DBClusterSnapshotNotFoundFault",- f"DB cluster snapshot {snap_id} not found.",- 404,- )- return snap---def _snapshot_attributes_response(root_tag, result_tag, snap):- """- Render a snapshot-attribute response document.-- The service model nests a ``DBClusterSnapshotAttributesResult`` element- inside the action's ``*Result`` wrapper.- """- attrs_xml = ""- for attr_name, values in (snap.get("_attributes") or {"restore": []}).items():- vals_xml = "".join(f"<AttributeValue>{_esc(v)}</AttributeValue>" for v in values)- attrs_xml += f"""<DBClusterSnapshotAttribute>- <AttributeName>{attr_name}</AttributeName>- <AttributeValues>{vals_xml}</AttributeValues>- </DBClusterSnapshotAttribute>"""- return _xml(200, root_tag,- f"<{result_tag}><DBClusterSnapshotAttributesResult>"- f"<DBClusterSnapshotIdentifier>{snap['DBClusterSnapshotIdentifier']}"- f"</DBClusterSnapshotIdentifier><DBClusterSnapshotAttributes>{attrs_xml}"- f"</DBClusterSnapshotAttributes></DBClusterSnapshotAttributesResult>"- f"</{result_tag}>")---# ----------------------------------------------------------------------------# DB Cluster Parameter Groups-# -----------------------------------------------------------------------------# Minimal plausible DocumentDB cluster-parameter catalog, applied to every-# family (docdb5.0 / docdb8.0): (name, default, description, type, apply type).-_CLUSTER_PARAMETER_DEFAULTS = [- ("audit_logs", "disabled", "Which audit logs to export to CloudWatch Logs.",- "string", "dynamic"),- ("change_stream_log_retention_duration", "10800",- "How long change stream events are retained, in seconds.", "string", "dynamic"),- ("profiler", "disabled", "Database profiler mode (off, slow_ops, all).", "string", "dynamic"),- ("profiler_rate_threshold_ns", "100000000",- "Slow-operation threshold for the profiler, in nanoseconds.", "integer", "dynamic"),- ("profiler_sampling_rate", "500",- "Fraction of slow operations sampled, in milliseconds.", "integer", "dynamic"),- ("tls", "enabled", "Whether TLS is required for connections.", "string", "static"),- ("ttl_monitor_enabled", "true",- "Whether the TTL monitor deletes expired documents.", "boolean", "dynamic"),-]---def _default_parameters_for_family(family): # pylint: disable=unused-argument # catalog may grow per family- """- Build default parameter records for a docdb parameter-group family.- """- return [- {- "name": name,- "value": default,- "description": description,- "data_type": data_type,- "apply_type": apply_type,- }- for name, default, description, data_type, apply_type in _CLUSTER_PARAMETER_DEFAULTS- ]---def _create_db_cluster_parameter_group(params):- """- Create an empty DB cluster parameter group for a given family.-- Raises:- DBParameterGroupAlreadyExistsFault: Same-name group exists (400).- """- name = _evaluate_params(params, "DBClusterParameterGroupName")- if not name:- return _error("MissingParameter", "DBClusterParameterGroupName is required", 400)- if name in _db_cluster_param_groups:- return _error(- "DBParameterGroupAlreadyExistsFault",- f"Parameter group {name} already exists.",- 400,- )- family = _evaluate_params(params, "DBParameterGroupFamily") or "docdb5.0"- desc = _evaluate_params(params, "Description") or name- arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:cluster-pg:{name}"-- _db_cluster_param_groups[name] = {- "DBClusterParameterGroupName": name,- "DBParameterGroupFamily": family,- "Description": desc,- "DBClusterParameterGroupArn": arn,- "Parameters": {},- }-- req_tags = _parse_tags(params)- if req_tags:- _tags[arn] = req_tags-- return _xml(200, "CreateDBClusterParameterGroupResponse",- "<CreateDBClusterParameterGroupResult><DBClusterParameterGroup>"- f"<DBClusterParameterGroupName>{name}</DBClusterParameterGroupName>"- f"<DBParameterGroupFamily>{family}</DBParameterGroupFamily>"- f"<Description>{_esc(desc)}</Description>"- f"<DBClusterParameterGroupArn>{arn}</DBClusterParameterGroupArn>"- "</DBClusterParameterGroup></CreateDBClusterParameterGroupResult>")---def _describe_db_cluster_parameter_groups(params):- """- Describe cluster parameter groups, optionally filtered by name.- """- name = _evaluate_params(params, "DBClusterParameterGroupName")- if name:- pg = _db_cluster_param_groups.get(name)- if not pg:- return _error("DBParameterGroupNotFound",- f"DB cluster parameter group {name} not found.", 404)- groups = [pg]- else:- groups = list(_db_cluster_param_groups.values())-- members = "".join(_cluster_parameter_group_xml(g) for g in groups)- return _xml(200, "DescribeDBClusterParameterGroupsResponse",- "<DescribeDBClusterParameterGroupsResult><DBClusterParameterGroups>"- f"{members}</DBClusterParameterGroups></DescribeDBClusterParameterGroupsResult>")---def _cluster_parameter_group_xml(g):- """- Render one cluster parameter group dict to XML fields.- """- name = g["DBClusterParameterGroupName"]- arn = g.get("DBClusterParameterGroupArn", "")- return f"""<DBClusterParameterGroup>- <DBClusterParameterGroupName>{name}</DBClusterParameterGroupName>- <DBParameterGroupFamily>{g['DBParameterGroupFamily']}</DBParameterGroupFamily>- <Description>{_esc(g['Description'])}</Description>- <DBClusterParameterGroupArn>{arn}</DBClusterParameterGroupArn>- </DBClusterParameterGroup>"""---def _delete_db_cluster_parameter_group(params):- """- Delete a cluster parameter group and its tags.-- Raises:- DBParameterGroupNotFound: Unknown group name (404).- """- name = _evaluate_params(params, "DBClusterParameterGroupName")- pg = _db_cluster_param_groups.pop(name, None)- if not pg:- return _error("DBParameterGroupNotFound",- f"DB cluster parameter group {name} not found.", 404)- _tags.pop(pg.get("DBClusterParameterGroupArn", ""), None)- return _xml(200, "DeleteDBClusterParameterGroupResponse", "")---def _modify_db_cluster_parameter_group(params):- """- Store submitted parameters on a group; status reports ``in-sync``.- """- pg = _resolve_cluster_param_group(params)- if isinstance(pg, tuple):- return pg- store = pg.setdefault("Parameters", {})- prefix = _parameter_member_prefix(params)- idx = 1- while _evaluate_params(params, f"{prefix}.{idx}.ParameterName"):- pname = _evaluate_params(params, f"{prefix}.{idx}.ParameterName")- pvalue = _evaluate_params(params, f"{prefix}.{idx}.ParameterValue")- apply_method = _evaluate_params(params, f"{prefix}.{idx}.ApplyMethod") or "immediate"- store[pname] = {"ParameterValue": pvalue, "ApplyMethod": apply_method}- idx += 1-- return _xml(200, "ModifyDBClusterParameterGroupResponse",- "<ModifyDBClusterParameterGroupResult>"- f"<DBClusterParameterGroupName>{pg['DBClusterParameterGroupName']}"- f"</DBClusterParameterGroupName></ModifyDBClusterParameterGroupResult>")---def _reset_db_cluster_parameter_group(params):- """- Reset some or all parameters of a group back to engine defaults.- """- pg = _resolve_cluster_param_group(params)- if isinstance(pg, tuple):- return pg- store = pg.setdefault("Parameters", {})- prefix = _parameter_member_prefix(params)- has_explicit_parameters = bool(_evaluate_params(params, f"{prefix}.1.ParameterName"))- reset_all = _evaluate_params(params, "ResetAllParameters", "").lower() == "true"- if reset_all and has_explicit_parameters:- return _error(- "InvalidParameterCombination",- "You can't specify both ResetAllParameters and Parameters.",- 400,- )-- if reset_all or not has_explicit_parameters:- store.clear()- else:- idx = 1- while _evaluate_params(params, f"{prefix}.{idx}.ParameterName"):- store.pop(_evaluate_params(params, f"{prefix}.{idx}.ParameterName"), None)- idx += 1-- return _xml(200, "ResetDBClusterParameterGroupResponse",- "<ResetDBClusterParameterGroupResult>"- f"<DBClusterParameterGroupName>{pg['DBClusterParameterGroupName']}"- f"</DBClusterParameterGroupName></ResetDBClusterParameterGroupResult>")---def _describe_db_cluster_parameters(params):- """- Describe a group's parameters: engine defaults overlaid with overrides.-- Supports the Source filter (``engine-default`` / ``user``).-- Raises:- DBParameterGroupNotFound: Unknown group name (404).- """- pg = _resolve_cluster_param_group(params)- if isinstance(pg, tuple):- return pg- source_filter = _evaluate_params(params, "Source")- members = _cluster_parameters_xml(pg, source_filter)- return _xml(200, "DescribeDBClusterParametersResponse",- "<DescribeDBClusterParametersResult>"- f"<Parameters>{members}</Parameters></DescribeDBClusterParametersResult>")---def _resolve_cluster_param_group(params):- """- Fetch the parameter group named in the request, or an error tuple.- """- name = _evaluate_params(params, "DBClusterParameterGroupName")- pg = _db_cluster_param_groups.get(name)- if not pg:- return _error("DBParameterGroupNotFound",- f"DB cluster parameter group {name} not found.", 404)- return pg---def _parameter_member_prefix(params, prefix="Parameters"):- """- Handle both Query API and botocore/SFN parameter-list serialization.- """- query_prefix = f"{prefix}.member"- if _evaluate_params(params, f"{query_prefix}.1.ParameterName"):- return query_prefix- return f"{prefix}.Parameter"---def _cluster_parameters_xml(pg, source_filter):- """- Render a group's parameter records (defaults merged with overrides).- """- defaults = _default_parameters_for_family(pg.get("DBParameterGroupFamily", ""))- custom = pg.get("Parameters", {})- default_names = {p["name"] for p in defaults}- params_xml = ""-- for param in defaults:- pname = param["name"]- override = custom.get(pname)- if isinstance(override, dict):- value = override.get("ParameterValue", param["value"])- apply_method = override.get("ApplyMethod", "immediate")- else:- value = param["value"]- apply_method = "immediate"- source = "user" if pname in custom else "engine-default"- if source_filter and source != source_filter:- continue- params_xml += _cluster_parameter_xml(pname, value, source, apply_method, param)-- if not source_filter or source_filter == "user":- for pname, override in custom.items():- if pname in default_names:- continue- if isinstance(override, dict):- value = override.get("ParameterValue", "")- apply_method = override.get("ApplyMethod", "immediate")- else:- value, apply_method = override, "immediate"- params_xml += _cluster_parameter_xml(pname, value, "user", apply_method, None)- return params_xml---def _cluster_parameter_xml(name, value, source, apply_method, spec):- """- Render one Parameter record; ``spec`` carries default metadata or None.- """- description = spec["description"] if spec else ""- data_type = spec["data_type"] if spec else "string"- apply_type = spec["apply_type"] if spec else "dynamic"- return f"""<Parameter>- <ParameterName>{_esc(str(name))}</ParameterName>- <ParameterValue>{_esc(str(value))}</ParameterValue>- <Description>{_esc(description)}</Description>- <Source>{source}</Source>- <ApplyType>{apply_type}</ApplyType>- <DataType>{data_type}</DataType>- <IsModifiable>true</IsModifiable>- <ApplyMethod>{apply_method}</ApplyMethod>- </Parameter>"""---# ----------------------------------------------------------------------------# Subnet Groups (minimal)-# -----------------------------------------------------------------------------def _create_subnet_group(params):- """- Create a DB subnet group listing VPC subnets for cluster placement.- """- name = _evaluate_params(params, "DBSubnetGroupName")- if not name:- return _error("MissingParameter", "DBSubnetGroupName is required", 400)- desc = _evaluate_params(params, "DBSubnetGroupDescription") or name- subnet_ids = _parse_member_list(params, "SubnetIds")- arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:subgrp:{name}"-- subnets = [{"SubnetIdentifier": sid, "SubnetAvailabilityZone": {"Name": f"{get_region()}a"},- "SubnetOutpost": {}, "SubnetStatus": "Active"} for sid in subnet_ids]-- _subnet_groups[name] = {- "DBSubnetGroupName": name,- "DBSubnetGroupDescription": desc,- "VpcId": "vpc-00000000",- "SubnetGroupStatus": "Complete",- "Subnets": subnets,- "DBSubnetGroupArn": arn,- "SupportedNetworkTypes": ["IPV4"],- }-- req_tags = _parse_tags(params)- if req_tags:- _tags[arn] = req_tags-- sg = _subnet_groups[name]- return _xml(200, "CreateDBSubnetGroupResponse",- "<CreateDBSubnetGroupResult><DBSubnetGroup>"- f"{_subnet_group_xml(sg)}</DBSubnetGroup></CreateDBSubnetGroupResult>")---def _delete_subnet_group(params):- """- Delete a DB subnet group and its tags.-- Raises:- DBSubnetGroupNotFoundFault: Unknown group name (404).- """- name = _evaluate_params(params, "DBSubnetGroupName")- sg = _subnet_groups.pop(name, None)- if not sg:- return _error("DBSubnetGroupNotFoundFault", f"Subnet group {name} not found.", 404)- _tags.pop(sg.get("DBSubnetGroupArn", ""), None)- return _xml(200, "DeleteDBSubnetGroupResponse", "")---def _describe_subnet_groups(params):- """- Describe DB subnet groups, optionally filtered by name.- """- name = _evaluate_params(params, "DBSubnetGroupName")- if name:- sg = _subnet_groups.get(name)- if not sg:- return _error("DBSubnetGroupNotFoundFault", f"Subnet group {name} not found.", 404)- groups = [sg]- else:- groups = list(_subnet_groups.values())-- members = "".join(f"<DBSubnetGroup>{_subnet_group_xml(g)}</DBSubnetGroup>" for g in groups)- return _xml(200, "DescribeDBSubnetGroupsResponse",- "<DescribeDBSubnetGroupsResult>"- f"<DBSubnetGroups>{members}</DBSubnetGroups></DescribeDBSubnetGroupsResult>")---# ----------------------------------------------------------------------------# Tags-# -----------------------------------------------------------------------------def _tags_resource_not_found(arn):- """- Build the documented not-found fault for an unknown tags target ARN.-- Resolves ``ResourceName`` against live records: cluster ARN, instance ARN,- cluster-snapshot ARN, legacy snapshot ARN, subnet-group ARN and cluster- parameter-group ARN. Returns the matching fault per the API Reference —- ``DBClusterNotFoundFault``, ``DBInstanceNotFound`` and- ``DBSnapshotNotFound`` are documented for the tags actions;- ``DBSubnetGroupNotFoundFault`` and ``DBParameterGroupNotFound`` reuse each- group handler's existing fault code (inference: the model does not list- them for the tags actions).- """- for cl in _clusters.values():- if cl.get("DBClusterArn") == arn:- return None- for inst in _instances.values():- if inst.get("DBInstanceArn") == arn:- return None- for snap in _snapshots.values():- if snap.get("DBSnapshotArn") == arn:- return None- for csnap in _db_cluster_snapshots.values():- if csnap.get("DBClusterSnapshotArn") == arn:- return None- for sg in _subnet_groups.values():- if sg.get("DBSubnetGroupArn") == arn:- return None- for pg in _db_cluster_param_groups.values():- if pg.get("DBClusterParameterGroupArn") == arn:- return None- parts = arn.split(":")- kind = parts[5] if len(parts) >= 7 and parts[0] == "arn" else ""- if kind == "db":- return _error("DBInstanceNotFound", f"DBInstance {arn} not found.", 404)- if kind in ("snapshot", "cluster-snapshot"):- return _error("DBSnapshotNotFound", f"DBSnapshot {arn} not found.", 404)- if kind == "subgrp":- return _error(- "DBSubnetGroupNotFoundFault", f"Subnet group {arn} not found.", 404)- if kind in ("cluster-pg", "pg"):- return _error(- "DBParameterGroupNotFound",- f"DB cluster parameter group {arn} not found.",- 404,- )- return _error("DBClusterNotFoundFault", f"DBCluster {arn} not found.", 404)---def _add_tags(params):- """- Add or overwrite tags on a resource identified by ARN.-- Raises:- DBClusterNotFoundFault | DBInstanceNotFound | DBSnapshotNotFound:- Unknown ResourceName (404).- """- arn = _evaluate_params(params, "ResourceName")- if not arn:- return _error("MissingParameter", "ResourceName is required", 400)- not_found = _tags_resource_not_found(arn)- if not_found:- return not_found+def _add_tags(params):+ """Add or overwrite tags on a resource identified by ARN."""+ arn = _evaluate_params(params, "ResourceName")+ if not arn:+ return _error("MissingParameter", "ResourceName is required", 400)+ not_found = _tags_resource_not_found(arn)+ if not_found:+ return not_foundnew_tags = _parse_tags(params)existing = _tags.get(arn, [])@@ -2816,13 +1618,7 @@ def _add_tags(params):def _remove_tags(params):- """- Remove tag keys from a resource identified by ARN.-- Raises:- DBClusterNotFoundFault | DBInstanceNotFound | DBSnapshotNotFound:- Unknown ResourceName (404).- """+ """Remove tag keys from a resource identified by ARN."""arn = _evaluate_params(params, "ResourceName")if not arn:return _error("MissingParameter", "ResourceName is required", 400)@@ -2839,13 +1635,7 @@ def _remove_tags(params):def _list_tags(params):- """- List tags on a resource identified by ARN.-- Raises:- DBClusterNotFoundFault | DBInstanceNotFound | DBSnapshotNotFound:- Unknown ResourceName (404).- """+ """List tags on a resource identified by ARN."""arn = _evaluate_params(params, "ResourceName")if not arn:return _error("MissingParameter", "ResourceName is required", 400)@@ -2863,9 +1653,7 @@ def _list_tags(params):def _sync_tag_list_to_resource(arn):- """- Keep embedded TagList copies in sync with the canonical _tags store.- """+ """Keep embedded TagList copies in sync with the canonical _tags store."""tag_list = _tags.get(arn, [])for inst in _instances.values():if inst.get("DBInstanceArn") == arn:@@ -2875,240 +1663,6 @@ def _sync_tag_list_to_resource(arn):if cl.get("DBClusterArn") == arn:cl["TagList"] = list(tag_list)return- for snap in _snapshots.values():- if snap.get("DBSnapshotArn") == arn:- snap["TagList"] = list(tag_list)- return- for csnap in _db_cluster_snapshots.values():- if csnap.get("DBClusterSnapshotArn") == arn:- csnap["TagList"] = list(tag_list)- return---# ----------------------------------------------------------------------------# Engine Versions & Orderable Options (docdb)-# -----------------------------------------------------------------------------def _describe_db_engine_versions(params):- """- Emit the cataloged docdb engine versions with their families.- """- version_filter = _evaluate_params(params, "EngineVersion")- members = ""- for ver, family in DOCDB_ENGINE_VERSIONS:- if version_filter and ver != version_filter:- continue- upgrade_targets = ""- seen_higher = False- for higher_ver, _ in DOCDB_ENGINE_VERSIONS:- if seen_higher:- upgrade_targets += f"""<ValidUpgradeTarget>- <Engine>docdb</Engine>- <EngineVersion>{higher_ver}</EngineVersion>- <Description>DocumentDB {higher_ver}</Description>- <AutoUpgrade>false</AutoUpgrade>- <IsMajorVersionUpgrade>true</IsMajorVersionUpgrade>- <SupportedEngineModes>- <member>provisioned</member>- </SupportedEngineModes>- <SupportsParallelQuery>false</SupportsParallelQuery>- <SupportsGlobalDatabases>false</SupportsGlobalDatabases>- <SupportsBabelfish>false</SupportsBabelfish>- </ValidUpgradeTarget>"""- if higher_ver == ver:- seen_higher = True- members += f"""<DBEngineVersion>- <Engine>docdb</Engine>- <EngineVersion>{ver}</EngineVersion>- <DBParameterGroupFamily>{family}</DBParameterGroupFamily>- <DBEngineDescription>Amazon DocumentDB (with MongoDB compatibility)</DBEngineDescription>- <DBEngineVersionDescription>DocumentDB {ver}</DBEngineVersionDescription>- <ValidUpgradeTarget>{upgrade_targets}</ValidUpgradeTarget>- <ExportableLogTypes/>- <SupportsLogExportsToCloudwatchLogs>false</SupportsLogExportsToCloudwatchLogs>- <SupportsReadReplica>true</SupportsReadReplica>- <SupportedFeatureNames/>- <Status>available</Status>- <SupportsParallelQuery>false</SupportsParallelQuery>- <SupportsGlobalDatabases>false</SupportsGlobalDatabases>- <SupportsBabelfish>false</SupportsBabelfish>- <SupportedCACertificateIdentifiers>- <member>rds-ca-rsa2048-g1</member>- </SupportedCACertificateIdentifiers>- <SupportsCertificateRotationWithoutRestart>true</SupportsCertificateRotationWithoutRestart>- </DBEngineVersion>"""- return _xml(200, "DescribeDBEngineVersionsResponse",- "<DescribeDBEngineVersionsResult>"- f"<DBEngineVersions>{members}</DBEngineVersions></DescribeDBEngineVersionsResult>")---def _describe_orderable_options(params):- """- List orderable instance classes for a cataloged engine version.- """- engine_version = _evaluate_params(params, "EngineVersion") or DEFAULT_ENGINE_VERSION- if engine_version not in _DOCDB_ENGINE_VERSION_SET:- engine_version = DEFAULT_ENGINE_VERSION- db_class = _evaluate_params(params, "DBInstanceClass")-- instance_classes = [- "db.t3.medium", "db.t3.large", "db.r5.large", "db.r5.xlarge",- "db.m5.large", "db.m5.xlarge",- ]-- members = ""- for cls in instance_classes:- if db_class and cls != db_class:- continue- members += f"""<OrderableDBInstanceOption>- <Engine>docdb</Engine>- <EngineVersion>{engine_version}</EngineVersion>- <DBInstanceClass>{cls}</DBInstanceClass>- <LicenseModel>docdb</LicenseModel>- <AvailabilityZones>- <AvailabilityZone><Name>{get_region()}a</Name></AvailabilityZone>- <AvailabilityZone><Name>{get_region()}b</Name></AvailabilityZone>- </AvailabilityZones>- <MultiAZCapable>true</MultiAZCapable>- <ReadReplicaCapable>true</ReadReplicaCapable>- <Vpc>true</Vpc>- <SupportsStorageEncryption>true</SupportsStorageEncryption>- <StorageType>gp2</StorageType>- <SupportsIops>false</SupportsIops>- <SupportsEnhancedMonitoring>true</SupportsEnhancedMonitoring>- <SupportsIAMDatabaseAuthentication>true</SupportsIAMDatabaseAuthentication>- <SupportsPerformanceInsights>false</SupportsPerformanceInsights>- <AvailableProcessorFeatures/>- <SupportedEngineModes><member>provisioned</member></SupportedEngineModes>- <SupportsStorageAutoscaling>true</SupportsStorageAutoscaling>- <SupportsKerberosAuthentication>false</SupportsKerberosAuthentication>- <OutpostCapable>false</OutpostCapable>- <SupportedNetworkTypes><member>IPV4</member></SupportedNetworkTypes>- <SupportsGlobalDatabases>false</SupportsGlobalDatabases>- <SupportsClusters>true</SupportsClusters>- <SupportedActivityStreamModes/>- </OrderableDBInstanceOption>"""- return _xml(200, "DescribeOrderableDBInstanceOptionsResponse",- "<DescribeOrderableDBInstanceOptionsResult>"- "<OrderableDBInstanceOptions>"- f"{members}</OrderableDBInstanceOptions>"- "</DescribeOrderableDBInstanceOptionsResult>")---# ----------------------------------------------------------------------------# Certificates, Events, Pending Maintenance Actions-# -----------------------------------------------------------------------------_STATIC_CERTIFICATE = {- "CertificateIdentifier": "rds-ca-rsa2048-g1",- "CertificateType": "CA",- "Thumbprint": "3c9a5e1f7b2d46a89e0c1d3f5a7b9c2e4d6f8a1b3c5d7e9f",- "ValidFrom": "2021-01-01T00:00:00Z",- "ValidTill": "2061-01-01T00:00:00Z",-}---def _describe_certificates(params):- """- Return the static CA certificate matching CACertificateIdentifier.- """- ident = _evaluate_params(params, "CertificateIdentifier")- cert_arn = (- f"arn:aws:rds:{get_region()}::cert:{_STATIC_CERTIFICATE['CertificateIdentifier']}")- cert = dict(_STATIC_CERTIFICATE, CertificateArn=cert_arn)- certs = [cert] if not ident or ident == cert["CertificateIdentifier"] else []- members = "".join(f"""<Certificate>- <CertificateArn>{c['CertificateArn']}</CertificateArn>- <CertificateIdentifier>{c['CertificateIdentifier']}</CertificateIdentifier>- <CertificateType>{c['CertificateType']}</CertificateType>- <Thumbprint>{c['Thumbprint']}</Thumbprint>- <ValidFrom>{c['ValidFrom']}</ValidFrom>- <ValidTill>{c['ValidTill']}</ValidTill>- </Certificate>""" for c in certs)- return _xml(200, "DescribeCertificatesResponse",- f"<DescribeCertificatesResult><Certificates>{members}"- f"</Certificates></DescribeCertificatesResult>")---def _describe_events(params): # pylint: disable=unused-argument # action handlers take params- """- Return recorded events; none are recorded today, so an empty list.- """- return _xml(200, "DescribeEventsResponse",- "<DescribeEventsResult><Events/></DescribeEventsResult>")---def _apply_pending_maintenance_action(params):- """- Record an opt-in for a pending maintenance action on a resource.-- :param params: Request parameters (ResourceIdentifier, ApplyAction,- OptInType required).-- Returns:- tuple: XML ApplyPendingMaintenanceActionResponse echoing the action.-- Raises:- ResourceNotFoundFault: Missing required parameter (400).- """- resource_identifier = _evaluate_params(params, "ResourceIdentifier")- apply_action = _evaluate_params(params, "ApplyAction")- opt_in_type = _evaluate_params(params, "OptInType") or "immediately"- if not resource_identifier or not apply_action:- return _error(- "ResourceNotFoundFault",- "ResourceIdentifier and ApplyAction are required.",- 400,- )- entry = {- "ResourceIdentifier": resource_identifier,- "ApplyAction": apply_action,- "OptInStatus": opt_in_type,- "Date": _format_time(time.time()),- }- _pending_maintenance_actions[:] = [- e for e in _pending_maintenance_actions- if not (e["ResourceIdentifier"] == resource_identifier and e["ApplyAction"] == apply_action)- ]- _pending_maintenance_actions.append(entry)- details = "".join(f"""<PendingMaintenanceAction>- <Action>{entry['ApplyAction']}</Action>- <OptInStatus>{entry['OptInStatus']}</OptInStatus>- <Date>{entry['Date']}</Date>- </PendingMaintenanceAction>""")- return _xml(200, "ApplyPendingMaintenanceActionResponse",- "<ApplyPendingMaintenanceActionResult><ResourcePendingMaintenanceActions>"- f"<ResourceIdentifier>{_esc(resource_identifier)}</ResourceIdentifier>"- f"<PendingMaintenanceActionDetails>{details}</PendingMaintenanceActionDetails>"- "</ResourcePendingMaintenanceActions></ApplyPendingMaintenanceActionResult>")---def _describe_pending_maintenance_actions(params):- """- Return recorded pending maintenance actions, optionally per resource.- """- resource_identifier = _evaluate_params(params, "ResourceIdentifier")- entries = [- e for e in _pending_maintenance_actions- if not resource_identifier or e["ResourceIdentifier"] == resource_identifier- ]- grouped: dict = {}- for entry in entries:- grouped.setdefault(entry["ResourceIdentifier"], []).append(entry)- members = ""- for rid, actions in grouped.items():- details = "".join(f"""<PendingMaintenanceAction>- <Action>{a['ApplyAction']}</Action>- <OptInStatus>{a['OptInStatus']}</OptInStatus>- <Date>{a['Date']}</Date>- </PendingMaintenanceAction>""" for a in actions)- members += f"""<ResourcePendingMaintenanceActions>- <ResourceIdentifier>{_esc(rid)}</ResourceIdentifier>- <PendingMaintenanceActionDetails>{details}</PendingMaintenanceActionDetails>- </ResourcePendingMaintenanceActions>"""- return _xml(200, "DescribePendingMaintenanceActionsResponse",- "<DescribePendingMaintenanceActionsResult><PendingMaintenanceActions>"- f"{members}</PendingMaintenanceActions></DescribePendingMaintenanceActionsResult>")# ---------------------------------------------------------------------------@@ -3116,13 +1670,7 @@ def _describe_pending_maintenance_actions(params):# ---------------------------------------------------------------------------def _xml(status, root_tag, inner):- """- Wrap rendered inner fields in a Query-API response document.-- Returns:- tuple: ``(status, headers, body)`` with the RDS-style XML namespace- the docdb service model declares.- """+ """Wrap rendered inner fields in a Query-API response document."""body = f"""<?xml version="1.0" encoding="UTF-8"?><{root_tag} xmlns="http://rds.amazonaws.com/doc/2014-10-31/">{inner}@@ -3132,14 +1680,7 @@ def _xml(status, root_tag, inner):def _error(code, message, status):- """- Build an RDS-style XML error response.-- Args:- code: AWS wire error code (e.g. ``DBClusterNotFoundFault``).- message: Human-readable explanation surfaced to the client.- status: HTTP status code; 4xx marks the fault type ``Sender``.- """+ """Build an RDS-style XML error response."""fault_type = "Sender" if 400 <= status < 500 else "Receiver"body = f"""<?xml version="1.0" encoding="UTF-8"?><ErrorResponse xmlns="http://rds.amazonaws.com/doc/2014-10-31/">@@ -3150,17 +1691,13 @@ def _error(code, message, status):def _single_instance_response(root_tag, result_tag, instance):- """- Wrap one instance record in a create/delete/modify/start/stop envelope.- """+ """Wrap one instance record in a create/delete/modify/start/stop envelope."""return _xml(200, root_tag,f"<{result_tag}><DBInstance>{_instance_xml(instance)}</DBInstance></{result_tag}>")def _subnet_az_name(subnet_entry):- """- AZ name for a subnet record, defaulting to the region.- """+ """AZ name for a subnet record, defaulting to the region."""zone = subnet_entry.get("SubnetAvailabilityZone")if isinstance(zone, dict) and zone.get("Name"):return zone["Name"]@@ -3168,9 +1705,7 @@ def _subnet_az_name(subnet_entry):def _instance_xml(i):- """- Render an instance dict to XML fields — no wrapping element.- """+ """Render an instance dict to XML fields — no wrapping element."""ep = i.get("Endpoint", {})subnet = i.get("DBSubnetGroup", {})if isinstance(subnet, str):@@ -3331,9 +1866,7 @@ def _instance_xml(i):def _cluster_xml(c):- """- Render a cluster dict to XML fields — no wrapping element.- """+ """Render a cluster dict to XML fields — no wrapping element."""vpc_sg_xml = ""for sg in c.get("VpcSecurityGroups", []):vpc_sg_xml += f"""<VpcSecurityGroupMembership>@@ -3421,127 +1954,18 @@ def _cluster_xml(c):<EngineLifecycleSupport>{lifecycle}</EngineLifecycleSupport>"""-def _snapshot_xml(s):- """- Render an (legacy) instance-snapshot dict to XML fields.- """- tag_xml = ""- for t in s.get("TagList", []):- tag_xml += f"<Tag><Key>{_esc(t['Key'])}</Key><Value>{_esc(t['Value'])}</Value></Tag>"- return f"""<DBSnapshotIdentifier>{s['DBSnapshotIdentifier']}</DBSnapshotIdentifier>- <DBInstanceIdentifier>{s['DBInstanceIdentifier']}</DBInstanceIdentifier>- <DBSnapshotArn>{s.get('DBSnapshotArn', '')}</DBSnapshotArn>- <Engine>{s['Engine']}</Engine>- <EngineVersion>{s['EngineVersion']}</EngineVersion>- <SnapshotCreateTime>{s.get('SnapshotCreateTime', '')}</SnapshotCreateTime>- <InstanceCreateTime>{s.get('InstanceCreateTime', '')}</InstanceCreateTime>- <Status>{s['Status']}</Status>- <AllocatedStorage>{s.get('AllocatedStorage', 20)}</AllocatedStorage>- <AvailabilityZone>{s.get('AvailabilityZone', f'{get_region()}a')}</AvailabilityZone>- <VpcId>{s.get('VpcId', 'vpc-00000000')}</VpcId>- <Port>{s.get('Port', 27017)}</Port>- <MasterUsername>{s.get('MasterUsername', 'root')}</MasterUsername>- <DBName>{s.get('DBName', '')}</DBName>- <SnapshotType>{s.get('SnapshotType', 'manual')}</SnapshotType>- <LicenseModel>{s.get('LicenseModel', 'docdb')}</LicenseModel>- <StorageType>{s.get('StorageType', 'gp2')}</StorageType>- <DBInstanceClass>{s.get('DBInstanceClass', 'db.t3.medium')}</DBInstanceClass>- <StorageEncrypted>{str(s.get('StorageEncrypted', False)).lower()}</StorageEncrypted>- <KmsKeyId>{s.get('KmsKeyId', '')}</KmsKeyId>- <Encrypted>{str(s.get('Encrypted', False)).lower()}</Encrypted>- <IAMDatabaseAuthenticationEnabled>- {str(s.get('IAMDatabaseAuthenticationEnabled', False)).lower()}- </IAMDatabaseAuthenticationEnabled>- <PercentProgress>{s.get('PercentProgress', 100)}</PercentProgress>- <DbiResourceId>{s.get('DbiResourceId', '')}</DbiResourceId>- <TagList>{tag_xml}</TagList>- <OriginalSnapshotCreateTime>- {s.get('OriginalSnapshotCreateTime', '')}- </OriginalSnapshotCreateTime>- <SnapshotDatabaseTime>{s.get('SnapshotDatabaseTime', '')}</SnapshotDatabaseTime>- <SnapshotTarget>{s.get('SnapshotTarget', 'region')}</SnapshotTarget>"""---def _cluster_snapshot_xml(s):- """- Render a cluster snapshot dict to XML fields — no wrapping element.- """- tag_xml = ""- for t in s.get("TagList", []):- tag_xml += f"<Tag><Key>{_esc(t['Key'])}</Key><Value>{_esc(t['Value'])}</Value></Tag>"- az_xml = "".join(f"<AvailabilityZone>{az}</AvailabilityZone>"- for az in s.get("AvailabilityZones", []))- snap_identifier = s['DBClusterSnapshotIdentifier']- open_id = f"<DBClusterSnapshotIdentifier>{snap_identifier}"- return f"""{open_id}</DBClusterSnapshotIdentifier>- <DBClusterIdentifier>{s['DBClusterIdentifier']}</DBClusterIdentifier>- <DBClusterSnapshotArn>{s.get('DBClusterSnapshotArn', '')}</DBClusterSnapshotArn>- <Engine>{s['Engine']}</Engine>- <EngineVersion>{s['EngineVersion']}</EngineVersion>- <SnapshotCreateTime>{s.get('SnapshotCreateTime', '')}</SnapshotCreateTime>- <ClusterCreateTime>{s.get('ClusterCreateTime', '')}</ClusterCreateTime>- <Status>{s['Status']}</Status>- <Port>{s.get('Port', 27017)}</Port>- <VpcId>{s.get('VpcId', 'vpc-00000000')}</VpcId>- <MasterUsername>{s.get('MasterUsername', 'root')}</MasterUsername>- <SnapshotType>{s.get('SnapshotType', 'manual')}</SnapshotType>- <PercentProgress>{s.get('PercentProgress', 100)}</PercentProgress>- <StorageEncrypted>{str(s.get('StorageEncrypted', False)).lower()}</StorageEncrypted>- <KmsKeyId>{s.get('KmsKeyId', '')}</KmsKeyId>- <AvailabilityZones>{az_xml}</AvailabilityZones>- <LicenseModel>{s.get('LicenseModel', 'docdb')}</LicenseModel>- <StorageType>{s.get('StorageType', 'gp2')}</StorageType>- <DbClusterResourceId>{s.get('DbClusterResourceId', '')}</DbClusterResourceId>- <SourceDBClusterSnapshotArn>- {s.get('SourceDBClusterSnapshotArn', '')}- </SourceDBClusterSnapshotArn>- <IAMDatabaseAuthenticationEnabled>- {str(s.get('IAMDatabaseAuthenticationEnabled', False)).lower()}- </IAMDatabaseAuthenticationEnabled>- <AllocatedStorage>{s.get('AllocatedStorage', 1)}</AllocatedStorage>- <TagList>{tag_xml}</TagList>"""---def _subnet_group_xml(sg):- """- Render a subnet-group dict to XML fields — no wrapping element.- """- subnets_xml = ""- for s in sg.get("Subnets", []):- az = _subnet_az_name(s)- subnets_xml += f"""<Subnet>- <SubnetIdentifier>{s.get('SubnetIdentifier', '')}</SubnetIdentifier>- <SubnetAvailabilityZone><Name>{az}</Name></SubnetAvailabilityZone>- <SubnetOutpost/>- <SubnetStatus>Active</SubnetStatus>- </Subnet>"""- group_name = sg["DBSubnetGroupName"]- return f"""<DBSubnetGroupName>{group_name}</DBSubnetGroupName>- <DBSubnetGroupDescription>{sg.get('DBSubnetGroupDescription', '')}- </DBSubnetGroupDescription>- <VpcId>{sg.get('VpcId', 'vpc-00000000')}</VpcId>- <SubnetGroupStatus>{sg.get('SubnetGroupStatus', 'Complete')}</SubnetGroupStatus>- <Subnets>{subnets_xml}</Subnets>- <DBSubnetGroupArn>{sg.get('DBSubnetGroupArn', '')}</DBSubnetGroupArn>- <SupportedNetworkTypes><member>IPV4</member></SupportedNetworkTypes>"""--# ---------------------------------------------------------------------------# Generic helpers# ---------------------------------------------------------------------------def _format_time(ts):- """- Format a unix timestamp as DocDB-style UTC with millisecond precision.- """+ """Format a unix timestamp as DocDB-style UTC with millisecond precision."""dt = datetime.datetime.fromtimestamp(ts, tz=datetime.timezone.utc)return dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"def _evaluate_params(params, key, default=""):- """- Read the first value for a request parameter, or the default.- """+ """Read the first value for a request parameter, or the default."""val = params.get(key, [default])if isinstance(val, list):return val[0] if val else default@@ -3549,9 +1973,7 @@ def _evaluate_params(params, key, default=""):def _parse_tags(params):- """- Parse Tags.member.N.Key/Value or Tags.Tag.N.Key/Value into records.- """+ """Parse Tags.member.N.Key/Value or Tags.Tag.N.Key/Value into records."""tags = []prefix = "Tags.member"if not _evaluate_params(params, "Tags.member.1.Key"):@@ -3568,13 +1990,7 @@ def _parse_tags(params):def _parse_member_list(params, prefix):- """- Parse list params in either Prefix.member.N or Prefix.<MemberName>.N form.-- The member.N format is used by direct AWS CLI/SDK calls. The- <MemberName>.N format is produced by botocore's serializer when dispatched- via Step Functions aws-sdk integrations (e.g. SubnetIds.SubnetIdentifier.N).- """+ """Parse list params in either Prefix.member.N or Prefix.<MemberName>.N form."""items = []i = 1while True:@@ -3597,9 +2013,9 @@ def _parse_member_list(params, prefix):def _parse_filters(params):"""- Parse request filters in either ``Filters.Filter.N`` or- ``Filters.member.N`` wire form (botocore emits one or the other- depending on the model's locationName)."""+ Parse request filters in either ``Filters.Filter.N`` or ``Filters.member.N`` wire form (botocore emits one+ or the other depending on the model's locationName).+ """filters = {}i = 1while True:@@ -3628,12 +2044,7 @@ def _parse_filters(params):# ---------------------------------------------------------------------------def _resolve_instance(db_id):- """- Look up an instance by DBInstanceIdentifier or DbiResourceId.-- AWS accepts either value for the DBInstanceIdentifier parameter in- DescribeDBInstances and related APIs.- """+ """Look up an instance by DBInstanceIdentifier or DbiResourceId."""inst = _instances.get(db_id)if inst:return inst@@ -3645,9 +2056,7 @@ def _resolve_instance(db_id):def _cluster_member_instances(cluster):- """- Resolve a cluster's member records to their live instance dicts.- """+ """Resolve a cluster's member records to their live instance dicts."""return [instfor inst in (@@ -3659,9 +2068,7 @@ def _cluster_member_instances(cluster):def _apply_instance_filters(instances, filters):- """- Filter instance records by db-instance-id, engine, or db-cluster-id.- """+ """Filter instance records by db-instance-id, engine, or db-cluster-id."""result = []for inst in instances:match = True@@ -3681,9 +2088,7 @@ def _apply_instance_filters(instances, filters):def _apply_cluster_filters(clusters, filters):- """- Filter cluster records by db-cluster-id or engine.- """+ """Filter cluster records by db-cluster-id or engine."""result = []for cl in clusters:match = True@@ -3704,14 +2109,7 @@ def _apply_cluster_filters(clusters, filters):# ---------------------------------------------------------------------------def reset():- """- Stop/remove every docdb container (cluster-owned and standalone), then- clear all state.-- Cluster-owned containers are reaped once from the cluster records before- standalone instances are considered, so members never race to remove the- same shared container.- """+ """Stop/remove every docdb container (cluster-owned and standalone), then clear all state."""with _shared_container_lock:docker_client = _get_docker()shared_container_ids = set()@@ -3735,12 +2133,7 @@ def reset():"reset: failed to stop/remove docdb container %s: %s", cid, e)_instances.clear()_clusters.clear()- _subnet_groups.clear()- _snapshots.clear()- _db_cluster_snapshots.clear()- _db_cluster_param_groups.clear()_tags.clear()- _pending_maintenance_actions.clear()_port_counter[0] = BASE_PORT@@ -3749,15 +2142,11 @@ def reset():# ---------------------------------------------------------------------------_ACTION_MAP = {- # Instances"CreateDBInstance": _create_db_instance,"DeleteDBInstance": _delete_db_instance,"DescribeDBInstances": _describe_db_instances,"ModifyDBInstance": _modify_db_instance,- "StartDBInstance": _start_db_instance,- "StopDBInstance": _stop_db_instance,"RebootDBInstance": _reboot_db_instance,- # Clusters"CreateDBCluster": _create_db_cluster,"DeleteDBCluster": _delete_db_cluster,"DescribeDBClusters": _describe_db_clusters,@@ -3765,49 +2154,14 @@ _ACTION_MAP = {"StartDBCluster": _start_db_cluster,"StopDBCluster": _stop_db_cluster,"FailoverDBCluster": _failover_db_cluster,- "RestoreDBClusterFromSnapshot": _restore_db_cluster_from_snapshot,- # Subnet groups- "CreateDBSubnetGroup": _create_subnet_group,- "DeleteDBSubnetGroup": _delete_subnet_group,- "DescribeDBSubnetGroups": _describe_subnet_groups,- # Instance snapshots (legacy direct-HTTP surface; not in the real API)- "CreateDBSnapshot": _create_db_snapshot,- "DeleteDBSnapshot": _delete_db_snapshot,- "DescribeDBSnapshots": _describe_db_snapshots,- # Cluster snapshots- "CreateDBClusterSnapshot": _create_db_cluster_snapshot,- "DeleteDBClusterSnapshot": _delete_db_cluster_snapshot,- "DescribeDBClusterSnapshots": _describe_db_cluster_snapshots,- "ModifyDBClusterSnapshotAttribute": _modify_db_cluster_snapshot_attribute,- "DescribeDBClusterSnapshotAttributes": _describe_db_cluster_snapshot_attributes,- # Cluster parameter groups- "CreateDBClusterParameterGroup": _create_db_cluster_parameter_group,- "DescribeDBClusterParameterGroups": _describe_db_cluster_parameter_groups,- "DeleteDBClusterParameterGroup": _delete_db_cluster_parameter_group,- "ModifyDBClusterParameterGroup": _modify_db_cluster_parameter_group,- "ResetDBClusterParameterGroup": _reset_db_cluster_parameter_group,- "DescribeDBClusterParameters": _describe_db_cluster_parameters,- # Tags- "ListTagsForResource": _list_tags,"AddTagsToResource": _add_tags,"RemoveTagsFromResource": _remove_tags,- # Catalog & maintenance- "DescribeDBEngineVersions": _describe_db_engine_versions,- "DescribeOrderableDBInstanceOptions": _describe_orderable_options,- "ApplyPendingMaintenanceAction": _apply_pending_maintenance_action,- "DescribePendingMaintenanceActions": _describe_pending_maintenance_actions,- "DescribeCertificates": _describe_certificates,- "DescribeEvents": _describe_events,+ "ListTagsForResource": _list_tags,}def _live_container_ids():- """- Container ids still owned by a live instance or cluster.-- A stopped cluster still owns its (exited) container — StartDBCluster must- be able to restart it — so it is reported here and never reaped.- """+ """Container ids still owned by a live instance or cluster."""ids = set()for _key, inst in _instances.all_items():cid = inst.get("_docker_container_id")diff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex 355e544b..120bd31a 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -5404,13 +5404,16 @@ def _describe_db_instances(p):return invalid_arnreturn _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)instances = [instance]+ docdb_members = ""else:instances = list(_instances.values())filters = _parse_filters(p)if filters:instances = _apply_instance_filters(instances, filters)+ from ministack.services import documentdb+ docdb_members = documentdb.instance_members_xml(filters)- members = "".join(f"<DBInstance>{_instance_xml(i)}</DBInstance>" for i in instances)+ members = "".join(f"<DBInstance>{_instance_xml(i)}</DBInstance>" for i in instances) + docdb_membersreturn _xml(200, "DescribeDBInstancesResponse",f"<DescribeDBInstancesResult><DBInstances>{members}</DBInstances></DescribeDBInstancesResult>")@@ -6081,13 +6084,16 @@ def _describe_db_clusters(p):return wrong_regionreturn _error("DBClusterNotFoundFault", f"DBCluster {cluster_id} not found.", 404)clusters = [cluster]+ docdb_members = ""else:clusters = list(_clusters.values())filters = _parse_filters(p)if filters:clusters = _apply_cluster_filters(clusters, filters)+ from ministack.services import documentdb+ docdb_members = documentdb.cluster_members_xml(filters)- members = "".join(f"<DBCluster>{_cluster_xml(c)}</DBCluster>" for c in clusters)+ members = "".join(f"<DBCluster>{_cluster_xml(c)}</DBCluster>" for c in clusters) + docdb_membersreturn _xml(200, "DescribeDBClustersResponse",f"<DescribeDBClustersResult><DBClusters>{members}</DBClusters></DescribeDBClustersResult>")diff --git a/tests/conftest.py b/tests/conftest.pyindex e2b15d75..c1cd8d6c 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -334,11 +334,6 @@ _SERIAL_TESTS = {"tests/test_iot_data.py::test_mtls_listener_survives_reset","tests/test_iot_data.py::test_mtls_reset_rebinds_with_a_device_connected","tests/test_iot_data.py::test_mtls_shutdown_completes_with_a_device_connected",- # DocDB pymongo tests start real DocumentDB containers and poll wall-clock- # readiness; xdist load makes the timing unreliable.- "tests/test_docdb.py::test_docdb_pymongo_shared_endpoint",- "tests/test_docdb.py::test_docdb_pymongo_v8_connects",- "tests/test_docdb.py::test_docdb_pymongo_tls_connects",}@@ -550,25 +545,7 @@ def rds():@pytest.fixture(scope="session")def docdb():- """A boto3 ``docdb`` client routed through a DocDB-prefixed hostname.-- DocumentDB shares RDS's signing name (``rds``) and Query API version- (2014-10-31), so credential-scope routing cannot tell the two apart.- MiniStack dispatches on the endpoint host instead; pointing the client at- ``docdb.<ENDPOINT_HOST>`` (with getaddrinfo patched so the name resolves- to ENDPOINT_HOST) makes the Host header carry that signal while every- request still reaches the same server.- """- endpoint = ENDPOINT.replace(f"//{ENDPOINT_HOST}", f"//docdb.{ENDPOINT_HOST}", 1)- with patch_endpoint_dns():- yield boto3.client(- "docdb",- endpoint_url=endpoint,- aws_access_key_id="test",- aws_secret_access_key="test",- region_name=REGION,- config=Config(**_default_config_kwargs),- )+ return make_client("docdb")@pytest.fixture(scope="session")diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex b04a3f83..0b20c545 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -34620,3 +34620,75 @@ def test_cfn_rds_custom_named_parameter_group_cannot_be_replaced(cfn):assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"finally:_delete_cfn_test_stack(cfn, stack_name)++++def _docdb_template(retention):+ username = {"Fn::Join": ["", ["{{resolve:secretsmanager:", {"Ref": "Secret"}, ":SecretString:username}}"]]}+ password = {"Fn::Join": ["", ["{{resolve:secretsmanager:", {"Ref": "Secret"}, ":SecretString:password}}"]]}+ return json.dumps({+ "Resources": {+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.0.0.0/16"}},+ "SubA": {"Type": "AWS::EC2::Subnet", "Properties": {+ "VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.0.1.0/24", "AvailabilityZone": "us-east-1a"}},+ "SubB": {"Type": "AWS::EC2::Subnet", "Properties": {+ "VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.0.2.0/24", "AvailabilityZone": "us-east-1b"}},+ "Subnets": {"Type": "AWS::DocDB::DBSubnetGroup", "Properties": {+ "DBSubnetGroupDescription": "docdb", "SubnetIds": [{"Ref": "SubA"}, {"Ref": "SubB"}]}},+ "Params": {"Type": "AWS::DocDB::DBClusterParameterGroup", "Properties": {+ "Description": "docdb", "Family": "docdb8.0", "Parameters": {"tls": "enabled"}}},+ "Secret": {"Type": "AWS::SecretsManager::Secret", "Properties": {"GenerateSecretString": {+ "SecretStringTemplate": '{"username": "docdbadmin"}', "GenerateStringKey": "password",+ "ExcludeCharacters": '"@/\\'}}},+ "Cluster": {"Type": "AWS::DocDB::DBCluster", "Properties": {+ "MasterUsername": username, "MasterUserPassword": password,+ "DBSubnetGroupName": {"Ref": "Subnets"}, "DBClusterParameterGroupName": {"Ref": "Params"},+ "BackupRetentionPeriod": retention}},+ "Instance": {"Type": "AWS::DocDB::DBInstance", "Properties": {+ "DBClusterIdentifier": {"Ref": "Cluster"}, "DBInstanceClass": "db.r6g.large"}},+ "Attach": {"Type": "AWS::SecretsManager::SecretTargetAttachment", "Properties": {+ "SecretId": {"Ref": "Secret"}, "TargetId": {"Ref": "Cluster"},+ "TargetType": "AWS::DocDB::DBCluster"}},+ },+ "Outputs": {+ "ClusterId": {"Value": {"Ref": "Cluster"}},+ "Endpoint": {"Value": {"Fn::GetAtt": ["Cluster", "Endpoint"]}},+ "Port": {"Value": {"Fn::GetAtt": ["Cluster", "Port"]}},+ "ReadEndpoint": {"Value": {"Fn::GetAtt": ["Cluster", "ReadEndpoint"]}},+ "ResourceId": {"Value": {"Fn::GetAtt": ["Cluster", "ClusterResourceId"]}},+ "InstancePort": {"Value": {"Fn::GetAtt": ["Instance", "Port"]}},+ "SecretArn": {"Value": {"Ref": "Secret"}},+ },+ })+++def test_cfn_docdb_cluster_lifecycle(cfn, sm):+ docdb = make_client("docdb")+ stack = f"docdb-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack, TemplateBody=_docdb_template(1))+ result = _wait_stack(cfn, stack, timeout=120)+ assert result["StackStatus"] == "CREATE_COMPLETE", result+ outputs = {o["OutputKey"]: o["OutputValue"] for o in result["Outputs"]}+ assert outputs["Endpoint"].endswith(".docdb.amazonaws.com")+ assert ".cluster-ro-" in outputs["ReadEndpoint"]+ assert outputs["Port"] == "27017"+ assert outputs["ResourceId"].startswith("cluster-")++ cluster = docdb.describe_db_clusters(DBClusterIdentifier=outputs["ClusterId"])["DBClusters"][0]+ assert cluster["Engine"] == "docdb"+ assert cluster["MasterUsername"] == "docdbadmin"+ assert [m["DBInstanceIdentifier"] for m in cluster["DBClusterMembers"]]+ secret = json.loads(sm.get_secret_value(SecretId=outputs["SecretArn"])["SecretString"])+ assert secret["engine"] == "mongo"+ assert secret["host"] == outputs["Endpoint"]+ assert secret["port"] == 27017++ cfn.update_stack(StackName=stack, TemplateBody=_docdb_template(7))+ assert _wait_stack(cfn, stack, timeout=120)["StackStatus"] == "UPDATE_COMPLETE"+ cluster = docdb.describe_db_clusters(DBClusterIdentifier=outputs["ClusterId"])["DBClusters"][0]+ assert cluster["BackupRetentionPeriod"] == 7++ cfn.delete_stack(StackName=stack)+ assert _wait_stack(cfn, stack, timeout=120)["StackStatus"] == "DELETE_COMPLETE"+ with pytest.raises(ClientError):+ docdb.describe_db_clusters(DBClusterIdentifier=outputs["ClusterId"])diff --git a/tests/test_cfn_docdb.py b/tests/test_cfn_docdb.pydeleted file mode 100644index 3549d781..00000000--- a/tests/test_cfn_docdb.py+++ /dev/null@@ -1,398 +0,0 @@-"""-CloudFormation + CDK support for AWS::DocDB::* resources.--Covers the two layers CDK deployments exercise:-- ``engine._resolve_dynamic_reference(s)`` — CDK L2 assembles- ``{{resolve:secretsmanager:...:SecretString:<key>::}}`` placeholders inside- Fn::Join, so they resolve in a second pass after intrinsics.-- The DocDB provisioners — DBCluster/DBInstance/SubnetGroup/ParameterGroup and- the SecretTargetAttachment linkage resource, deployed end-to-end with a- CDK-shaped template (generated secret feeding MasterUserPassword).-"""--import json-import os-import socket-import time-from urllib.parse import urlparse--import boto3-import pytest-from botocore.config import Config-from botocore.exceptions import ClientError--from ministack.services import secretsmanager as sm-from ministack.services import ssm as ssm_svc-from ministack.services.cloudformation.engine import (- _resolve_dynamic_reference,- _resolve_dynamic_references,-)--# White-box tests assert on service internals by design.-# pylint: disable=protected-access-# pytest fixture injection requires these names.-# pylint: disable=redefined-outer-name---def _endpoint():- return os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")---def _client(service):- return boto3.client(- service,- endpoint_url=_endpoint(),- region_name="us-east-1",- aws_access_key_id="test",- aws_secret_access_key="test",- config=Config(retries={"mode": "standard"}),- )--[email protected](scope="module")-def cfn():- """A CloudFormation client pointed at the MiniStack endpoint."""- return _client("cloudformation")--[email protected](scope="module")-def docdb():- """DocDB client routed via a ``docdb.``-prefixed hostname.-- DocumentDB shares RDS's SigV4 scope, so MiniStack dispatches on the Host- header; the prefixed endpoint plus a getaddrinfo patch (mirroring- conftest's docdb fixture) makes plain-localhost deployments reachable.- """- endpoint = _endpoint()- host = urlparse(endpoint).hostname or "localhost"- real_getaddrinfo = socket.getaddrinfo-- def _patched(h, port, *args, **kwargs):- if isinstance(h, str) and h.endswith(f".{host}"):- h = host- return real_getaddrinfo(h, port, *args, **kwargs)-- socket.getaddrinfo = _patched- try:- yield boto3.client(- "docdb",- endpoint_url=endpoint.replace(f"//{host}", f"//docdb.{host}", 1),- region_name="us-east-1",- aws_access_key_id="test",- aws_secret_access_key="test",- config=Config(retries={"mode": "standard"}),- )- finally:- socket.getaddrinfo = real_getaddrinfo---def _delete_stack_if_exists(client, name, timeout=60):- try:- client.describe_stacks(StackName=name)- except ClientError as exc:- if "does not exist" not in str(exc):- raise- return- client.delete_stack(StackName=name)- _wait_stack(client, name, timeout=timeout)--# ----------------------------------------------------------------------------# Pure-function tests for the secretsmanager dynamic-reference pass-# -----------------------------------------------------------------------------def test_dynref_bare_form_returns_whole_secret():- """A bare secretsmanager reference resolves to the whole secret string."""- sm._secrets["plain-secret"] = {- "ARN": "arn:aws:secretsmanager:us-east-1:000000000000:secret:plain-secret",- "Name": "plain-secret", "DeletedDate": None,- "Versions": {"v1": {"SecretString": "the-whole-string",- "Stages": ["AWSCURRENT"]}},- }- try:- assert _resolve_dynamic_reference(- "{{resolve:secretsmanager:plain-secret}}") == "the-whole-string"- finally:- sm._secrets.pop("plain-secret", None)---def test_dynref_secretstring_key_with_arn():- """CDK emits ARN-based refs whose colons must not break parsing."""- arn = ("arn:aws:secretsmanager:us-east-1:000000000000:"- "secret:docdb-master-AbCdEf")- sm._secrets["docdb-master-AbCdEf"] = {- "ARN": arn, "Name": "docdb-master-AbCdEf", "DeletedDate": None,- "Versions": {"v1": {- "SecretString": json.dumps({"username": "docdbadmin",- "password": "s3cret"}),- "Stages": ["AWSCURRENT"],- }},- }- try:- ref = f"{{{{resolve:secretsmanager:{arn}:SecretString:password::}}}}"- assert _resolve_dynamic_reference(ref) == "s3cret"- ref2 = f"{{{{resolve:secretsmanager:{arn}:SecretString:username::}}}}"- assert _resolve_dynamic_reference(ref2) == "docdbadmin"- finally:- sm._secrets.pop("docdb-master-AbCdEf", None)---def test_dynref_inside_structure_and_caching():- """Refs resolve inside nested structures and one literal is read once."""- sm._secrets["struct-secret"] = {- "ARN": "arn:test", "Name": "struct-secret", "DeletedDate": None,- "Versions": {"v1": {"SecretString": json.dumps({"user": "admin", "pw": "x"}),- "Stages": ["AWSCURRENT"]}},- }- calls = []- real = sm.resolve_secret_string-- def counting(*args, **kw):- calls.append(args[0])- return real(*args, **kw)-- try:- sm.resolve_secret_string = counting- props = {- "MasterUsername": "{{resolve:secretsmanager:struct-secret:SecretString:user::}}",- "Nested": [{"Pw": "{{resolve:secretsmanager:struct-secret:SecretString:pw::}}"}],- }- out, cache = _resolve_dynamic_references(props)- assert out["MasterUsername"] == "admin"- assert out["Nested"][0]["Pw"] == "x"- # Each distinct literal is resolved exactly once.- assert sorted(cache) == sorted({props["MasterUsername"], props["Nested"][0]["Pw"]})- assert calls == ["struct-secret", "struct-secret"]- # A prior deployment's cache satisfies the pass without store reads.- n = len(calls)- _resolve_dynamic_references(props, cache, reuse_secrets=True)- assert len(calls) == n- finally:- sm.resolve_secret_string = real- sm._secrets.pop("struct-secret", None)---def test_dynref_missing_key_raises():- """A missing SecretString key raises ValueError."""- sm._secrets["tiny-secret"] = {- "ARN": "arn:test", "Name": "tiny-secret", "DeletedDate": None,- "Versions": {"v1": {"SecretString": "{}", "Stages": ["AWSCURRENT"]}},- }- try:- with pytest.raises(ValueError, match="not found in the secret"):- _resolve_dynamic_reference(- "{{resolve:secretsmanager:tiny-secret:SecretString:nope::}}")- finally:- sm._secrets.pop("tiny-secret", None)---def test_dynref_missing_secret_raises():- """An unknown secret name raises ValueError."""- with pytest.raises(ValueError, match="could not be resolved: secret"):- _resolve_dynamic_reference("{{resolve:secretsmanager:no-such-secret-xyz}}")---def test_dynref_ssm_service_resolves_too():- """The same pass resolves ssm references; unsupported services are- refused at CreateStack time by the template pre-flight."""- record = {- "Name": "/docdb/dynref", "Value": "param-value",- "OriginalValue": "param-value", "Type": "String", "KeyId": "",- "Version": 1, "ARN": "arn:aws:ssm:us-east-1:000000000000:parameter/docdb/dynref",- "LastModifiedDate": 0, "DataType": "text", "Description": "",- "Tier": "Standard", "AllowedPattern": "", "Policies": [], "Labels": [],- }- ssm_svc._parameters["/docdb/dynref"] = record- try:- val = {"A": "{{resolve:ssm:/docdb/dynref}}"}- out, _ = _resolve_dynamic_references(val)- assert out["A"] == "param-value"- finally:- ssm_svc._parameters._data.pop(- (ssm_svc.get_account_id(), ssm_svc.get_region(), "/docdb/dynref"), None)---# ----------------------------------------------------------------------------# End-to-end deploy of a CDK-shaped DocumentDB stack-# -----------------------------------------------------------------------------def _wait_stack(client, name, timeout=60):- deadline = time.time() + timeout- while time.time() < deadline:- try:- stacks = client.describe_stacks(StackName=name)["Stacks"]- except ClientError as exc:- if "does not exist" in str(exc):- return {"StackStatus": "DELETE_COMPLETE", "StackName": name}- raise- status = stacks[0]["StackStatus"]- if not status.endswith("_IN_PROGRESS"):- return stacks[0]- time.sleep(0.5)- raise TimeoutError(f"Stack {name} stuck at {status}")---CDK_SHAPE_TEMPLATE = {- "AWSTemplateFormatVersion": "2010-09-09",- "Resources": {- "DocDBSubnets": {- "Type": "AWS::DocDB::DBSubnetGroup",- "Properties": {- "DBSubnetGroupDescription": "demo subnets",- "SubnetIds": ["subnet-aaaa", "subnet-bbbb"],- },- },- # CDK L2 generates the master secret with GenerateSecretString +- # SecretStringTemplate, then Fn::Joins dynamic references to it into- # the cluster's MasterUsername / MasterUserPassword.- "DocDBMasterSecret": {- "Type": "AWS::SecretsManager::Secret",- "Properties": {- "Description": "Master user credentials",- "GenerateSecretString": {- "SecretStringTemplate": "{\"username\": \"docdbadmin\"}",- "GenerateStringKey": "password",- "ExcludeCharacters": "\"@/\\",- },- },- },- "DocDBCluster": {- "Type": "AWS::DocDB::DBCluster",- "Properties": {- "EngineVersion": "5.0.0",- "DBSubnetGroupName": {"Ref": "DocDBSubnets"},- "ManageMasterUserPassword": True,- "MasterUsername": {- "Fn::Join": ["", [- "{{resolve:secretsmanager:",- {"Ref": "DocDBMasterSecret"},- ":SecretString:username::}}",- ]],- },- "MasterUserPassword": {- "Fn::Join": ["", [- "{{resolve:secretsmanager:",- {"Ref": "DocDBMasterSecret"},- ":SecretString:password::}}",- ]],- },- },- },- "DocDBInstance": {- "Type": "AWS::DocDB::DBInstance",- "Properties": {- "DBClusterIdentifier": {"Ref": "DocDBCluster"},- "DBInstanceClass": "db.t3.medium",- "Engine": "docdb",- },- },- "SecretAttachment": {- "Type": "AWS::SecretsManager::SecretTargetAttachment",- "Properties": {- "SecretId": {"Ref": "DocDBMasterSecret"},- "TargetId": {"Ref": "DocDBCluster"},- "TargetType": "AWS::DocDB::DBCluster",- },- },- },- "Outputs": {- "ClusterEndpointPort": {"Value": {"Fn::GetAtt": "DocDBCluster.Endpoint.Port"}},- "InstanceEndpointAddress": {- "Value": {"Fn::GetAtt": "DocDBInstance.Endpoint.Address"}},- },-}---# pytest fixture injection requires these names.-# pylint: disable=redefined-outer-name---def test_cfn_docdb_cdk_shape_stack_lifecycle(cfn, docdb):- """A CDK-shaped stack deploys end to end and deletes cleanly."""- stack_name = "cfn-docdb-cdk-shape"- _delete_stack_if_exists(cfn, stack_name)- cfn.create_stack(StackName=stack_name,- TemplateBody=json.dumps(CDK_SHAPE_TEMPLATE))- result = _wait_stack(cfn, stack_name)- assert result["StackStatus"] == "CREATE_COMPLETE", result.get("StackStatusReason")-- outputs = {o["OutputKey"]: o["OutputValue"] for o in result.get("Outputs", [])}- cluster_port = outputs["ClusterEndpointPort"]- port_ok = cluster_port in ("27017",) or int(cluster_port) >= 27117- assert port_ok- assert outputs["InstanceEndpointAddress"]-- mine = [c for c in docdb.describe_db_clusters()["DBClusters"]- if c["DBClusterIdentifier"].startswith(stack_name)]- assert len(mine) == 1- assert mine[0]["Status"] == "available"- assert mine[0]["MasterUsername"] == "docdbadmin"-- members = [i for i in docdb.describe_db_instances()["DBInstances"]- if i["DBInstanceIdentifier"].startswith(stack_name)]- assert len(members) == 1- port = members[0]["Endpoint"]["Port"]- assert port == 27017 or port >= 27117-- # Stack delete removes instance -> cluster -> DocumentDB containers.- cfn.delete_stack(StackName=stack_name)- done = _wait_stack(cfn, stack_name)- assert done["StackStatus"] == "DELETE_COMPLETE"- remaining = [c for c in docdb.describe_db_clusters()["DBClusters"]- if c["DBClusterIdentifier"].startswith(stack_name)]- assert not remaining---def test_cfn_docdb_cluster_master_user_secret_passthrough(cfn, docdb):- """Explicit MasterUserSecretArn surfaces as DescribeDBClusters.MasterUserSecret."""- template = {- "Resources": {- "Cluster": {- "Type": "AWS::DocDB::DBCluster",- "Properties": {- "EngineVersion": "8.0.0",- "MasterUsername": "root",- "MasterUserPassword": "password123",- "MasterUserSecretArn":- "arn:aws:secretsmanager:us-east-1:000000000000:secret:linked",- },- },- },- }- stack_name = "cfn-docdb-musecret"- _delete_stack_if_exists(cfn, stack_name)- cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))- result = _wait_stack(cfn, stack_name)- assert result["StackStatus"] == "CREATE_COMPLETE", result.get("StackStatusReason")-- clusters = docdb.describe_db_clusters()["DBClusters"]- mine = next(c for c in clusters if c["DBClusterIdentifier"].startswith(stack_name))- resp = docdb.describe_db_clusters(DBClusterIdentifier=mine["DBClusterIdentifier"])- secret = resp["DBClusters"][0].get("MasterUserSecret")- assert secret and secret["SecretArn"].endswith(":linked")- assert secret["SecretStatus"] == "active"---def test_cfn_docdb_bad_engine_version_fails_readably(cfn):- """An unsupported EngineVersion rolls the stack back with a clear reason."""- template = {- "Resources": {- "Cluster": {- "Type": "AWS::DocDB::DBCluster",- "Properties": {- "EngineVersion": "6.0.0",- "MasterUsername": "root",- "MasterUserPassword": "password123",- },- },- },- }- stack_name = "cfn-docdb-badversion"- _delete_stack_if_exists(cfn, stack_name)- cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))- result = _wait_stack(cfn, stack_name)- assert result["StackStatus"] == "ROLLBACK_COMPLETE"- reason = result.get("StackStatusReason") or ""- events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]- failed = [e for e in events if e.get("ResourceStatusReason")]- reasons = " ".join(e["ResourceStatusReason"] for e in failed)- assert "InvalidParameterCombination" in reasons or "InvalidParameterCombination" in reasondiff --git a/tests/test_docdb.py b/tests/test_docdb.pyindex 44c53f1b..9a2c81e7 100644--- a/tests/test_docdb.py+++ b/tests/test_docdb.py@@ -1,764 +1,141 @@-"""-DocumentDB service integration tests.--Covers the control plane (instances, clusters, snapshots, parameter groups,-tags, engine catalog) through the boto3 ``docdb`` client. Docker- and pymongo--gated smoke tests at the bottom connect to the real ``documentdb-local``-container; they skip when either optional dependency is missing.-"""-import importlib.utilimport time+import uuid as _uuid_modimport pytestfrom botocore.exceptions import ClientError-from ministack.services.documentdb import _docker_image_for_docdb--[email protected](scope="module", autouse=True)-def _docdb_teardown_after_module(docdb):- """Tear down every DocumentDB resource after this module's tests.-- Many control-plane tests create clusters whose first member starts a real- DocumentDB container; without this teardown those containers keep running- after the session (the server deliberately leaves containers alive across- restarts for warm-boot reattachment, so it will not reap them on its own).- Scoped to the DocumentDB API on purpose — a full ``/_ministack/reset``- would wipe other services' state mid-session under xdist.- """- yield- try:- for inst in docdb.describe_db_instances()["DBInstances"]:- try:- docdb.delete_db_instance(DBInstanceIdentifier=inst["DBInstanceIdentifier"])- except ClientError:- pass- for cluster in docdb.describe_db_clusters()["DBClusters"]:- try:- docdb.delete_db_cluster(DBClusterIdentifier=cluster["DBClusterIdentifier"])- except ClientError:- pass- for snap in docdb.describe_db_cluster_snapshots()["DBClusterSnapshots"]:- try:- docdb.delete_db_cluster_snapshot(- DBClusterSnapshotIdentifier=snap["DBClusterSnapshotIdentifier"])- except ClientError:- pass- except Exception: # pylint: disable=broad-exception-caught- pass---# ----------------------------------------------------------------------------# Instances (created as cluster members, as the docdb API requires)-# -----------------------------------------------------------------------------def _make_cluster(docdb, cluster_id, **kwargs):- """Create a minimal cluster with the given identifier and overrides."""- params = {- "DBClusterIdentifier": cluster_id,- "Engine": "docdb",- "MasterUsername": "root",- "MasterUserPassword": "password123",- }- params.update(kwargs)- return docdb.create_db_cluster(**params)["DBCluster"]---def test_docdb_create_instance(docdb):- """A cluster member instance reports its parent cluster and endpoint."""- _make_cluster(docdb, "test-docdb-cluster-a")- docdb.create_db_instance(- DBInstanceIdentifier="test-docdb",- DBInstanceClass="db.t3.medium",- Engine="docdb",- DBClusterIdentifier="test-docdb-cluster-a",- )- resp = docdb.describe_db_instances(DBInstanceIdentifier="test-docdb")- instances = resp["DBInstances"]- assert len(instances) == 1- assert instances[0]["DBInstanceIdentifier"] == "test-docdb"- assert instances[0]["Engine"] == "docdb"- assert instances[0]["DBClusterIdentifier"] == "test-docdb-cluster-a"- assert instances[0]["Endpoint"]["Port"] == 27017 or instances[0]["Endpoint"]["Port"] >= 27117+def _wait_available(client, db_id, timeout=120):+ deadline = time.time() + timeout+ while time.time() < deadline:+ instance = client.describe_db_instances(DBInstanceIdentifier=db_id)["DBInstances"][0]+ if instance["DBInstanceStatus"] == "available":+ return instance+ time.sleep(2)+ raise TimeoutError(f"DocumentDB instance {db_id} not available after {timeout}s")-def test_docdb_cluster_member_shares_endpoint(docdb):- """Two members alias one endpoint; exactly one member is the writer."""- _make_cluster(docdb, "member-endpoint-cluster")- a = docdb.create_db_instance(- DBInstanceIdentifier="member-a",- DBInstanceClass="db.t3.medium",- Engine="docdb",- DBClusterIdentifier="member-endpoint-cluster",- )["DBInstance"]- b = docdb.create_db_instance(- DBInstanceIdentifier="member-b",- DBInstanceClass="db.t3.medium",- Engine="docdb",- DBClusterIdentifier="member-endpoint-cluster",- )["DBInstance"]- assert a["Endpoint"] == b["Endpoint"]- cluster = docdb.describe_db_clusters(- DBClusterIdentifier="member-endpoint-cluster")["DBClusters"][0]- members = sorted(m["DBInstanceIdentifier"] for m in cluster["DBClusterMembers"])- assert members == ["member-a", "member-b"]- writers = [m for m in cluster["DBClusterMembers"] if m["IsClusterWriter"]]- assert len(writers) == 1- assert writers[0]["DBInstanceIdentifier"] == "member-a"+def _docdb_cluster(docdb, cluster_id, **kwargs):+ return docdb.create_db_cluster(DBClusterIdentifier=cluster_id, Engine="docdb", MasterUsername="mainuser",+ MasterUserPassword="Passw0rd123", **kwargs)["DBCluster"]-def test_docdb_engines(docdb):- """The catalog lists every supported version with its parameter family."""- resp = docdb.describe_db_engine_versions(Engine="docdb")- versions = {v["EngineVersion"]: v for v in resp["DBEngineVersions"]}- assert set(versions) >= {"5.0.0", "8.0.0"}- assert all(v["Engine"] == "docdb" for v in resp["DBEngineVersions"])- assert versions["5.0.0"]["DBParameterGroupFamily"] == "docdb5.0"- assert versions["8.0.0"]["DBParameterGroupFamily"] == "docdb8.0"+def test_docdb_cluster_defaults(docdb):+ cluster_id = f"docdb-{_uuid_mod.uuid4().hex[:8]}"+ try:+ cluster = _docdb_cluster(docdb, cluster_id)+ assert cluster["Engine"] == "docdb"+ assert cluster["EngineVersion"] == "8.0.0"+ assert cluster["Port"] == 27017+ assert cluster["DBClusterParameterGroup"] == "default.docdb8.0"+ assert cluster["Endpoint"].endswith(".us-east-1.docdb.amazonaws.com")+ assert cluster["ReaderEndpoint"].startswith(f"{cluster_id}.cluster-ro-")+ finally:+ docdb.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)-def test_docdb_unsupported_engine_version_rejected(docdb):- """An engine version outside the catalog raises InvalidParameterCombination."""+def test_docdb_engine_versions(docdb):+ cluster_id = f"docdb-{_uuid_mod.uuid4().hex[:8]}"+ try:+ cluster = _docdb_cluster(docdb, cluster_id, EngineVersion="5.0.0")+ assert cluster["DBClusterParameterGroup"] == "default.docdb5.0"+ finally:+ docdb.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)with pytest.raises(ClientError) as exc:- docdb.create_db_cluster(- DBClusterIdentifier="bad-version-cluster",- Engine="docdb",- MasterUsername="root",- MasterUserPassword="password123",- EngineVersion="6.0.0",- )+ _docdb_cluster(docdb, f"docdb-{_uuid_mod.uuid4().hex[:8]}", EngineVersion="9.9.9")assert exc.value.response["Error"]["Code"] == "InvalidParameterCombination"+ assert exc.value.response["Error"]["Message"] == "Cannot find version 9.9.9 for docdb"-def test_docdb_delete_instance(docdb):- """A deleted instance disappears from DescribeDBInstances."""- _make_cluster(docdb, "delete-instance-cluster")- docdb.create_db_instance(- DBInstanceIdentifier="docdb-del-v2",- DBInstanceClass="db.t3.medium",- Engine="docdb",- DBClusterIdentifier="delete-instance-cluster",- )- # The real DocDB DeleteDBInstance takes only the identifier (no final- # snapshot options — cluster snapshots are the only snapshots).- docdb.delete_db_instance(DBInstanceIdentifier="docdb-del-v2")- with pytest.raises(ClientError) as exc:- docdb.describe_db_instances(DBInstanceIdentifier="docdb-del-v2")- assert exc.value.response["Error"]["Code"] == "DBInstanceNotFound"---def test_docdb_modify_instance(docdb):- """ModifyDBInstance applies the new class to the stored record."""- _make_cluster(docdb, "modify-instance-cluster")- docdb.create_db_instance(- DBInstanceIdentifier="docdb-mod-v2",- DBInstanceClass="db.t3.medium",- Engine="docdb",- DBClusterIdentifier="modify-instance-cluster",- )- docdb.modify_db_instance(- DBInstanceIdentifier="docdb-mod-v2",- DBInstanceClass="db.t3.large",- ApplyImmediately=True,- )- inst = docdb.describe_db_instances(DBInstanceIdentifier="docdb-mod-v2")["DBInstances"][0]- assert inst["DBInstanceClass"] == "db.t3.large"---def test_docdb_deletion_protection(docdb):- """Deletion protection is cluster-level; DeleteDBInstance is refused."""- # See note [1] in the docstring: members inherit the cluster's live flag.- _make_cluster(docdb, "protected-cluster", DeletionProtection=True)- docdb.create_db_instance(- DBInstanceIdentifier="docdb-protected",- DBInstanceClass="db.t3.medium",- Engine="docdb",- DBClusterIdentifier="protected-cluster",- )+def test_docdb_instance_lifecycle_and_tags(docdb, rds):+ cluster_id = f"docdb-{_uuid_mod.uuid4().hex[:8]}"+ db_id = f"{cluster_id}-1"+ _docdb_cluster(docdb, cluster_id, Tags=[{"Key": "team", "Value": "a"}])try:- with pytest.raises(ClientError) as exc:- docdb.delete_db_instance(DBInstanceIdentifier="docdb-protected")- assert exc.value.response["Error"]["Code"] == "InvalidParameterCombination"+ instance = docdb.create_db_instance(DBInstanceIdentifier=db_id, DBInstanceClass="db.r6g.large",+ Engine="docdb", DBClusterIdentifier=cluster_id)["DBInstance"]+ assert instance["Engine"] == "docdb"+ assert instance["DBClusterIdentifier"] == cluster_id+ _wait_available(docdb, db_id)+ members = docdb.describe_db_clusters(DBClusterIdentifier=cluster_id)["DBClusters"][0]["DBClusterMembers"]+ assert [m["DBInstanceIdentifier"] for m in members] == [db_id]+ assert db_id in [i["DBInstanceIdentifier"] for i in docdb.describe_db_instances()["DBInstances"]]++ # One control plane: the rds client sees the cluster, and the engine filter selects it.+ assert cluster_id in [c["DBClusterIdentifier"] for c in rds.describe_db_clusters()["DBClusters"]]+ filtered = docdb.describe_db_clusters(Filters=[{"Name": "engine", "Values": ["docdb"]}])["DBClusters"]+ assert cluster_id in [c["DBClusterIdentifier"] for c in filtered]++ arn = docdb.describe_db_clusters(DBClusterIdentifier=cluster_id)["DBClusters"][0]["DBClusterArn"]+ docdb.add_tags_to_resource(ResourceName=arn, Tags=[{"Key": "env", "Value": "dev"}])+ tags = docdb.list_tags_for_resource(ResourceName=arn)["TagList"]+ assert {"Key": "team", "Value": "a"} in tags and {"Key": "env", "Value": "dev"} in tags++ docdb.stop_db_cluster(DBClusterIdentifier=cluster_id)+ assert docdb.describe_db_clusters(DBClusterIdentifier=cluster_id)["DBClusters"][0]["Status"] == "stopped"+ docdb.start_db_cluster(DBClusterIdentifier=cluster_id)+ deadline = time.time() + 120+ while docdb.describe_db_clusters(DBClusterIdentifier=cluster_id)["DBClusters"][0]["Status"] != "available":+ assert time.time() < deadline+ time.sleep(1)+ docdb.delete_db_instance(DBInstanceIdentifier=db_id)finally:- docdb.modify_db_cluster(- DBClusterIdentifier="protected-cluster",- DeletionProtection=False,- ApplyImmediately=True,- )- docdb.delete_db_instance(DBInstanceIdentifier="docdb-protected")---def test_docdb_tags(docdb):- """Create-time tags round-trip through add/list/remove tag actions."""- _make_cluster(docdb, "tag-cluster", Tags=[{"Key": "env", "Value": "dev"}])- docdb.create_db_instance(- DBInstanceIdentifier="docdb-tag-v2",- DBInstanceClass="db.t3.medium",- Engine="docdb",- DBClusterIdentifier="tag-cluster",- )- arn = docdb.describe_db_clusters(- DBClusterIdentifier="tag-cluster")["DBClusters"][0]["DBClusterArn"]-- tags = docdb.list_tags_for_resource(ResourceName=arn)["TagList"]- assert any(t["Key"] == "env" and t["Value"] == "dev" for t in tags)-- docdb.add_tags_to_resource(ResourceName=arn, Tags=[{"Key": "team", "Value": "dba"}])- tags2 = docdb.list_tags_for_resource(ResourceName=arn)["TagList"]- assert any(t["Key"] == "team" and t["Value"] == "dba" for t in tags2)-- docdb.remove_tags_from_resource(ResourceName=arn, TagKeys=["env"])- tags3 = docdb.list_tags_for_resource(ResourceName=arn)["TagList"]- assert not any(t["Key"] == "env" for t in tags3)- assert any(t["Key"] == "team" for t in tags3)---def test_docdb_tags_unknown_resource_404(docdb):- """Unknown ResourceName raises the matching documented fault (404).-- Error codes are per the botocore docdb model: the shape names end in- Fault but DBClusterNotFoundFault keeps its name, while the instance and- snapshot faults serialize as DBInstanceNotFound / DBSnapshotNotFound.- """- bad_arn = "arn:aws:rds:us-east-1:000000000000:cluster:no-such-cluster"- with pytest.raises(ClientError) as exc:- docdb.list_tags_for_resource(ResourceName=bad_arn)- assert exc.value.response["Error"]["Code"] == "DBClusterNotFoundFault"- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404-+ deadline = time.time() + 60+ while docdb.describe_db_clusters(DBClusterIdentifier=cluster_id)["DBClusters"][0]["DBClusterMembers"]:+ if time.time() > deadline:+ break+ time.sleep(1)+ docdb.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)with pytest.raises(ClientError) as exc:- docdb.add_tags_to_resource(- ResourceName=bad_arn, Tags=[{"Key": "k", "Value": "v"}])+ docdb.describe_db_clusters(DBClusterIdentifier=cluster_id)assert exc.value.response["Error"]["Code"] == "DBClusterNotFoundFault"- with pytest.raises(ClientError) as exc:- docdb.remove_tags_from_resource(ResourceName=bad_arn, TagKeys=["k"])- assert exc.value.response["Error"]["Code"] == "DBClusterNotFoundFault"-- bad_db_arn = "arn:aws:rds:us-east-1:000000000000:db:no-such-instance"- with pytest.raises(ClientError) as exc:- docdb.list_tags_for_resource(ResourceName=bad_db_arn)- assert exc.value.response["Error"]["Code"] == "DBInstanceNotFound"-- bad_snap_arn = "arn:aws:rds:us-east-1:000000000000:cluster-snapshot:no-such-snap"- with pytest.raises(ClientError) as exc:- docdb.list_tags_for_resource(ResourceName=bad_snap_arn)- assert exc.value.response["Error"]["Code"] == "DBSnapshotNotFound"---def test_docdb_tags_missing_resource_name(docdb):- """Missing ResourceName raises MissingParameter for all three actions."""- with pytest.raises(ClientError) as exc:- docdb.list_tags_for_resource(ResourceName="")- assert exc.value.response["Error"]["Code"] == "MissingParameter"-- with pytest.raises(ClientError) as exc:- docdb.add_tags_to_resource(ResourceName="", Tags=[{"Key": "k", "Value": "v"}])- assert exc.value.response["Error"]["Code"] == "MissingParameter"-- with pytest.raises(ClientError) as exc:- docdb.remove_tags_from_resource(ResourceName="", TagKeys=["k"])- assert exc.value.response["Error"]["Code"] == "MissingParameter"---def test_docdb_tags_on_subnet_group_and_param_group(docdb):- """Group-ARN resolution tags subnet/parameter groups like live resources."""- docdb.create_db_subnet_group(- DBSubnetGroupName="tag-subnets",- DBSubnetGroupDescription="tags test",- SubnetIds=["subnet-aaaa", "subnet-bbbb"],- )- sg_arn = docdb.describe_db_subnet_groups(- DBSubnetGroupName="tag-subnets")["DBSubnetGroups"][0]["DBSubnetGroupArn"]- docdb.add_tags_to_resource(- ResourceName=sg_arn, Tags=[{"Key": "net", "Value": "yes"}])- assert docdb.list_tags_for_resource(ResourceName=sg_arn)["TagList"] == [- {"Key": "net", "Value": "yes"}]- docdb.delete_db_subnet_group(DBSubnetGroupName="tag-subnets")-- docdb.create_db_cluster_parameter_group(- DBClusterParameterGroupName="tag-pg",- DBParameterGroupFamily="docdb5.0",- Description="tags test",- )- pg_arn = docdb.describe_db_cluster_parameter_groups(- DBClusterParameterGroupName="tag-pg")["DBClusterParameterGroups"][0][- "DBClusterParameterGroupArn"]- docdb.add_tags_to_resource(- ResourceName=pg_arn, Tags=[{"Key": "cfg", "Value": "yes"}])- assert docdb.list_tags_for_resource(ResourceName=pg_arn)["TagList"] == [- {"Key": "cfg", "Value": "yes"}]- docdb.delete_db_cluster_parameter_group(DBClusterParameterGroupName="tag-pg")---def test_docdb_orderable_options(docdb):- """Orderable options exist for the requested engine version only."""- resp = docdb.describe_orderable_db_instance_options(Engine="docdb", EngineVersion="8.0.0")- options = resp["OrderableDBInstanceOptions"]- assert options- assert all(o["EngineVersion"] == "8.0.0" for o in options)---# ----------------------------------------------------------------------------# Cluster snapshots (metadata-only)-# -----------------------------------------------------------------------------def test_docdb_cluster_snapshot_crud(docdb):- """Cluster snapshots create, list, and delete; duplicates are refused."""- _make_cluster(docdb, "snapshot-cluster")-- snap = docdb.create_db_cluster_snapshot(- DBClusterSnapshotIdentifier="snap-1",- DBClusterIdentifier="snapshot-cluster",- )["DBClusterSnapshot"]- assert snap["Status"] == "available"- assert snap["DBClusterIdentifier"] == "snapshot-cluster"- assert snap["EngineVersion"] in ("5.0.0", "8.0.0")-- with pytest.raises(ClientError) as exc:- docdb.create_db_cluster_snapshot(- DBClusterSnapshotIdentifier="snap-1",- DBClusterIdentifier="snapshot-cluster",- )- assert exc.value.response["Error"]["Code"] == "DBClusterSnapshotAlreadyExistsFault"-- desc = docdb.describe_db_cluster_snapshots(DBClusterSnapshotIdentifier="snap-1")- assert len(desc["DBClusterSnapshots"]) == 1-- by_cluster = docdb.describe_db_cluster_snapshots(DBClusterIdentifier="snapshot-cluster")- assert any(- s["DBClusterSnapshotIdentifier"] == "snap-1" for s in by_cluster["DBClusterSnapshots"])-- docdb.delete_db_cluster_snapshot(DBClusterSnapshotIdentifier="snap-1")- with pytest.raises(ClientError) as exc:- docdb.describe_db_cluster_snapshots(DBClusterSnapshotIdentifier="snap-1")- assert exc.value.response["Error"]["Code"] == "DBClusterSnapshotNotFoundFault"---def test_docdb_cluster_snapshot_attributes(docdb):- """Snapshot restore attributes add and remove account IDs."""- _make_cluster(docdb, "attribute-cluster")- docdb.create_db_cluster_snapshot(- DBClusterSnapshotIdentifier="snap-attrs",- DBClusterIdentifier="attribute-cluster",- )-- attrs = docdb.describe_db_cluster_snapshot_attributes(DBClusterSnapshotIdentifier="snap-attrs")- result = attrs["DBClusterSnapshotAttributesResult"]- restore = next(- a for a in result["DBClusterSnapshotAttributes"] if a["AttributeName"] == "restore")- assert "000000000000" in restore["AttributeValues"]-- mod = docdb.modify_db_cluster_snapshot_attribute(- DBClusterSnapshotIdentifier="snap-attrs",- AttributeName="restore",- ValuesToAdd=["111111111111"],- )- result = mod["DBClusterSnapshotAttributesResult"]- restore = next(- a for a in result["DBClusterSnapshotAttributes"]- if a["AttributeName"] == "restore"- )- assert set(restore["AttributeValues"]) >= {"000000000000", "111111111111"}-- mod2 = docdb.modify_db_cluster_snapshot_attribute(- DBClusterSnapshotIdentifier="snap-attrs",- AttributeName="restore",- ValuesToRemove=["111111111111"],- )- result = mod2["DBClusterSnapshotAttributesResult"]- restore = next(- a for a in result["DBClusterSnapshotAttributes"]- if a["AttributeName"] == "restore"- )- assert "111111111111" not in restore["AttributeValues"]-- docdb.delete_db_cluster_snapshot(DBClusterSnapshotIdentifier="snap-attrs")---# ----------------------------------------------------------------------------# Cluster parameter groups-# -----------------------------------------------------------------------------def test_docdb_cluster_parameter_group_crud(docdb):- """A parameter group creates, describes, and deletes cleanly."""- docdb.create_db_cluster_parameter_group(- DBClusterParameterGroupName="pg-crud",- DBParameterGroupFamily="docdb5.0",- Description="crud test group",- )- groups = docdb.describe_db_cluster_parameter_groups(DBClusterParameterGroupName="pg-crud")- pg = groups["DBClusterParameterGroups"][0]- assert pg["DBParameterGroupFamily"] == "docdb5.0"- assert pg["Description"] == "crud test group"-- docdb.delete_db_cluster_parameter_group(DBClusterParameterGroupName="pg-crud")- with pytest.raises(ClientError) as exc:- docdb.describe_db_cluster_parameter_groups(DBClusterParameterGroupName="pg-crud")- assert exc.value.response["Error"]["Code"] == "DBParameterGroupNotFound"--def test_docdb_cluster_parameters_modify_reset(docdb):- """Modified parameters persist; a full reset restores engine defaults."""- docdb.create_db_cluster_parameter_group(- DBClusterParameterGroupName="pg-mod",- DBParameterGroupFamily="docdb8.0",- Description="modify/reset test",- )- docdb.modify_db_cluster_parameter_group(- DBClusterParameterGroupName="pg-mod",- Parameters=[{"ParameterName": "ttl_monitor_enabled", "ParameterValue": "false"}],- )-- user_params = docdb.describe_db_cluster_parameters(- DBClusterParameterGroupName="pg-mod", Source="user")- names = [p["ParameterName"] for p in user_params["Parameters"]]- assert "ttl_monitor_enabled" in names-- all_params = docdb.describe_db_cluster_parameters(DBClusterParameterGroupName="pg-mod")- defaults = [p for p in all_params["Parameters"] if p["Source"] == "engine-default"]- assert defaults-- docdb.reset_db_cluster_parameter_group(- DBClusterParameterGroupName="pg-mod",- ResetAllParameters=True,- )- after = docdb.describe_db_cluster_parameters(- DBClusterParameterGroupName="pg-mod", Source="user")- assert after["Parameters"] == []-- docdb.delete_db_cluster_parameter_group(DBClusterParameterGroupName="pg-mod")---# ----------------------------------------------------------------------------# Failover / restore / maintenance / certificates / events-# -----------------------------------------------------------------------------def test_docdb_delete_cluster_refused_while_members_exist(docdb):- """DeleteDBCluster is refused until every member is deleted first."""- _make_cluster(docdb, "occupied-cluster")- docdb.create_db_instance(- DBInstanceIdentifier="occupied-member",- DBInstanceClass="db.t3.medium",- Engine="docdb",- DBClusterIdentifier="occupied-cluster",- )- with pytest.raises(ClientError) as exc:- docdb.delete_db_cluster(DBClusterIdentifier="occupied-cluster")- assert exc.value.response["Error"]["Code"] == "InvalidDBClusterStateFault"-- # AWS ordering: delete the members first, then the cluster.- docdb.delete_db_instance(DBInstanceIdentifier="occupied-member")- docdb.delete_db_cluster(DBClusterIdentifier="occupied-cluster")- with pytest.raises(ClientError) as exc:- docdb.describe_db_clusters(DBClusterIdentifier="occupied-cluster")- assert exc.value.response["Error"]["Code"] == "DBClusterNotFoundFault"---def test_docdb_failover_rotates_writer(docdb):- """Failover promotes the top-tier member; an explicit target wins."""- _make_cluster(docdb, "failover-cluster")- docdb.create_db_instance(- DBInstanceIdentifier="fo-writer",- DBInstanceClass="db.t3.medium",- Engine="docdb",- DBClusterIdentifier="failover-cluster",- PromotionTier=1,- )- docdb.create_db_instance(- DBInstanceIdentifier="fo-reader-tier1",- DBInstanceClass="db.t3.medium",- Engine="docdb",- DBClusterIdentifier="failover-cluster",- PromotionTier=2,- )- docdb.create_db_instance(- DBInstanceIdentifier="fo-reader-tier0",- DBInstanceClass="db.t3.medium",- Engine="docdb",- DBClusterIdentifier="failover-cluster",- PromotionTier=1,- )-- resp = docdb.failover_db_cluster(DBClusterIdentifier="failover-cluster")- cluster = resp["DBCluster"]- # Response carries the transitional status; endpoints are stable.- assert cluster["Status"] == "failing-over"- writers = [m for m in cluster["DBClusterMembers"] if m["IsClusterWriter"]]- assert len(writers) == 1- assert writers[0]["DBInstanceIdentifier"] == "fo-reader-tier0"-- stored = docdb.describe_db_clusters(DBClusterIdentifier="failover-cluster")["DBClusters"][0]- stored_writer = next(m for m in stored["DBClusterMembers"] if m["IsClusterWriter"])- assert stored_writer["DBInstanceIdentifier"] == "fo-reader-tier0"-- explicit = docdb.failover_db_cluster(- DBClusterIdentifier="failover-cluster",- TargetDBInstanceIdentifier="fo-writer",- )["DBCluster"]- writer = next(m for m in explicit["DBClusterMembers"] if m["IsClusterWriter"])- assert writer["DBInstanceIdentifier"] == "fo-writer"---def test_docdb_restore_cluster_from_snapshot(docdb):- """A restore keeps version, user, and identifiers from the snapshot."""- src = _make_cluster(- docdb, "restore-source",- EngineVersion="8.0.0",- )- docdb.create_db_cluster_snapshot(- DBClusterSnapshotIdentifier="snap-restore",- DBClusterIdentifier="restore-source",- )-- restored = docdb.restore_db_cluster_from_snapshot(- DBClusterIdentifier="restored-cluster",- Engine="docdb",- SnapshotIdentifier="snap-restore",- )["DBCluster"]- assert restored["Status"] == "available"- assert restored["EngineVersion"] == src["EngineVersion"] == "8.0.0"- assert restored["MasterUsername"] == src["MasterUsername"] == "root"- assert restored["DBClusterMembers"] == []-- desc = docdb.describe_db_clusters(DBClusterIdentifier="restored-cluster")- assert desc["DBClusters"][0]["DBClusterIdentifier"] == "restored-cluster"---def test_docdb_pending_maintenance_actions(docdb):- """Applied maintenance actions are listable for the same resource."""- arn = docdb.describe_db_clusters(- DBClusterIdentifier="failover-cluster")["DBClusters"][0]["DBClusterArn"]- applied = docdb.apply_pending_maintenance_action(- ResourceIdentifier=arn,- ApplyAction="system-update",- OptInType="immediately",- )- details = applied["ResourcePendingMaintenanceActions"]["PendingMaintenanceActionDetails"]- assert any(a["Action"] == "system-update" for a in details)-- described = docdb.describe_pending_maintenance_actions(ResourceIdentifier=arn)- resources = described["PendingMaintenanceActions"]- assert any(- r["ResourceIdentifier"] == arn- and any(a["Action"] == "system-update" for a in r["PendingMaintenanceActionDetails"])- for r in resources- )---def test_docdb_describe_certificates_and_events(docdb):- """One CA certificate is cataloged; no events are recorded."""- certs = docdb.describe_certificates()["Certificates"]- assert len(certs) == 1- assert certs[0]["CertificateIdentifier"] == "rds-ca-rsa2048-g1"-- events = docdb.describe_events()["Events"]- assert events == []---# ----------------------------------------------------------------------------# Docker image helper tests (always run, no container required)-# -----------------------------------------------------------------------------def test_docker_image_for_docdb_versions():- """The image helper returns the documentdb-local config per version."""- image, env, port, data_path = _docker_image_for_docdb("5.0.0", "root", "secret", "admin")- assert image.endswith("ghcr.io/documentdb/documentdb/documentdb-local:latest") \- or image.endswith("documentdb-local:latest")- assert env["USERNAME"] == "root"- assert env["PASSWORD"] == "secret"- assert env["DOCUMENTDB_PORT"] == "27017"- assert port == 27017- assert data_path == "/data"-- image8, _, port8, data_path8 = _docker_image_for_docdb("8.0.0", "root", "secret", "admin")- assert image8 == image- assert port8 == 27017- assert data_path8 == "/data"---def test_docker_image_for_docdb_unknown_version_same_image():- """An unknown version maps to the one image that backs the catalog."""- # See note [1] in the docstring of _docker_image_for_docdb.- image, _, _, _ = _docker_image_for_docdb("9.9.9", "root", "secret")- known, _, _, _ = _docker_image_for_docdb("5.0.0", "root", "secret")- assert image == known---def test_docker_image_prefix_honored(monkeypatch):- """MINISTACK_IMAGE_PREFIX is applied to the image reference."""- monkeypatch.setenv("MINISTACK_IMAGE_PREFIX", "mirror.example.com/")-- image, _, _, _ = _docker_image_for_docdb("8.0.0", "root", "secret")- assert image == (- "mirror.example.com/ghcr.io/documentdb/documentdb/documentdb-local:latest"- )---# ----------------------------------------------------------------------------# Pymongo integration (Docker + pymongo gated)-# -----------------------------------------------------------------------------def _docker_available():- try:- import docker # pylint: disable=import-outside-toplevel # optional-dep probe- docker.from_env().ping()- return True- except Exception: # pylint: disable=broad-exception-caught- return False---def _pymongo_available():- return importlib.util.find_spec("pymongo") is not None---def test_docdb_pymongo_shared_endpoint(docdb):- """Cluster members share one mongo endpoint: writes via A are visible via B."""- if not _pymongo_available():- pytest.skip("pymongo not installed")- if not _docker_available():- pytest.skip("Docker not available for DocDB container launch")-- import pymongo # pylint: disable=import-outside-toplevel # imported after skip guards-- _make_cluster(docdb, "smoke-cluster")- for member_id in ("smoke-a", "smoke-b"):- docdb.create_db_instance(- DBInstanceIdentifier=member_id,- DBInstanceClass="db.t3.medium",- Engine="docdb",- DBClusterIdentifier="smoke-cluster",- )-- deadline = time.time() + 300- while time.time() < deadline:- instances = docdb.describe_db_instances(- Filters=[{"Name": "db-cluster-id", "Values": ["smoke-cluster"]}])["DBInstances"]- identifiers = {i["DBInstanceIdentifier"] for i in instances}- if {"smoke-a", "smoke-b"} <= identifiers and all(- i["DBInstanceStatus"] == "available" for i in instances- ):- break- time.sleep(2)- else:- raise TimeoutError("DocDB members not available after 300s")-- ep_a = next(i["Endpoint"] for i in instances if i["DBInstanceIdentifier"] == "smoke-a")- ep_b = next(i["Endpoint"] for i in instances if i["DBInstanceIdentifier"] == "smoke-b")- assert ep_a == ep_b-- client_a = pymongo.MongoClient(- ep_a["Address"], int(ep_a["Port"]),- username="root", password="password123",- serverSelectionTimeoutMS=120000, directConnection=True,- )- client_b = pymongo.MongoClient(- ep_b["Address"], int(ep_b["Port"]),- username="root", password="password123",- serverSelectionTimeoutMS=120000, directConnection=True,- )[email protected]_plane+def test_docdb_instance_serves_the_mongodb_protocol(docdb):+ pymongo = pytest.importorskip("pymongo")+ cluster_id = f"docdb-{_uuid_mod.uuid4().hex[:8]}"+ db_id = f"{cluster_id}-1"+ _docdb_cluster(docdb, cluster_id)try:- client_a.smoketest.items.insert_one({"k": 1, "msg": "visible through member B"})- found = client_b.smoketest.items.find_one({"k": 1})- assert found is not None- assert found["msg"] == "visible through member B"+ docdb.create_db_instance(DBInstanceIdentifier=db_id, DBInstanceClass="db.r6g.large",+ Engine="docdb", DBClusterIdentifier=cluster_id)+ endpoint = _wait_available(docdb, db_id, timeout=300)["Endpoint"]+ client = pymongo.MongoClient(endpoint["Address"], int(endpoint["Port"]), username="mainuser",+ password="Passw0rd123", tls=True, tlsAllowInvalidCertificates=True,+ directConnection=True, serverSelectionTimeoutMS=60000)+ client.app.items.insert_one({"k": "v"})+ assert client.app.items.find_one({"k": "v"}, {"_id": 0}) == {"k": "v"}+ client.close()finally:- client_a.close()- client_b.close()-- for member_id in ("smoke-a", "smoke-b"):- docdb.delete_db_instance(DBInstanceIdentifier=member_id)- docdb.delete_db_cluster(DBClusterIdentifier="smoke-cluster")---def test_docdb_pymongo_v8_connects(docdb):- """- A DocDB 8.0.0 cluster member accepts wire connections (documentdb-local).- """- if not _pymongo_available():- pytest.skip("pymongo not installed")- if not _docker_available():- pytest.skip("Docker not available for DocDB container launch")-- import pymongo # pylint: disable=import-outside-toplevel # imported after skip guards-- _make_cluster(docdb, "v8-cluster", EngineVersion="8.0.0")- docdb.create_db_instance(- DBInstanceIdentifier="v8-member",- DBInstanceClass="db.t3.medium",- Engine="docdb",- DBClusterIdentifier="v8-cluster",- )- inst = docdb.describe_db_instances(DBInstanceIdentifier="v8-member")["DBInstances"][0]- assert inst["EngineVersion"] == "8.0.0"- ep = inst["Endpoint"]-- client = pymongo.MongoClient(- ep["Address"], int(ep["Port"]),- username="root", password="password123",- serverSelectionTimeoutMS=120000, directConnection=True,- )+ docdb.delete_db_instance(DBInstanceIdentifier=db_id)+ deadline = time.time() + 60+ while docdb.describe_db_clusters(DBClusterIdentifier=cluster_id)["DBClusters"][0]["DBClusterMembers"]:+ if time.time() > deadline:+ break+ time.sleep(1)+ docdb.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)+++def test_docdb_and_rds_share_the_cluster_listing(docdb, rds):+ docdb_id = f"docdb-{_uuid_mod.uuid4().hex[:8]}"+ rds_id = f"aurora-{_uuid_mod.uuid4().hex[:8]}"+ _docdb_cluster(docdb, docdb_id)+ rds.create_db_cluster(DBClusterIdentifier=rds_id, Engine="aurora-postgresql",+ MasterUsername="mainuser", MasterUserPassword="Passw0rd123")try:- db = client["v8check"]- coll = db["items"]- coll.insert_one({"k": 8})- found = coll.find_one({"k": 8})- assert found is not None+ assert rds.describe_db_clusters(DBClusterIdentifier=rds_id)["DBClusters"][0]["Engine"] == "aurora-postgresql"+ listed = {c["DBClusterIdentifier"]: c["Engine"] for c in docdb.describe_db_clusters()["DBClusters"]}+ assert listed[docdb_id] == "docdb" and listed[rds_id] == "aurora-postgresql"+ only_docdb = docdb.describe_db_clusters(Filters=[{"Name": "engine", "Values": ["docdb"]}])["DBClusters"]+ assert docdb_id in [c["DBClusterIdentifier"] for c in only_docdb]+ assert rds_id not in [c["DBClusterIdentifier"] for c in only_docdb]finally:- client.close()- docdb.delete_db_instance(DBInstanceIdentifier="v8-member")- docdb.delete_db_cluster(DBClusterIdentifier="v8-cluster")---def test_docdb_pymongo_tls_connects(docdb):- """- The same endpoint accepts TLS with the container's self-signed cert.-- The documentdb-local gateway always serves TLS; its tlsMode default- (allowTLS) accepts plaintext, and clients can also connect explicitly- with tls=true. The self-signed certificate requires- tlsAllowInvalidCertificates=true.- """- if not _pymongo_available():- pytest.skip("pymongo not installed")- if not _docker_available():- pytest.skip("Docker not available for DocDB container launch")+ docdb.delete_db_cluster(DBClusterIdentifier=docdb_id, SkipFinalSnapshot=True)+ rds.delete_db_cluster(DBClusterIdentifier=rds_id, SkipFinalSnapshot=True)- import pymongo # pylint: disable=import-outside-toplevel # imported after skip guards- _make_cluster(docdb, "tls-cluster")- docdb.create_db_instance(- DBInstanceIdentifier="tls-member",- DBInstanceClass="db.t3.medium",- Engine="docdb",- DBClusterIdentifier="tls-cluster",- )-- deadline = time.time() + 300- while time.time() < deadline:- instances = docdb.describe_db_instances(- DBInstanceIdentifier="tls-member")["DBInstances"]- if instances and instances[0]["DBInstanceStatus"] == "available":- break- time.sleep(2)- else:- raise TimeoutError("DocDB member not available after 300s")-- ep = instances[0]["Endpoint"]- client = pymongo.MongoClient(- ep["Address"], int(ep["Port"]),- username="root", password="password123",- serverSelectionTimeoutMS=120000, directConnection=True,- tls=True, tlsAllowInvalidCertificates=True,- )- try:- db = client["tlscheck"]- coll = db["items"]- coll.insert_one({"k": "tls"})- found = coll.find_one({"k": "tls"})- assert found is not None- finally:- client.close()- docdb.delete_db_instance(DBInstanceIdentifier="tls-member")- docdb.delete_db_cluster(DBClusterIdentifier="tls-cluster")+def test_docdb_cluster_parameter_group_must_exist(docdb):+ with pytest.raises(ClientError) as exc:+ _docdb_cluster(docdb, f"docdb-{_uuid_mod.uuid4().hex[:8]}", DBClusterParameterGroupName="missing-group")+ assert exc.value.response["Error"]["Code"] == "DBClusterParameterGroupNotFound"