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
Feat/v1.0.3 improvements (#4)
Nahuel Nucera66512754df74
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f9fc4f0b..0e8a041a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,86 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [0.2.0] — 2026-03-25++### Added++**API Gateway HTTP API v2** (completing roadmap item)+- Full control plane: CreateApi, GetApi, GetApis, UpdateApi, DeleteApi+- Routes: CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute+- Integrations: CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration+- Stages: CreateStage, GetStage, GetStages, UpdateStage, DeleteStage+- Deployments: CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment+- Tags: TagResource, UntagResource, GetTags+- Data plane: execute-api requests routed by host header (`{apiId}.execute-api.localhost`)+- Lambda proxy (AWS_PROXY) invocation via API Gateway v2 payload format 2.0+- HTTP proxy (HTTP_PROXY) forwarding to arbitrary HTTP backends+- Route path parameter matching (`{param}` placeholders in route keys)+- State persistence support via `get_state()` / `load_persisted_state()`++**SNS → SQS Fanout** (completing roadmap item)+- SNS subscriptions with `sqs` protocol deliver messages directly to SQS queues+- Message envelope follows AWS SNS JSON notification format+- Fanout is synchronous within the same process++**SQS → Lambda Event Source Mapping**+- `CreateEventSourceMapping` / `DeleteEventSourceMapping` / `GetEventSourceMapping` / `ListEventSourceMappings` / `UpdateEventSourceMapping`+- Background poller delivers SQS messages to Lambda functions as batched events+- Configurable batch size and enabled/disabled state++**Lambda Warm/Cold Start Worker Pool** (`core/lambda_runtime.py`)+- Persistent Python subprocess per function — handler module imported once (cold start)+- Subsequent invocations reuse the warm worker without re-importing+- Worker respawns automatically on crash+- Accurately models AWS Lambda cold/warm start behavior++**State Persistence Infrastructure** (`core/persistence.py`)+- `PERSIST_STATE=1` environment variable enables persistence+- `STATE_DIR` environment variable controls storage location (default `/tmp/ministack-state`)+- Atomic file writes (write-to-tmp then rename) prevent corruption on crash+- API Gateway state persisted across container restarts+- Persistence framework ready for other services to adopt++### Fixed+- `_path_matches` bug in API Gateway: `re.escape` was applied before `{param}` substitution,+ causing all parameterised routes to never match. Fixed by splitting on `{param}` segments,+ escaping literal parts, then joining with `[^/]+` wildcards.+- `execute-api` credential scope in `core/router.py` incorrectly mapped to `lambda`;+ corrected to `apigateway`.++### Infrastructure+- `app.py`: API Gateway registered in `SERVICE_HANDLERS`, BANNER, and `SERVICE_NAME_ALIASES`+- `app.py`: Execute-api data plane dispatched before normal service routing via host-header match+- `app.py`: Persistence load/save wired into ASGI lifespan startup/shutdown+- `core/router.py`: API Gateway patterns added; `/v2/apis` path detection added+- `tests/conftest.py`: `apigw` fixture added (`apigatewayv2` boto3 client)+- `tests/test_services.py`: fixed 4 tests that used hardcoded resource names and collided on repeated runs (`test_kinesis_stream_encryption`, `test_kinesis_enhanced_monitoring`, `test_sfn_start_sync_execution`, `test_sfn_describe_state_machine_for_execution`)+- `tests/test_services.py`: added 10 new tests covering previously untested paths — health endpoint, STS `GetSessionToken`, DynamoDB TTL enable/disable, Lambda warm start, API Gateway execute-api Lambda proxy, `$default` catch-all route, path parameter matching, 404 on missing route, EventBridge → Lambda target dispatch+- `tests/test_services.py`: added 25 new tests covering all new operations introduced since v0.1.0 — Kinesis `SplitShard`/`MergeShards`/`UpdateShardCount`/`RegisterStreamConsumer`/`DeregisterStreamConsumer`/`ListStreamConsumers`, SSM `LabelParameterVersion`/`AddTagsToResource`/`RemoveTagsFromResource`, CloudWatch Logs retention policy/subscription filters/metric filters/tag APIs/Insights, CloudWatch composite alarms/`DescribeAlarmsForMetric`/`DescribeAlarmHistory`, EventBridge archives/permissions, DynamoDB `UpdateTable`, S3 bucket versioning/encryption/lifecycle/CORS/ACL, Athena `UpdateWorkGroup`/`BatchGetNamedQuery`/`BatchGetQueryExecution`+- `README.md`: updated supported operations tables to reflect all new operations across all 21 services+- 371 integration tests — all passing (up from 54 in v0.1.0)++### Fixed (post-release patches)+- **SNS → Lambda fanout**: `protocol == "lambda"` subscriptions now invoke the Lambda function via `_execute_function()` with a standard `Records[].Sns` event envelope (was a no-op stub)+- **DynamoDB TTL enforcement**: background daemon thread (`dynamodb-ttl-reaper`) now scans every 60 s and deletes items whose TTL attribute value is ≤ current epoch time+- **Lambda Function URLs**: `CreateFunctionUrlConfig`, `GetFunctionUrlConfig`, `UpdateFunctionUrlConfig`, `DeleteFunctionUrlConfig`, `ListFunctionUrlConfigs` — full CRUD, persisted in `_function_urls` dict; was a 404 stub+- **`/_ministack/reset` disk cleanup**: when `PERSIST_STATE=1`, reset now also deletes `STATE_DIR/*.json` and `S3_DATA_DIR` contents so a subsequent restart does not reload old state+- **API Gateway `{proxy+}` greedy path matching**: `_path_matches` now handles `{param+}` placeholders matching multiple path segments (e.g. `/files/{proxy+}` matches `/files/a/b/c`)+- **API Gateway `routeKey` in Lambda event**: Lambda proxy event `routeKey` now reflects the matched route key (e.g. `"GET /ping"`) instead of always being `"$default"`+- **API Gateway Authorizers**: `CreateAuthorizer`, `GetAuthorizer`, `GetAuthorizers`, `UpdateAuthorizer`, `DeleteAuthorizer` — full CRUD for JWT and Lambda authorizers; state included in persistence snapshot+- **Test idempotency**: added `POST /_ministack/reset` endpoint and session-scoped `autouse` fixture so the test suite passes on repeated runs against the same server without restarting+- 377 integration tests — all passing (6 new tests covering the above gaps)++### Roadmap Update+The following roadmap items from v0.1.0 are now **completed**:+- ✅ API Gateway (REST + HTTP APIs) — HTTP API v2 delivered+- ✅ SNS → SQS fan-out delivery+- ✅ DynamoDB transactions (TransactWriteItems, TransactGetItems)+- ✅ S3 multipart upload+- ✅ SQS FIFO queues++---+## [0.1.0] — 2024-03-24Initial public release. Built as a free, open-source alternative to LocalStack.diff --git a/Dockerfile b/Dockerfileindex 3f21c8a3..69479794 100644--- a/Dockerfile+++ b/Dockerfile@@ -3,16 +3,12 @@ FROM python:3.12-alpineLABEL maintainer="MiniStack" \description="Local AWS Service Emulator — drop-in LocalStack replacement"-# Upgrade all base packages to pick up latest security patches,-# then install nothing extra — curl/unzip removed to eliminate CVEs.-# Upgrade base packages and remove busybox wget (CVE-2025-60876 - HTTP header injection)-# wget is not used in this image; removing it eliminates the attack surface entirely.+# Upgrade base packages to pick up latest security patches.RUN apk upgrade --no-cache && rm -f /usr/bin/wget /bin/wgetWORKDIR /opt/ministack-# Upgrade pip to latest to clear pip CVEs, then install app deps.-# httptools/duckdb require C compilation on musl — excluded intentionally.+# Install all Python dependencies.RUN pip install --no-cache-dir --upgrade pip && \pip install --no-cache-dir \uvicorn==0.30.6 \@@ -23,10 +19,10 @@ COPY core/ core/COPY services/ services/COPY app.py .-RUN mkdir -p /tmp/localstack-data/s3--# Run as non-rootRUN addgroup -S ministack && adduser -S ministack -G ministack+RUN mkdir -p /tmp/localstack-data/s3 && chown -R ministack:ministack /tmp/localstack-data+RUN mkdir -p /docker-entrypoint-initaws.d && chown ministack:ministack /docker-entrypoint-initaws.d+VOLUME /docker-entrypoint-initaws.dUSER ministackENV GATEWAY_PORT=4566 \@@ -37,6 +33,7 @@ ENV GATEWAY_PORT=4566 \REDIS_PORT=6379 \RDS_BASE_PORT=15432 \ELASTICACHE_BASE_PORT=16379 \+ LAMBDA_EXECUTOR=local \PYTHONUNBUFFERED=1EXPOSE 4566diff --git a/README.md b/README.mdindex 657c1962..5542f720 100644--- a/README.md+++ b/README.md@@ -24,7 +24,7 @@LocalStack recently moved its core services behind a paid plan. If you relied on LocalStack Community for local development and CI/CD pipelines, MiniStack is your free alternative.-- **20 AWS services** emulated on a single port (4566)+- **21 AWS services** emulated on a single port (4566)- **Drop-in compatible** — works with `boto3`, AWS CLI, Terraform, CDK, Pulumi, any SDK- **Real infrastructure** — RDS spins up actual Postgres/MySQL containers, ElastiCache spins up real Redis, Athena runs real SQL via DuckDB, ECS runs real Docker containers- **Tiny footprint** — ~150MB image, ~30MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM@@ -167,36 +167,37 @@ sfn.create_state_machine(| Service | Operations | Notes ||---------|-----------|-------|-| **S3** | CreateBucket, DeleteBucket, ListBuckets, HeadBucket, PutObject, GetObject, DeleteObject, HeadObject, CopyObject, ListObjects v1/v2, DeleteObjects | Optional disk persistence via `S3_PERSIST=1` |-| **SQS** | CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes, SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage, ChangeMessageVisibility, SendMessageBatch, DeleteMessageBatch | Both Query API and JSON protocol |-| **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, Publish | |-| **DynamoDB** | CreateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem | |-| **Lambda** | CreateFunction, DeleteFunction, GetFunction, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration | Python runtimes actually execute; others return mock |-| **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, CreatePolicy, AttachRolePolicy, PutRolePolicy, CreateAccessKey, ListAccessKeys | |+| **S3** | CreateBucket, DeleteBucket, ListBuckets, HeadBucket, PutObject, GetObject, DeleteObject, HeadObject, CopyObject, ListObjects v1/v2, DeleteObjects, GetBucketVersioning, PutBucketVersioning, GetBucketEncryption, PutBucketEncryption, DeleteBucketEncryption, GetBucketLifecycleConfiguration, PutBucketLifecycleConfiguration, DeleteBucketLifecycle, GetBucketCors, PutBucketCors, DeleteBucketCors, GetBucketAcl, PutBucketAcl, GetBucketTagging, PutBucketTagging, DeleteBucketTagging, GetBucketPolicy, PutBucketPolicy, DeleteBucketPolicy, GetBucketNotificationConfiguration, PutBucketNotificationConfiguration, GetBucketLogging, PutBucketLogging, ListObjectVersions, CreateMultipartUpload, UploadPart, CompleteMultipartUpload, AbortMultipartUpload | Optional disk persistence via `S3_PERSIST=1` |+| **SQS** | CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes, SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage, ChangeMessageVisibility, ChangeMessageVisibilityBatch, SendMessageBatch, DeleteMessageBatch, TagQueue, UntagQueue, ListQueueTags | Both Query API and JSON protocol; FIFO queues with deduplication; DLQ support |+| **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, CreatePlatformEndpoint | SNS→SQS fanout delivery; SNS→Lambda fanout (synchronous invocation) |+| **DynamoDB** | CreateTable, UpdateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems, DescribeTimeToLive, UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints, TagResource, UntagResource, ListTagsOfResource | TTL enforced via background reaper (60s cadence) |+| **Lambda** | CreateFunction, DeleteFunction, GetFunction, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, ListVersionsByFunction, PublishVersion, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs | Python runtimes actually execute with warm worker pool; SQS event source mapping; Function URL CRUD |+| **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, CreatePolicy, GetPolicy, DeletePolicy, AttachRolePolicy, DetachRolePolicy, PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies, ListAttachedRolePolicies, CreateAccessKey, ListAccessKeys, DeleteAccessKey, CreateInstanceProfile, GetInstanceProfile, DeleteInstanceProfile, AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile, ListInstanceProfiles, CreateGroup, GetGroup, AddUserToGroup, RemoveUserFromGroup, CreateServiceLinkedRole, CreateOpenIDConnectProvider, TagRole, UntagRole, TagUser, UntagUser, TagPolicy, UntagPolicy | || **STS** | GetCallerIdentity, AssumeRole, GetSessionToken | |-| **SecretsManager** | CreateSecret, GetSecretValue, ListSecrets, DeleteSecret, UpdateSecret, DescribeSecret, PutSecretValue | |-| **CloudWatch Logs** | CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents | |+| **SecretsManager** | CreateSecret, GetSecretValue, ListSecrets, DeleteSecret, UpdateSecret, DescribeSecret, PutSecretValue, RestoreSecret, RotateSecret, GetRandomPassword, ListSecretVersionIds, TagResource, UntagResource, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy, ValidateResourcePolicy | |+| **CloudWatch Logs** | CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents, PutRetentionPolicy, DeleteRetentionPolicy, PutSubscriptionFilter, DeleteSubscriptionFilter, DescribeSubscriptionFilters, PutMetricFilter, DeleteMetricFilter, DescribeMetricFilters, TagLogGroup, UntagLogGroup, ListTagsLogGroup, TagResource, UntagResource, ListTagsForResource, StartQuery, GetQueryResults, StopQuery, PutDestination, DeleteDestination, DescribeDestinations | |### Extended Services| Service | Operations | Notes ||---------|-----------|-------|-| **SSM Parameter Store** | PutParameter, GetParameter, GetParameters, GetParametersByPath, DeleteParameter, DeleteParameters, DescribeParameters | Supports String, SecureString, StringList |-| **EventBridge** | CreateEventBus, DeleteEventBus, ListEventBuses, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, PutEvents | |-| **Kinesis** | CreateStream, DeleteStream, DescribeStream, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords | Partition key → shard routing |-| **CloudWatch Metrics** | PutMetricData, GetMetricStatistics, ListMetrics, PutMetricAlarm, DescribeAlarms, DeleteAlarms, SetAlarmState | |-| **SES** | SendEmail, SendRawEmail, VerifyEmailIdentity, ListIdentities, GetIdentityVerificationAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics | Emails stored in-memory, not sent |-| **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StopExecution, DescribeExecution, ListExecutions, GetExecutionHistory | |+| **SSM Parameter Store** | PutParameter, GetParameter, GetParameters, GetParametersByPath, DeleteParameter, DeleteParameters, DescribeParameters, GetParameterHistory, LabelParameterVersion, AddTagsToResource, RemoveTagsFromResource, ListTagsForResource | Supports String, SecureString, StringList |+| **EventBridge** | CreateEventBus, DeleteEventBus, ListEventBuses, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, PutEvents, TagResource, UntagResource, ListTagsForResource, CreateArchive, DeleteArchive, DescribeArchive, ListArchives, PutPermission, RemovePermission, CreateConnection, DescribeConnection, DeleteConnection, ListConnections, CreateApiDestination, DescribeApiDestination, DeleteApiDestination, ListApiDestinations | Lambda target dispatch on PutEvents |+| **Kinesis** | CreateStream, DeleteStream, DescribeStream, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords, MergeShards, SplitShard, UpdateShardCount, StartStreamEncryption, StopStreamEncryption, EnableEnhancedMonitoring, DisableEnhancedMonitoring, RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers, DescribeStreamConsumer, AddTagsToStream, RemoveTagsFromStream, ListTagsForStream | Partition key → shard routing |+| **CloudWatch Metrics** | PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics, PutMetricAlarm, PutCompositeAlarm, DescribeAlarms, DescribeAlarmsForMetric, DescribeAlarmHistory, DeleteAlarms, SetAlarmState, EnableAlarmActions, DisableAlarmActions, TagResource, UntagResource, ListTagsForResource, PutDashboard, GetDashboard, DeleteDashboards, ListDashboards | CBOR and JSON protocol |+| **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates | Emails stored in-memory, not sent |+| **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel |+| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags | HTTP API (v2) protocol; Lambda proxy (AWS_PROXY) and HTTP proxy (HTTP_PROXY) integrations; data plane via `{apiId}.execute-api.localhost`; `{param}` and `{proxy+}` path matching; JWT/Lambda authorizer CRUD |### Infrastructure Services (with real Docker execution)| Service | Operations | Real Execution ||---------|-----------|----------------|-| **ECS** | CreateCluster, DeleteCluster, DescribeClusters, ListClusters, RegisterTaskDefinition, DeregisterTaskDefinition, ListTaskDefinitions, CreateService, DeleteService, DescribeServices, UpdateService, ListServices, RunTask, StopTask, DescribeTasks, ListTasks | `RunTask` starts real Docker containers via Docker socket |-| **RDS** | CreateDBInstance, DeleteDBInstance, DescribeDBInstances, StartDBInstance, StopDBInstance, RebootDBInstance, ModifyDBInstance, CreateDBCluster, DeleteDBCluster, DescribeDBClusters, CreateDBSubnetGroup, DescribeDBSubnetGroups, CreateDBParameterGroup, DescribeDBParameterGroups, DescribeDBEngineVersions | `CreateDBInstance` spins up real Postgres/MySQL Docker container, returns actual `host:port` endpoint |-| **ElastiCache** | CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters, ModifyCacheCluster, CreateReplicationGroup, DeleteReplicationGroup, DescribeReplicationGroups, CreateCacheSubnetGroup, DescribeCacheSubnetGroups, CreateCacheParameterGroup, DescribeCacheParameterGroups, DescribeCacheEngineVersions | `CreateCacheCluster` spins up real Redis/Memcached Docker container |-| **Glue** | CreateDatabase, DeleteDatabase, GetDatabase, GetDatabases, CreateTable, DeleteTable, GetTable, GetTables, UpdateTable, BatchDeleteTable, CreatePartition, GetPartitions, BatchCreatePartition, CreateConnection, GetConnections, CreateCrawler, GetCrawler, StartCrawler, CreateJob, GetJob, GetJobs, StartJobRun, GetJobRun, GetJobRuns | Python shell jobs actually execute via subprocess |-| **Athena** | StartQueryExecution, GetQueryExecution, GetQueryResults, StopQueryExecution, ListQueryExecutions, CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results |+| **ECS** | CreateCluster, UpdateCluster, DeleteCluster, DescribeClusters, ListClusters, RegisterTaskDefinition, DeregisterTaskDefinition, DescribeTaskDefinition, ListTaskDefinitions, CreateService, DeleteService, DescribeServices, UpdateService, ListServices, RunTask, StopTask, DescribeTasks, ListTasks, CreateCapacityProvider, DeleteCapacityProvider, DescribeCapacityProviders, PutClusterCapacityProviders, TagResource, UntagResource, ListTagsForResource | `RunTask` starts real Docker containers via Docker socket |+| **RDS** | CreateDBInstance, DeleteDBInstance, DescribeDBInstances, StartDBInstance, StopDBInstance, RebootDBInstance, ModifyDBInstance, CreateDBCluster, DeleteDBCluster, DescribeDBClusters, StartDBCluster, StopDBCluster, CreateDBSubnetGroup, DescribeDBSubnetGroups, ModifyDBSubnetGroup, DeleteDBSubnetGroup, CreateDBParameterGroup, DescribeDBParameterGroups, ModifyDBParameterGroup, DeleteDBParameterGroup, DescribeDBParameters, CreateDBClusterParameterGroup, DescribeDBEngineVersions, DescribeOrderableDBInstanceOptions, CreateDBSnapshot, DeleteDBSnapshot, DescribeDBSnapshots, CreateDBClusterSnapshot, DeleteDBClusterSnapshot, DescribeDBClusterSnapshots, CreateDBInstanceReadReplica, RestoreDBInstanceFromDBSnapshot, CreateOptionGroup, DescribeOptionGroups, AddTagsToResource, RemoveTagsFromResource, ListTagsForResource | `CreateDBInstance` spins up real Postgres/MySQL Docker container, returns actual `host:port` endpoint |+| **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, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, DescribeEvents | `CreateCacheCluster` spins up real Redis/Memcached Docker container |+| **Glue** | CreateDatabase, DeleteDatabase, GetDatabase, GetDatabases, CreateTable, DeleteTable, GetTable, GetTables, UpdateTable, BatchDeleteTable, CreatePartition, GetPartitions, BatchCreatePartition, BatchGetPartition, CreatePartitionIndex, GetPartitionIndexes, CreateConnection, GetConnections, CreateCrawler, UpdateCrawler, GetCrawler, GetCrawlerMetrics, StartCrawler, CreateJob, GetJob, GetJobs, StartJobRun, GetJobRun, GetJobRuns, CreateTrigger, GetTrigger, DeleteTrigger, UpdateTrigger, StartTrigger, StopTrigger, ListTriggers, GetTriggers, CreateWorkflow, GetWorkflow, DeleteWorkflow, UpdateWorkflow, StartWorkflowRun, CreateSecurityConfiguration, GetSecurityConfiguration, GetSecurityConfigurations, DeleteSecurityConfiguration, CreateClassifier, GetClassifier, GetClassifiers, DeleteClassifier, TagResource, UntagResource, GetTags | Python shell jobs actually execute via subprocess |+| **Athena** | StartQueryExecution, GetQueryExecution, GetQueryResults, StopQueryExecution, ListQueryExecutions, BatchGetQueryExecution, CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, UpdateWorkGroup, CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries, BatchGetNamedQuery, CreateDataCatalog, GetDataCatalog, ListDataCatalogs, DeleteDataCatalog, UpdateDataCatalog, CreatePreparedStatement, GetPreparedStatement, DeletePreparedStatement, ListPreparedStatements, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; result pagination; column type metadata |---@@ -337,6 +338,26 @@ ecs.stop_task(cluster="dev", task=task_arn)| `REDIS_PORT` | `6379` | Redis port for ElastiCache fallback || `RDS_BASE_PORT` | `15432` | Starting host port for RDS containers || `ELASTICACHE_BASE_PORT` | `16379` | Starting host port for ElastiCache containers |+| `PERSIST_STATE` | `0` | Set `1` to persist service state across restarts |+| `STATE_DIR` | `/tmp/ministack-state` | Directory for persisted state files |++### State Persistence++When `PERSIST_STATE=1`, MiniStack saves service state to `STATE_DIR` on shutdown and reloads it on startup. Writes are atomic (write-to-tmp then rename) to prevent corruption on crash.++Services currently supporting persistence: **API Gateway**++```bash+docker run -p 4566:4566 \+ -e PERSIST_STATE=1 \+ -e STATE_DIR=/data/ministack-state \+ -v /tmp/ministack-data:/data \+ nahuelnucera/ministack+```++### Lambda Warm Starts++MiniStack keeps Python Lambda functions warm between invocations. After the first call (cold start), the handler module stays imported in a persistent subprocess. Subsequent calls skip the import step, matching real AWS warm-start behaviour and making test suites significantly faster.---@@ -363,7 +384,7 @@ ecs.stop_task(cluster="dev", task=task_arn)│ │ SSM EventBridge Kinesis │ ││ │ CloudWatch SES StepFunctions │ ││ │ ECS RDS ElastiCache │ │- │ │ Glue Athena │ │+ │ │ Glue Athena API Gateway │ ││ └──────────────────────────────────┘ ││ ││ In-Memory Storage + Optional Docker │@@ -386,20 +407,19 @@ pip install boto3 pytest duckdb docker cbor2# Start MiniStackdocker compose up -d-# Run the full test suite (56 tests across all 20 services)+# Run the full test suite (377 tests across all 21 services)pytest tests/ -v```Expected output:```-collected 54 items+collected 377 itemstests/test_services.py::test_s3_create_bucket PASSED-tests/test_services.py::test_s3_put_get PASSED...-tests/test_services.py::test_athena_workgroup PASSED+tests/test_services.py::test_lambda_function_url_config PASSED-56 passed in 7.6s+377 passed in ~12s```---@@ -438,6 +458,7 @@ provider "aws" {logs = "http://localhost:4566"events = "http://localhost:4566"ses = "http://localhost:4566"+ apigateway = "http://localhost:4566"}}```@@ -482,7 +503,7 @@ config:| **ECS (real Docker containers)** | ✅ | ❌ | ✅ || **Athena (real SQL via DuckDB)** | ✅ | ❌ | ✅ || **Glue Data Catalog + Jobs** | ✅ | ❌ | ✅ |-| API Gateway | ❌ | ✅ | ✅ |+| **API Gateway v2 (HTTP API)** | ✅ | ✅ | ✅ || Cognito | ❌ | ✅ | ✅ || CloudFormation | ❌ | partial | ✅ || Cost | **Free** | Was free, now paid | $35+/mo |diff --git a/app.py b/app.pyindex 3b646a27..4400c8bf 100644--- a/app.py+++ b/app.py@@ -6,18 +6,25 @@ Compatible with AWS CLI, boto3, and any AWS SDK via --endpoint-url."""import os+import reimport json+import uuidimport asyncioimport logging+import subprocessfrom urllib.parse import parse_qs, urlparse+# Matches host headers like "{apiId}.execute-api.localhost" or "{apiId}.execute-api.localhost:4566"+_EXECUTE_API_RE = re.compile(r"^([a-f0-9]{8})\.execute-api\.localhost(?::\d+)?$")+from core.router import detect_service, extract_region, extract_account_id+from core.persistence import save_all, load_state, PERSIST_STATEfrom services import s3, sqs, sns, dynamodb, lambda_svc, secretsmanager, cloudwatch_logsfrom services import ssm, eventbridge, kinesis, cloudwatch, ses, stepfunctionsfrom services import ecs, rds, elasticache, glue, athena+from services import apigatewayfrom services.iam_sts import handle_iam_request, handle_sts_request-# Configure loggingLOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()logging.basicConfig(level=getattr(logging, LOG_LEVEL, logging.INFO),@@ -26,7 +33,6 @@ logging.basicConfig()logger = logging.getLogger("ministack")-# Service handler mappingSERVICE_HANDLERS = {"s3": s3.handle_request,"sqs": sqs.handle_request,@@ -48,8 +54,42 @@ SERVICE_HANDLERS = {"elasticache": elasticache.handle_request,"glue": glue.handle_request,"athena": athena.handle_request,+ "apigateway": apigateway.handle_request,+}++SERVICE_NAME_ALIASES = {+ "cloudwatch-logs": "logs",+ "cloudwatch": "monitoring",+ "eventbridge": "events",+ "step-functions": "states",+ "stepfunctions": "states",+ "execute-api": "apigateway",+ "apigatewayv2": "apigateway",}++def _resolve_port():+ """Resolve gateway port: GATEWAY_PORT > EDGE_PORT > 4566."""+ return os.environ.get("GATEWAY_PORT") or os.environ.get("EDGE_PORT") or "4566"+++if os.environ.get("LOCALSTACK_PERSISTENCE") == "1" and os.environ.get("S3_PERSIST") != "1":+ os.environ["S3_PERSIST"] = "1"+ logger.info("LOCALSTACK_PERSISTENCE=1 detected — enabling S3_PERSIST")++_services_env = os.environ.get("SERVICES", "").strip()+if _services_env:+ _requested = {s.strip() for s in _services_env.split(",") if s.strip()}+ _resolved = set()+ for _name in _requested:+ _key = SERVICE_NAME_ALIASES.get(_name, _name)+ if _key in SERVICE_HANDLERS:+ _resolved.add(_key)+ else:+ logger.warning("SERVICES: unknown service '%s' (resolved as '%s') — skipping", _name, _key)+ SERVICE_HANDLERS = {k: v for k, v in SERVICE_HANDLERS.items() if k in _resolved}+ logger.info("SERVICES filter active — enabled: %s", sorted(SERVICE_HANDLERS.keys()))+BANNER = r"""__ __ _ _ ____ _ _| \/ (_)_ __ (_) ___|| |_ __ _ ___| | __@@ -60,7 +100,7 @@ BANNER = r"""Local AWS Service Emulator — Port {port}Services: S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, SecretsManager, CloudWatch Logs,SSM, EventBridge, Kinesis, CloudWatch, SES, Step Functions,- ECS, RDS, ElastiCache, Glue, Athena+ ECS, RDS, ElastiCache, Glue, Athena, API Gateway"""@@ -73,7 +113,6 @@ async def app(scope, receive, send):if scope["type"] != "http":return- # Read requestmethod = scope["method"]path = scope["path"]query_string = scope.get("query_string", b"").decode("utf-8")@@ -90,13 +129,61 @@ async def app(scope, receive, send):if not message.get("more_body", False):break- # Health check endpoints- if path in ("/_localstack/health", "/health", "/_ministack/health"):+ request_id = str(uuid.uuid4())++ if path == "/_ministack/reset" and method == "POST":+ _reset_all_state()await _send_response(send, 200, {"Content-Type": "application/json"},- json.dumps({"status": "running", "services": {s: "available" for s in SERVICE_HANDLERS}}).encode())+ json.dumps({"reset": "ok"}).encode())+ return++ if path in ("/_localstack/health", "/health", "/_ministack/health"):+ await _send_response(send, 200, {+ "Content-Type": "application/json",+ "x-amzn-requestid": request_id,+ }, json.dumps({+ "services": {s: "available" for s in SERVICE_HANDLERS},+ "edition": "light",+ "version": "3.0.0.dev",+ }).encode())+ return++ if method == "OPTIONS":+ await _send_response(send, 200, {+ "Access-Control-Allow-Origin": "*",+ "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH",+ "Access-Control-Allow-Headers": "*",+ "Access-Control-Expose-Headers": "*",+ "Access-Control-Max-Age": "86400",+ "Content-Length": "0",+ "x-amzn-requestid": request_id,+ }, b"")+ return++ # API Gateway execute-api data plane: host = {apiId}.execute-api.localhost[:{port}]+ host = headers.get("host", "")+ _execute_match = _EXECUTE_API_RE.match(host)+ if _execute_match:+ api_id = _execute_match.group(1)+ # Path format: /{stage}/{proxy+} or just /{proxy+} if stage is $default+ path_parts = path.lstrip("/").split("/", 1)+ stage = path_parts[0] if path_parts else "$default"+ execute_path = "/" + path_parts[1] if len(path_parts) > 1 else "/"+ try:+ status, resp_headers, resp_body = await apigateway.handle_execute(+ api_id, stage, execute_path, method, headers, body, query_params+ )+ except Exception as e:+ logger.exception(f"Error in execute-api dispatch: {e}")+ status, resp_headers, resp_body = 500, {"Content-Type": "application/json"}, json.dumps({"message": str(e)}).encode()+ resp_headers.update({+ "Access-Control-Allow-Origin": "*",+ "x-amzn-requestid": request_id,+ "x-amz-request-id": request_id,+ })+ await _send_response(send, status, resp_headers, resp_body)return- # Detect target serviceservice = detect_service(method, path, headers, query_params)region = extract_region(headers)@@ -116,13 +203,14 @@ async def app(scope, receive, send):json.dumps({"__type": "InternalError", "message": str(e)}).encode())return- # Add CORS headers (same as LocalStack)resp_headers.update({"Access-Control-Allow-Origin": "*","Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH","Access-Control-Allow-Headers": "*","Access-Control-Expose-Headers": "*",- "x-amzn-requestid": headers.get("x-amzn-requestid", ""),+ "x-amzn-requestid": request_id,+ "x-amz-request-id": request_id,+ "x-amz-id-2": request_id,})await _send_response(send, status, resp_headers, resp_body)@@ -147,18 +235,112 @@ async def _handle_lifespan(scope, receive, send):while True:message = await receive()if message["type"] == "lifespan.startup":- port = os.environ.get("GATEWAY_PORT", "4566")+ port = _resolve_port()logger.info(BANNER.format(port=port))+ _run_init_scripts()+ if PERSIST_STATE:+ _load_persisted_state()await send({"type": "lifespan.startup.complete"})elif message["type"] == "lifespan.shutdown":logger.info("MiniStack shutting down...")+ if PERSIST_STATE:+ save_all({"apigateway": apigateway.get_state})await send({"type": "lifespan.shutdown.complete"})return+def _load_persisted_state():+ """Load persisted state for services that support it."""+ data = load_state("apigateway")+ if data:+ apigateway.load_persisted_state(data)+ logger.info("Loaded persisted state for apigateway")+++def _run_init_scripts():+ """Execute .sh scripts from /docker-entrypoint-initaws.d/ in alphabetical order."""+ init_dir = "/docker-entrypoint-initaws.d"+ if not os.path.isdir(init_dir):+ return+ scripts = sorted(f for f in os.listdir(init_dir) if f.endswith(".sh"))+ if not scripts:+ return+ logger.info("Found %d init script(s) in %s", len(scripts), init_dir)+ for script in scripts:+ script_path = os.path.join(init_dir, script)+ logger.info("Running init script: %s", script_path)+ try:+ result = subprocess.run(+ ["sh", script_path], env=os.environ,+ capture_output=True, text=True, timeout=300,+ )+ if result.stdout:+ logger.info(" stdout: %s", result.stdout.rstrip())+ if result.returncode != 0:+ logger.error("Init script %s failed (exit %d): %s", script_path, result.returncode, result.stderr)+ else:+ logger.info("Init script %s completed successfully", script_path)+ except subprocess.TimeoutExpired:+ logger.error("Init script %s timed out after 300s", script_path)+ except Exception as e:+ logger.error("Failed to execute init script %s: %s", script_path, e)+++def _reset_all_state():+ """Wipe all in-memory state across every service module, and persisted files if enabled."""+ import shutil+ from services.iam_sts import reset as _iam_reset+ from core.persistence import STATE_DIR, PERSIST_STATE+ from services.s3 import DATA_DIR as S3_DATA_DIR, PERSIST as S3_PERSIST++ for mod, fn in [+ (s3, s3.reset), (sqs, sqs.reset), (sns, sns.reset),+ (dynamodb, dynamodb.reset), (lambda_svc, lambda_svc.reset),+ (secretsmanager, secretsmanager.reset), (cloudwatch_logs, cloudwatch_logs.reset),+ (ssm, ssm.reset), (eventbridge, eventbridge.reset), (kinesis, kinesis.reset),+ (cloudwatch, cloudwatch.reset), (ses, ses.reset),+ (stepfunctions, stepfunctions.reset), (ecs, ecs.reset),+ (rds, rds.reset), (elasticache, elasticache.reset),+ (glue, glue.reset), (athena, athena.reset),+ (apigateway, apigateway.reset),+ ]:+ try:+ fn()+ except Exception as e:+ logger.warning("reset() failed for %s: %s", mod.__name__, e)+ try:+ _iam_reset()+ except Exception as e:+ logger.warning("reset() failed for iam_sts: %s", e)++ # Wipe persisted files so a subsequent restart doesn't reload old state+ if PERSIST_STATE and os.path.isdir(STATE_DIR):+ for fname in os.listdir(STATE_DIR):+ if fname.endswith(".json"):+ try:+ os.remove(os.path.join(STATE_DIR, fname))+ except Exception as e:+ logger.warning("reset: failed to remove %s: %s", fname, e)+ logger.info("Wiped persisted state files in %s", STATE_DIR)++ if S3_PERSIST and os.path.isdir(S3_DATA_DIR):+ for entry in os.listdir(S3_DATA_DIR):+ entry_path = os.path.join(S3_DATA_DIR, entry)+ try:+ if os.path.isdir(entry_path):+ shutil.rmtree(entry_path)+ else:+ os.remove(entry_path)+ except Exception as e:+ logger.warning("reset: failed to remove S3 data %s: %s", entry, e)+ logger.info("Wiped S3 persisted data in %s", S3_DATA_DIR)++ logger.info("State reset complete")++def main():import uvicorn- port = int(os.environ.get("GATEWAY_PORT", "4566"))+ port = int(_resolve_port())uvicorn.run("app:app", host="0.0.0.0", port=port, log_level=LOG_LEVEL.lower())diff --git a/core/lambda_runtime.py b/core/lambda_runtime.pynew file mode 100644index 00000000..a4d44c58--- /dev/null+++ b/core/lambda_runtime.py@@ -0,0 +1,196 @@+"""+Lambda warm/cold start worker pool.+Each function gets a persistent Python worker process that imports the handler+once (cold start) and then handles subsequent invocations without re-importing (warm).+"""++import os+import sys+import json+import time+import base64+import zipfile+import tempfile+import threading+import subprocess+import logging++logger = logging.getLogger("lambda_runtime")++# function_name -> Worker+_workers: dict = {}+_lock = threading.Lock()++# Worker script that runs inside the subprocess+_WORKER_SCRIPT = '''+import sys, json, importlib, traceback, os++def run():+ # Read init payload: {"code_dir": "...", "module": "...", "handler": "...", "env": {...}}+ init = json.loads(sys.stdin.readline())+ code_dir = init["code_dir"]+ module_name = init["module"]+ handler_name = init["handler"]+ env = init.get("env", {})++ # Apply env vars+ os.environ.update(env)++ # Import handler module (cold start)+ sys.path.insert(0, code_dir)+ try:+ mod = importlib.import_module(module_name)+ handler_fn = getattr(mod, handler_name)+ sys.stdout.write(json.dumps({"status": "ready", "cold": True}) + "\\n")+ sys.stdout.flush()+ except Exception as e:+ sys.stdout.write(json.dumps({"status": "error", "error": str(e)}) + "\\n")+ sys.stdout.flush()+ return++ # Event loop+ while True:+ line = sys.stdin.readline()+ if not line:+ break+ event = json.loads(line)+ context = type("Context", (), {+ "function_name": init.get("function_name", ""),+ "memory_limit_in_mb": init.get("memory", 128),+ "invoked_function_arn": init.get("arn", ""),+ "aws_request_id": event.get("_request_id", ""),+ })()+ try:+ result = handler_fn(event, context)+ sys.stdout.write(json.dumps({"status": "ok", "result": result}) + "\\n")+ except Exception as e:+ sys.stdout.write(json.dumps({"status": "error", "error": str(e), "trace": traceback.format_exc()}) + "\\n")+ sys.stdout.flush()++run()+'''+++class Worker:+ def __init__(self, func_name: str, config: dict, code_zip: bytes):+ self.func_name = func_name+ self.config = config+ self.code_zip = code_zip+ self._proc = None+ self._tmpdir = None+ self._lock = threading.Lock()+ self._cold = True+ self._start_time = None++ def _spawn(self):+ """Extract zip and start worker process."""+ self._tmpdir = tempfile.mkdtemp(prefix=f"ministack-lambda-{self.func_name}-")++ # Write worker script+ worker_path = os.path.join(self._tmpdir, "_worker.py")+ with open(worker_path, "w") as f:+ f.write(_WORKER_SCRIPT)++ # Extract function code+ code_dir = os.path.join(self._tmpdir, "code")+ os.makedirs(code_dir)+ with open(os.path.join(self._tmpdir, "code.zip"), "wb") as f:+ f.write(self.code_zip)+ with zipfile.ZipFile(os.path.join(self._tmpdir, "code.zip")) as zf:+ zf.extractall(code_dir)++ handler = self.config.get("Handler", "index.handler")+ module_name, handler_name = handler.rsplit(".", 1)+ env_vars = self.config.get("Environment", {}).get("Variables", {})++ self._proc = subprocess.Popen(+ [sys.executable, worker_path],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ bufsize=1,+ )++ # Send init payload+ init = {+ "code_dir": code_dir,+ "module": module_name,+ "handler": handler_name,+ "env": env_vars,+ "function_name": self.config.get("FunctionName", ""),+ "memory": self.config.get("MemorySize", 128),+ "arn": self.config.get("FunctionArn", ""),+ }+ self._proc.stdin.write(json.dumps(init) + "\n")+ self._proc.stdin.flush()++ # Wait for ready+ response_line = self._proc.stdout.readline()+ response = json.loads(response_line)+ if response.get("status") != "ready":+ raise RuntimeError(f"Worker init failed: {response.get('error')}")++ self._start_time = time.time()+ logger.info(f"Lambda worker spawned for {self.func_name} (cold start)")++ def invoke(self, event: dict, request_id: str) -> dict:+ with self._lock:+ cold = self._cold++ # Spawn if not running+ if self._proc is None or self._proc.poll() is not None:+ self._spawn()+ cold = True+ self._cold = False+ else:+ cold = False++ event["_request_id"] = request_id+ try:+ self._proc.stdin.write(json.dumps(event) + "\n")+ self._proc.stdin.flush()+ response_line = self._proc.stdout.readline()+ if not response_line:+ raise RuntimeError("Worker process died")+ response = json.loads(response_line)+ response["cold_start"] = cold+ return response+ except Exception as e:+ self._proc = None # force respawn next time+ return {"status": "error", "error": str(e), "cold_start": cold}++ def kill(self):+ if self._proc and self._proc.poll() is None:+ self._proc.terminate()+ self._proc = None+ if self._tmpdir and os.path.exists(self._tmpdir):+ import shutil+ shutil.rmtree(self._tmpdir, ignore_errors=True)+++def get_or_create_worker(func_name: str, config: dict, code_zip: bytes) -> Worker:+ with _lock:+ worker = _workers.get(func_name)+ if worker is None:+ worker = Worker(func_name, config, code_zip)+ _workers[func_name] = worker+ return worker+++def invalidate_worker(func_name: str):+ """Kill and remove worker when function is updated or deleted."""+ with _lock:+ worker = _workers.pop(func_name, None)+ if worker:+ worker.kill()+++def reset():+ """Terminate all warm workers and clear the pool."""+ for worker in list(_workers.values()):+ try:+ worker.proc.terminate()+ except Exception:+ pass+ _workers.clear()diff --git a/core/persistence.py b/core/persistence.pynew file mode 100644index 00000000..d55b8dea--- /dev/null+++ b/core/persistence.py@@ -0,0 +1,55 @@+"""+State persistence for MiniStack services.+When PERSIST_STATE=1, service state is saved to STATE_DIR on shutdown+and reloaded on startup.+"""++import os+import json+import logging+import tempfile++logger = logging.getLogger("persistence")++PERSIST_STATE = os.environ.get("PERSIST_STATE", "0") == "1"+STATE_DIR = os.environ.get("STATE_DIR", "/tmp/ministack-state")+++def save_state(service: str, data: dict) -> None:+ if not PERSIST_STATE:+ return+ try:+ os.makedirs(STATE_DIR, exist_ok=True)+ path = os.path.join(STATE_DIR, f"{service}.json")+ tmp = path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(data, f)+ os.replace(tmp, path)+ logger.info(f"Persistence: saved {service} state to {path}")+ except Exception as e:+ logger.error(f"Persistence: failed to save {service}: {e}")+++def load_state(service: str) -> dict | None:+ if not PERSIST_STATE:+ return None+ path = os.path.join(STATE_DIR, f"{service}.json")+ if not os.path.exists(path):+ return None+ try:+ with open(path) as f:+ data = json.load(f)+ logger.info(f"Persistence: loaded {service} state from {path}")+ return data+ except Exception as e:+ logger.error(f"Persistence: failed to load {service}: {e}")+ return None+++def save_all(services: dict) -> None:+ """Save all service states. services = {name: get_state_fn}"""+ for name, get_state in services.items():+ try:+ save_state(name, get_state())+ except Exception as e:+ logger.error(f"Persistence: error getting state for {name}: {e}")diff --git a/core/responses.py b/core/responses.pyindex 401db967..27c7f90b 100644--- a/core/responses.py+++ b/core/responses.py@@ -81,6 +81,20 @@ def now_iso() -> str:return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+def now_rfc7231() -> str:+ """Current time in RFC 7231 format for HTTP headers (e.g. Last-Modified)."""+ return datetime.now(timezone.utc).strftime("%a, %d %b %Y %H:%M:%S GMT")+++def iso_to_rfc7231(iso_str: str) -> str:+ """Convert an ISO 8601 timestamp to RFC 7231 format."""+ try:+ dt = datetime.fromisoformat(iso_str.replace("Z", "+00:00"))+ return dt.strftime("%a, %d %b %Y %H:%M:%S GMT")+ except (ValueError, AttributeError):+ return iso_str++def now_epoch() -> float:return datetime.now(timezone.utc).timestamp()diff --git a/core/router.py b/core/router.pyindex 2f88565c..a5474e55 100644--- a/core/router.py+++ b/core/router.py@@ -96,6 +96,10 @@ SERVICE_PATTERNS = {"target_prefixes": ["AmazonAthena"],"host_patterns": [r"athena\."],},+ "apigateway": {+ "host_patterns": [r"apigateway\.", r"execute-api\."],+ "path_patterns": [r"^/v2/apis"],+ },}@@ -123,7 +127,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) -># Map common credential scope namesscope_map = {"monitoring": "monitoring",- "execute-api": "lambda",+ "execute-api": "apigateway","ses": "ses","states": "states","kinesis": "kinesis",@@ -147,18 +151,42 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"CreateQueue": "sqs", "DeleteQueue": "sqs", "ListQueues": "sqs","GetQueueUrl": "sqs", "GetQueueAttributes": "sqs", "SetQueueAttributes": "sqs","PurgeQueue": "sqs", "ChangeMessageVisibility": "sqs",+ "ChangeMessageVisibilityBatch": "sqs","SendMessageBatch": "sqs", "DeleteMessageBatch": "sqs",+ "ListQueueTags": "sqs", "TagQueue": "sqs", "UntagQueue": "sqs",# SNS actions"Publish": "sns", "Subscribe": "sns", "Unsubscribe": "sns","CreateTopic": "sns", "DeleteTopic": "sns", "ListTopics": "sns","ListSubscriptions": "sns", "ConfirmSubscription": "sns","SetTopicAttributes": "sns", "GetTopicAttributes": "sns","ListSubscriptionsByTopic": "sns",+ "GetSubscriptionAttributes": "sns", "SetSubscriptionAttributes": "sns",+ "PublishBatch": "sns",+ "ListTagsForResource": "sns", "TagResource": "sns", "UntagResource": "sns",+ "CreatePlatformApplication": "sns", "CreatePlatformEndpoint": "sns",# IAM actions"CreateRole": "iam", "GetRole": "iam", "ListRoles": "iam","DeleteRole": "iam", "CreateUser": "iam", "GetUser": "iam",- "ListUsers": "iam", "CreatePolicy": "iam", "AttachRolePolicy": "iam",- "PutRolePolicy": "iam", "CreateAccessKey": "iam",+ "ListUsers": "iam", "DeleteUser": "iam",+ "CreatePolicy": "iam", "GetPolicy": "iam", "DeletePolicy": "iam",+ "GetPolicyVersion": "iam", "ListPolicyVersions": "iam",+ "CreatePolicyVersion": "iam", "DeletePolicyVersion": "iam",+ "ListPolicies": "iam",+ "AttachRolePolicy": "iam", "DetachRolePolicy": "iam",+ "ListAttachedRolePolicies": "iam",+ "PutRolePolicy": "iam", "GetRolePolicy": "iam",+ "DeleteRolePolicy": "iam", "ListRolePolicies": "iam",+ "CreateAccessKey": "iam", "ListAccessKeys": "iam", "DeleteAccessKey": "iam",+ "CreateInstanceProfile": "iam", "DeleteInstanceProfile": "iam",+ "GetInstanceProfile": "iam", "AddRoleToInstanceProfile": "iam",+ "RemoveRoleFromInstanceProfile": "iam",+ "ListInstanceProfiles": "iam", "ListInstanceProfilesForRole": "iam",+ "UpdateAssumeRolePolicy": "iam",+ "AttachUserPolicy": "iam", "DetachUserPolicy": "iam",+ "ListAttachedUserPolicies": "iam",+ "TagRole": "iam", "UntagRole": "iam", "ListRoleTags": "iam",+ "TagUser": "iam", "UntagUser": "iam", "ListUserTags": "iam",+ "SimulatePrincipalPolicy": "iam", "SimulateCustomPolicy": "iam",# STS actions"GetCallerIdentity": "sts", "AssumeRole": "sts","GetSessionToken": "sts",@@ -167,33 +195,63 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"ListMetrics": "monitoring", "PutMetricAlarm": "monitoring","DescribeAlarms": "monitoring", "DeleteAlarms": "monitoring","GetMetricStatistics": "monitoring", "SetAlarmState": "monitoring",+ "EnableAlarmActions": "monitoring", "DisableAlarmActions": "monitoring",+ "DescribeAlarmsForMetric": "monitoring", "DescribeAlarmHistory": "monitoring",+ "PutCompositeAlarm": "monitoring",# SES actions"SendEmail": "ses", "SendRawEmail": "ses","VerifyEmailIdentity": "ses", "VerifyEmailAddress": "ses",+ "VerifyDomainIdentity": "ses", "VerifyDomainDkim": "ses","ListIdentities": "ses", "DeleteIdentity": "ses","GetSendQuota": "ses", "GetSendStatistics": "ses","ListVerifiedEmailAddresses": "ses",+ "GetIdentityVerificationAttributes": "ses",+ "GetIdentityDkimAttributes": "ses",+ "SetIdentityNotificationTopic": "ses",+ "SetIdentityFeedbackForwardingEnabled": "ses",+ "CreateConfigurationSet": "ses", "DeleteConfigurationSet": "ses",+ "DescribeConfigurationSet": "ses", "ListConfigurationSets": "ses",+ "CreateTemplate": "ses", "GetTemplate": "ses",+ "DeleteTemplate": "ses", "ListTemplates": "ses", "UpdateTemplate": "ses",+ "SendTemplatedEmail": "ses", "SendBulkTemplatedEmail": "ses",# RDS actions"CreateDBInstance": "rds", "DeleteDBInstance": "rds", "DescribeDBInstances": "rds","StartDBInstance": "rds", "StopDBInstance": "rds", "RebootDBInstance": "rds","ModifyDBInstance": "rds", "CreateDBCluster": "rds", "DeleteDBCluster": "rds",+ "ModifyDBCluster": "rds","DescribeDBClusters": "rds", "CreateDBSubnetGroup": "rds", "DescribeDBSubnetGroups": "rds",+ "DeleteDBSubnetGroup": "rds","CreateDBParameterGroup": "rds", "DescribeDBParameterGroups": "rds",+ "DeleteDBParameterGroup": "rds", "DescribeDBParameters": "rds","DescribeDBEngineVersions": "rds",+ "DescribeOrderableDBInstanceOptions": "rds",+ "CreateDBSnapshot": "rds", "DeleteDBSnapshot": "rds", "DescribeDBSnapshots": "rds",+ "CreateDBInstanceReadReplica": "rds", "RestoreDBInstanceFromDBSnapshot": "rds",+ "AddTagsToResource": "rds", "RemoveTagsFromResource": "rds",+ "ListTagsForResource": "rds",# ElastiCache actions"CreateCacheCluster": "elasticache", "DeleteCacheCluster": "elasticache","DescribeCacheClusters": "elasticache", "ModifyCacheCluster": "elasticache",+ "RebootCacheCluster": "elasticache","CreateReplicationGroup": "elasticache", "DeleteReplicationGroup": "elasticache",- "DescribeReplicationGroups": "elasticache",+ "DescribeReplicationGroups": "elasticache", "ModifyReplicationGroup": "elasticache","CreateCacheSubnetGroup": "elasticache", "DescribeCacheSubnetGroups": "elasticache",+ "DeleteCacheSubnetGroup": "elasticache","CreateCacheParameterGroup": "elasticache", "DescribeCacheParameterGroups": "elasticache",+ "DeleteCacheParameterGroup": "elasticache",+ "DescribeCacheParameters": "elasticache", "ModifyCacheParameterGroup": "elasticache","DescribeCacheEngineVersions": "elasticache",+ "CreateSnapshot": "elasticache", "DeleteSnapshot": "elasticache",+ "DescribeSnapshots": "elasticache",+ "IncreaseReplicaCount": "elasticache", "DecreaseReplicaCount": "elasticache",}if action in action_service_map:return action_service_map[action]# 4. Check URL path patternspath_lower = path.lower()+ if path_lower.startswith("/v2/apis"):+ return "apigateway"if path_lower.startswith("/2015-03-31/functions"):return "lambda"if path_lower.startswith(("/clusters", "/taskdefinitions", "/tasks", "/services", "/stoptask")):diff --git a/docker-compose.yml b/docker-compose.ymlindex 5f4b58ae..7b142a6f 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -21,7 +21,7 @@ services:redis:condition: service_healthyhealthcheck:- test: ["CMD", "curl", "-sf", "http://localhost:4566/_localstack/health"]+ test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:4566/_localstack/health')"]interval: 10stimeout: 3sretries: 3diff --git a/index.html b/index.htmldeleted file mode 100644index effe6d3c..00000000--- a/index.html+++ /dev/null@@ -1,277 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>-<meta charset="UTF-8">-<meta name="viewport" content="width=device-width, initial-scale=1.0">-<title>MiniStack — Free Open-Source Local AWS Emulator</title>-<meta name="description" content="Free, open-source LocalStack alternative. 20 AWS services on a single port. Real Postgres, Redis, Docker containers. MIT licensed, no account required.">-<meta property="og:title" content="MiniStack — Free Local AWS Emulator">-<meta property="og:description" content="LocalStack is no longer free. MiniStack is. 20 AWS services, real database containers, 2-second startup. MIT licensed.">-<meta property="og:url" content="https://ministack.org">-<meta property="og:image" content="https://ministack.org/og-image.png">-<meta property="og:type" content="website">-<meta name="twitter:card" content="summary_large_image">-<meta name="twitter:title" content="MiniStack — Free Local AWS Emulator">-<meta name="twitter:description" content="Free, open-source LocalStack alternative. 20 AWS services, real infrastructure, MIT licensed.">-<meta name="twitter:image" content="https://ministack.org/og-image.png">-<link rel="canonical" href="https://ministack.org">-<link rel="icon" href="logo.png" type="image/png">-<link rel="preconnect" href="https://fonts.googleapis.com">-<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>-<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet">-<style>-*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}-:root{--bg:#080a0f;--bg2:#0d1017;--bg3:#141820;--surface:#1a1f2b;--border:#1e2433;--border-b:#2a3040;--tx:#e4e8f0;--tx2:#8891a5;--tx3:#4d5568;--blue:#2d9bd6;--blueL:#45b8f0;--blueG:rgba(45,155,214,.15);--green:#22c55e;--red:#ef4444;--yellow:#eab308;--cyan:#06b6d4;--mono:'JetBrains Mono',monospace;--sans:'Outfit',system-ui,sans-serif}-html{scroll-behavior:smooth}-body{background:var(--bg);color:var(--tx);font-family:var(--sans);line-height:1.6;overflow-x:hidden;-webkit-font-smoothing:antialiased}-body::before{content:'';position:fixed;inset:0;background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");opacity:.025;pointer-events:none;z-index:9999}-.gridbg{position:fixed;inset:0;background-image:linear-gradient(rgba(45,155,214,.04) 1px,transparent 1px),linear-gradient(90deg,rgba(45,155,214,.04) 1px,transparent 1px);background-size:80px 80px;pointer-events:none;z-index:0;mask-image:radial-gradient(ellipse 60% 40% at 50% 20%,#000 10%,transparent 70%)}-.glow{position:absolute;top:-100px;left:50%;transform:translateX(-50%);width:700px;height:500px;background:radial-gradient(ellipse,rgba(45,155,214,.12) 0%,rgba(45,155,214,.03) 40%,transparent 70%);pointer-events:none;z-index:0}-@keyframes fadeUp{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}-@keyframes pulse{0%,100%{box-shadow:0 0 6px var(--green)}50%{box-shadow:0 0 14px var(--green),0 0 28px rgba(34,197,94,.2)}}-.a{opacity:0;animation:fadeUp .6s cubic-bezier(.16,1,.3,1) forwards}-.d1{animation-delay:.05s}.d2{animation-delay:.1s}.d3{animation-delay:.18s}.d4{animation-delay:.26s}.d5{animation-delay:.34s}.d6{animation-delay:.42s}.d7{animation-delay:.5s}.d8{animation-delay:.6s}--nav{position:fixed;top:0;left:0;right:0;z-index:100;padding:0 2rem;height:60px;display:flex;align-items:center;justify-content:space-between;background:rgba(8,10,15,.85);backdrop-filter:blur(16px) saturate(1.4);border-bottom:1px solid var(--border)}-.nlogo{display:flex;align-items:center;gap:10px;text-decoration:none}-.nlogo img{height:32px}.nlogo span{font-family:var(--mono);font-weight:700;font-size:1rem;color:var(--tx)}-.nr{display:flex;align-items:center;gap:1.5rem}-.nr a{color:var(--tx2);text-decoration:none;font-size:.88rem;font-weight:500;transition:color .2s}-.nr a:hover{color:var(--tx)}-.ghb{display:inline-flex;align-items:center;gap:7px;padding:7px 14px;background:var(--surface);border:1px solid var(--border-b);border-radius:8px;color:var(--tx);font-size:.82rem;font-weight:600;transition:all .2s}-.ghb:hover{border-color:var(--blue);background:var(--bg3)}-.ghb svg{width:16px;height:16px;fill:currentColor}--.hero{position:relative;z-index:1;padding:150px 2rem 80px;max-width:1000px;margin:0 auto;text-align:center}-.badge{display:inline-flex;align-items:center;gap:8px;padding:5px 14px;border-radius:100px;border:1px solid var(--border-b);background:var(--bg2);font-size:.8rem;font-family:var(--mono);color:var(--tx2);margin-bottom:1.8rem}-.badge .dot{width:7px;height:7px;border-radius:50%;background:var(--green);animation:pulse 2s infinite}-h1{font-size:clamp(2.5rem,6.5vw,4.5rem);font-weight:800;line-height:1.08;letter-spacing:-.035em;margin-bottom:1.2rem}-.bl{color:var(--blueL)}-.hsub{font-size:1.15rem;color:var(--tx2);max-width:580px;margin:0 auto 2.2rem;line-height:1.7}-.hsub strong{color:var(--tx);font-weight:600}-.hacts{display:flex;align-items:center;justify-content:center;gap:1rem;flex-wrap:wrap;margin-bottom:2rem}-.btn{display:inline-flex;align-items:center;gap:8px;padding:12px 24px;border-radius:9px;font-weight:700;font-size:.92rem;text-decoration:none;transition:all .25s;border:none;cursor:pointer}-.btn-b{background:var(--blue);color:#fff}.btn-b:hover{background:var(--blueL);transform:translateY(-2px);box-shadow:0 8px 30px rgba(45,155,214,.3)}-.btn-g{background:transparent;color:var(--tx);border:1px solid var(--border-b)}.btn-g:hover{background:var(--surface);border-color:var(--tx3);transform:translateY(-2px)}-.btn svg{width:17px;height:17px;fill:currentColor}-.cmd{display:inline-flex;align-items:center;gap:12px;padding:12px 20px;background:var(--bg2);border:1px solid var(--border);border-radius:9px;font-family:var(--mono);font-size:.88rem;cursor:pointer;transition:all .2s}-.cmd:hover{border-color:var(--blue)}-.cmd .p{color:var(--blue)}.cmd .c{color:var(--tx)}-.cmd .tg{font-family:var(--sans);font-size:.72rem;color:var(--tx3);padding:2px 8px;background:var(--surface);border-radius:4px}-.cmd.copied .tg{color:var(--green)}--.stats{display:flex;justify-content:center;gap:3rem;flex-wrap:wrap;padding:2rem 2rem 3rem;max-width:950px;margin:0 auto}-.sv{font-family:var(--mono);font-size:1.8rem;font-weight:700;color:var(--blueL)}-.sl{font-size:.78rem;color:var(--tx3);text-transform:uppercase;letter-spacing:.1em;margin-top:2px}--.callout{position:relative;z-index:1;max-width:800px;margin:0 auto 4rem;padding:0 2rem}-.cbox{display:flex;align-items:flex-start;gap:16px;padding:20px 24px;background:rgba(239,68,68,.06);border:1px solid rgba(239,68,68,.15);border-radius:10px}-.cbox-i{font-size:1.4rem;flex-shrink:0;margin-top:2px}-.cbox-t{font-size:.92rem;color:var(--tx2);line-height:1.6}.cbox-t strong{color:var(--tx)}--.tw{position:relative;z-index:1;max-width:800px;margin:0 auto 5rem;padding:0 2rem}-.term{background:var(--bg2);border:1px solid var(--border);border-radius:12px;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.4)}-.tb{display:flex;align-items:center;gap:7px;padding:12px 16px;background:var(--bg3);border-bottom:1px solid var(--border)}-.td{width:11px;height:11px;border-radius:50%}.td.r{background:#ff5f57}.td.y{background:#febc2e}.td.g{background:#28c840}-.tt{flex:1;text-align:center;font-family:var(--mono);font-size:.75rem;color:var(--tx3)}-.tc{padding:20px;font-family:var(--mono);font-size:.82rem;line-height:1.9;overflow-x:auto;white-space:pre}-.cm{color:var(--tx3)}.pr{color:var(--blue)}.fl{color:var(--cyan)}.st{color:var(--yellow)}.out{color:var(--tx2)}.ok{color:var(--green)}--.sec{position:relative;z-index:1;max-width:1060px;margin:0 auto;padding:4.5rem 2rem}-.stag{font-family:var(--mono);font-size:.75rem;text-transform:uppercase;letter-spacing:.14em;color:var(--blue);margin-bottom:.8rem}-.sec h2{font-size:clamp(1.7rem,3.5vw,2.5rem);font-weight:800;letter-spacing:-.02em;margin-bottom:.8rem}-.sdesc{color:var(--tx2);font-size:1rem;max-width:560px;margin-bottom:2.5rem}-.div{border:none;border-top:1px solid var(--border);margin:0 auto;max-width:1020px}--.sg{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:1px;background:var(--border);border:1px solid var(--border);border-radius:12px;overflow:hidden}-.sc{background:var(--bg2);padding:22px 20px;transition:background .2s}.sc:hover{background:var(--bg3)}-.si{font-size:1.3rem;margin-bottom:8px}.sn{font-weight:700;font-size:.92rem;margin-bottom:4px}-.sd{font-size:.76rem;color:var(--tx3);line-height:1.5}-.sp{display:inline-block;margin-top:8px;padding:2px 8px;background:var(--surface);border-radius:4px;font-family:var(--mono);font-size:.68rem;color:var(--tx2)}-.sp.real{background:rgba(45,155,214,.1);color:var(--blue);border:1px solid rgba(45,155,214,.2)}--.ct{width:100%;border-collapse:separate;border-spacing:0;border:1px solid var(--border);border-radius:12px;overflow:hidden;font-size:.88rem}-.ct th,.ct td{padding:14px 18px;text-align:left;border-bottom:1px solid var(--border)}-.ct th{background:var(--bg3);font-weight:600;font-size:.78rem;text-transform:uppercase;letter-spacing:.06em;color:var(--tx2)}-.ct th.hl{color:var(--blueL)}-.ct td{background:var(--bg2)}.ct tr:last-child td{border-bottom:none}-.w{color:var(--blueL);font-family:var(--mono);font-weight:700}.dm{color:var(--tx3)}--.fg{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:1.2rem}-.fc{padding:28px;background:var(--bg2);border:1px solid var(--border);border-radius:12px;transition:all .25s}-.fc:hover{border-color:var(--border-b);transform:translateY(-2px)}-.fi{width:40px;height:40px;background:var(--blueG);border:1px solid rgba(45,155,214,.15);border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:1.1rem;margin-bottom:14px}-.ft{font-weight:700;margin-bottom:6px;font-size:.95rem}-.fd{font-size:.84rem;color:var(--tx2);line-height:1.6}--.fcta{position:relative;z-index:1;text-align:center;padding:5rem 2rem;max-width:650px;margin:0 auto}-.fcta h2{font-size:clamp(1.6rem,3.5vw,2.3rem);font-weight:800;letter-spacing:-.02em;margin-bottom:.8rem}-.fcta p{color:var(--tx2);margin-bottom:2rem;font-size:1rem}-footer{position:relative;z-index:1;border-top:1px solid var(--border);padding:1.8rem 2rem;text-align:center;font-size:.8rem;color:var(--tx3)}-footer a{color:var(--tx2);text-decoration:none}footer a:hover{color:var(--blue)}--@media(max-width:768px){.nr a:not(.ghb){display:none}.hero{padding:120px 1.5rem 50px}.stats{gap:1.5rem}.sv{font-size:1.4rem}.hacts{flex-direction:column}.sg{grid-template-columns:repeat(auto-fill,minmax(160px,1fr))}.ct{font-size:.78rem}.ct th,.ct td{padding:10px 12px}.tc{font-size:.72rem;padding:14px}}-@media(max-width:480px){.cmd{font-size:.76rem;padding:10px 14px}.sg{grid-template-columns:1fr 1fr}}-</style>-</head>-<body>-<div class="gridbg"></div>--<nav>- <a href="/" class="nlogo"><img src="logo.png" alt="MiniStack"><span>MiniStack</span></a>- <div class="nr">- <a href="#services">Services</a>- <a href="#comparison">Compare</a>- <a href="#features">Features</a>- <a href="https://github.com/Nahuel990/ministack" target="_blank" class="ghb">- <svg viewBox="0 0 16 16"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>- Star- </a>- </div>-</nav>--<section class="hero">- <div class="glow"></div>- <div class="badge a d1"><span class="dot"></span>v1.0.11 · MIT licensed · free forever</div>- <h1 class="a d2">The <span class="bl">free</span> LocalStack<br>replacement</h1>- <p class="hsub a d3">LocalStack is no longer free. <strong>MiniStack is.</strong><br>20 AWS services on a single port — with <strong>real Postgres, Redis, and Docker containers</strong>. No account, no license key, no telemetry.</p>- <div class="hacts a d4">- <a href="https://github.com/Nahuel990/ministack" target="_blank" class="btn btn-b">- <svg viewBox="0 0 16 16"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>- View on GitHub</a>- <a href="https://hub.docker.com/r/nahuelnucera/ministack" target="_blank" class="btn btn-g">🐳 Docker Hub</a>- </div>- <div class="cmd a d5" onclick="cp(this)"><span class="p">$</span><span class="c">docker run -p 4566:4566 nahuelnucera/ministack</span><span class="tg">copy</span></div>-</section>--<div class="stats a d6">- <div><div class="sv">20</div><div class="sl">AWS Services</div></div>- <div><div class="sv">~2s</div><div class="sl">Startup</div></div>- <div><div class="sv">~30MB</div><div class="sl">RAM at idle</div></div>- <div><div class="sv">150MB</div><div class="sl">Docker Image</div></div>- <div><div class="sv">56</div><div class="sl">Tests passing</div></div>-</div>--<div class="callout a d7">- <div class="cbox">- <span class="cbox-i">⚠️</span>- <div class="cbox-t"><strong>LocalStack moved core services behind a paid plan.</strong> If you relied on LocalStack Community for local dev and CI/CD, MiniStack is your free, MIT-licensed drop-in replacement. No sign-up, no API key, no telemetry.</div>- </div>-</div>--<div class="tw a d8">- <div class="term">- <div class="tb"><span class="td r"></span><span class="td y"></span><span class="td g"></span><span class="tt">ministack — bash</span></div>- <div class="tc"><span class="cm"># Start MiniStack</span>-<span class="pr">$</span> docker run <span class="fl">-p</span> <span class="st">4566:4566</span> nahuelnucera/ministack--<span class="cm"># Works with any AWS tool — no config changes</span>-<span class="pr">$</span> aws <span class="fl">--endpoint-url=</span><span class="st">http://localhost:4566</span> s3 mb s3://my-bucket-<span class="out">make_bucket: my-bucket</span>--<span class="cm"># Real database — RDS spins up actual Postgres</span>-<span class="pr">$</span> aws <span class="fl">--endpoint-url=</span><span class="st">http://localhost:4566</span> rds create-db-instance \- <span class="fl">--db-instance-identifier</span> mydb <span class="fl">--engine</span> postgres \- <span class="fl">--master-username</span> admin <span class="fl">--master-user-password</span> secret-<span class="ok">✓ Real Postgres container running on localhost:15432</span>--<span class="cm"># Real Redis via ElastiCache</span>-<span class="pr">$</span> aws <span class="fl">--endpoint-url=</span><span class="st">http://localhost:4566</span> elasticache \- create-cache-cluster <span class="fl">--cache-cluster-id</span> my-redis <span class="fl">--engine</span> redis-<span class="ok">✓ Real Redis container running on localhost:16379</span></div>- </div>-</div>--<hr class="div">--<section class="sec" id="services">- <div class="stag">20 Services</div>- <h2>Everything you need, locally</h2>- <p class="sdesc">Core AWS services plus real infrastructure — RDS runs actual databases, ElastiCache runs real Redis, ECS starts real Docker containers, Athena executes real SQL via DuckDB (when installed).</p>- <div class="sg">- <div class="sc"><div class="si">🪣</div><div class="sn">S3</div><div class="sd">Buckets, objects, copy, list, batch</div><span class="sp">REST/XML</span></div>- <div class="sc"><div class="si">📨</div><div class="sn">SQS</div><div class="sd">Queues, send/receive, batch, visibility</div><span class="sp">JSON+Query</span></div>- <div class="sc"><div class="si">📢</div><div class="sn">SNS</div><div class="sd">Topics, subscriptions, publish</div><span class="sp">Query/XML</span></div>- <div class="sc"><div class="si">🗃️</div><div class="sn">DynamoDB</div><div class="sd">Tables, CRUD, query, scan, batch</div><span class="sp">JSON</span></div>- <div class="sc"><div class="si">⚡</div><div class="sn">Lambda</div><div class="sd">Real Python execution from zip</div><span class="sp">REST/JSON</span></div>- <div class="sc"><div class="si">🔐</div><div class="sn">IAM</div><div class="sd">Users, roles, policies, keys</div><span class="sp">Query/XML</span></div>- <div class="sc"><div class="si">🎫</div><div class="sn">STS</div><div class="sd">CallerIdentity, AssumeRole</div><span class="sp">Query/XML</span></div>- <div class="sc"><div class="si">🔑</div><div class="sn">Secrets Manager</div><div class="sd">CRUD with versioning</div><span class="sp">JSON</span></div>- <div class="sc"><div class="si">📊</div><div class="sn">CW Logs</div><div class="sd">Groups, streams, events, filter</div><span class="sp">JSON</span></div>- <div class="sc"><div class="si">📐</div><div class="sn">SSM Params</div><div class="sd">String, SecureString, paths</div><span class="sp">JSON</span></div>- <div class="sc"><div class="si">🚌</div><div class="sn">EventBridge</div><div class="sd">Buses, rules, targets, events</div><span class="sp">JSON</span></div>- <div class="sc"><div class="si">🌊</div><div class="sn">Kinesis</div><div class="sd">Streams, shards, put/get records</div><span class="sp">JSON</span></div>- <div class="sc"><div class="si">📈</div><div class="sn">CW Metrics</div><div class="sd">Metrics, alarms, statistics</div><span class="sp">Query/XML</span></div>- <div class="sc"><div class="si">✉️</div><div class="sn">SES</div><div class="sd">Send email, identities, quotas</div><span class="sp">Query/XML</span></div>- <div class="sc"><div class="si">🔄</div><div class="sn">Step Functions</div><div class="sd">State machines, executions</div><span class="sp">JSON</span></div>- <div class="sc"><div class="si">🐘</div><div class="sn">RDS</div><div class="sd">Real Postgres/MySQL containers</div><span class="sp real">Real Docker</span></div>- <div class="sc"><div class="si">🔴</div><div class="sn">ElastiCache</div><div class="sd">Real Redis/Memcached containers</div><span class="sp real">Real Docker</span></div>- <div class="sc"><div class="si">🐳</div><div class="sn">ECS</div><div class="sd">RunTask starts real containers</div><span class="sp real">Real Docker</span></div>- <div class="sc"><div class="si">🧪</div><div class="sn">Glue</div><div class="sd">Catalog, crawlers, jobs</div><span class="sp real">Real Exec</span></div>- <div class="sc"><div class="si">🔍</div><div class="sn">Athena</div><div class="sd">Real SQL via DuckDB (optional)</div><span class="sp real">DuckDB</span></div>- </div>-</section>--<hr class="div">--<section class="sec" id="comparison">- <div class="stag">Comparison</div>- <h2>LocalStack vs MiniStack</h2>- <p class="sdesc">Same developer experience. Fraction of the cost and footprint.</p>- <table class="ct">- <thead><tr><th>Feature</th><th>LocalStack Free</th><th>LocalStack Pro</th><th class="hl">MiniStack ⚡</th></tr></thead>- <tbody>- <tr><td>Core services (S3, SQS, DDB…)</td><td class="dm">Now paid</td><td>✅</td><td class="w">✅ Free</td></tr>- <tr><td>Lambda, IAM, SSM, EventBridge</td><td class="dm">Paid</td><td>✅</td><td class="w">✅ Free</td></tr>- <tr><td>RDS (real DB containers)</td><td class="dm">❌</td><td>✅</td><td class="w">✅ Real Postgres/MySQL</td></tr>- <tr><td>ElastiCache (real Redis)</td><td class="dm">❌</td><td>✅</td><td class="w">✅ Real Redis</td></tr>- <tr><td>ECS (real Docker)</td><td class="dm">❌</td><td>✅</td><td class="w">✅ Real Docker</td></tr>- <tr><td>Athena (real SQL)</td><td class="dm">❌</td><td>✅</td><td class="w">✅ DuckDB (optional)</td></tr>- <tr><td>Glue Catalog + Jobs</td><td class="dm">❌</td><td>✅</td><td class="w">✅</td></tr>- <tr><td>Startup time</td><td class="dm">~15-30s</td><td class="dm">~15-30s</td><td class="w">~2s</td></tr>- <tr><td>Memory at idle</td><td class="dm">~500MB</td><td class="dm">~500MB</td><td class="w">~30MB</td></tr>- <tr><td>Docker image</td><td class="dm">~1 GB</td><td class="dm">~1 GB</td><td class="w">150 MB</td></tr>- <tr><td>License</td><td class="dm">BSL (restricted)</td><td class="dm">Proprietary</td><td class="w">MIT</td></tr>- <tr><td>Price</td><td class="dm">Now paid</td><td class="dm">$35+/mo</td><td class="w">$0 forever</td></tr>- </tbody>- </table>-</section>--<hr class="div">--<section class="sec" id="features">- <div class="stag">Built different</div>- <h2>Real infrastructure, not mocks</h2>- <p class="sdesc">Where it matters most — RDS, ElastiCache, and ECS run real Docker containers. No fake endpoints, no stubbed responses.</p> <div class="fg">- <div class="fc"><div class="fi">🐘</div><div class="ft">Real databases via RDS</div><div class="fd">CreateDBInstance spins up an actual Postgres or MySQL Docker container. Connect with psycopg2 — it's a real database.</div></div>- <div class="fc"><div class="fi">🔴</div><div class="ft">Real Redis via ElastiCache</div><div class="fd">CreateCacheCluster starts an actual Redis container. Use redis-py, run SUBSCRIBE, use it as your session store.</div></div>- <div class="fc"><div class="fi">🐳</div><div class="ft">Real containers via ECS</div><div class="fd">RunTask pulls and starts real Docker containers via the Docker socket. Test your ECS task definitions locally.</div></div>- <div class="fc"><div class="fi">🔍</div><div class="ft">Real SQL via Athena</div><div class="fd">Queries execute via DuckDB when installed. Query S3 data with actual SQL, get actual result sets back. Falls back to mock results without it.</div></div>- <div class="fc"><div class="fi">🔌</div><div class="ft">Full SDK compatibility</div><div class="fd">Works with boto3, AWS CLI, Terraform, CDK, Pulumi — any tool that speaks the AWS API.</div></div>- <div class="fc"><div class="fi">🔓</div><div class="ft">MIT licensed forever</div><div class="fd">No BSL, no feature gates, no "community" vs "pro". Every service is free. Fork it, embed it. MIT is MIT.</div></div>- </div>-</section>--<hr class="div">--<section class="fcta">- <h2>Stop paying for local development</h2>- <p>One command. 20 services. Real infrastructure. Free.</p>- <div class="hacts" style="margin-bottom:1.5rem">- <a href="https://github.com/Nahuel990/ministack" target="_blank" class="btn btn-b">- <svg width="17" height="17" viewBox="0 0 16 16" fill="currentColor"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>- GitHub</a>- <a href="https://hub.docker.com/r/nahuelnucera/ministack" target="_blank" class="btn btn-g">🐳 Docker Hub</a>- </div>- <div class="cmd" onclick="cp(this)"><span class="p">$</span><span class="c">docker run -p 4566:4566 nahuelnucera/ministack</span><span class="tg">copy</span></div>-</section>--<footer>Built by <a href="https://github.com/Nahuel990" target="_blank">Nahuel</a> · <a href="https://github.com/Nahuel990/ministack" target="_blank">GitHub</a> · MIT License · 2025</footer>--<script>-function cp(e){navigator.clipboard.writeText(e.querySelector('.c').textContent).then(()=>{const t=e.querySelector('.tg');t.textContent='copied!';e.classList.add('copied');setTimeout(()=>{t.textContent='copy';e.classList.remove('copied')},2e3)})}-const o=new IntersectionObserver(e=>{e.forEach(x=>{if(x.isIntersecting){x.target.classList.add('a');o.unobserve(x.target)}})},{threshold:.08,rootMargin:'0px 0px -30px 0px'});-document.querySelectorAll('.sec .stag,.sec h2,.sdesc,.sc,.fc,.ct,.cbox').forEach(e=>{if(!e.classList.contains('a')){e.style.opacity='0';o.observe(e)}});-</script>-</body>-</html>diff --git a/services/apigateway.py b/services/apigateway.pynew file mode 100644index 00000000..4067ef2e--- /dev/null+++ b/services/apigateway.py@@ -0,0 +1,714 @@+"""+API Gateway HTTP API v2 Emulator.++Control plane endpoints implemented:+ POST /v2/apis — CreateApi+ GET /v2/apis — GetApis+ GET /v2/apis/{apiId} — GetApi+ PATCH /v2/apis/{apiId} — UpdateApi+ DELETE /v2/apis/{apiId} — DeleteApi+ POST /v2/apis/{apiId}/routes — CreateRoute+ GET /v2/apis/{apiId}/routes — GetRoutes+ GET /v2/apis/{apiId}/routes/{routeId} — GetRoute+ PATCH /v2/apis/{apiId}/routes/{routeId} — UpdateRoute+ DELETE /v2/apis/{apiId}/routes/{routeId} — DeleteRoute+ POST /v2/apis/{apiId}/integrations — CreateIntegration+ GET /v2/apis/{apiId}/integrations — GetIntegrations+ GET /v2/apis/{apiId}/integrations/{integId} — GetIntegration+ PATCH /v2/apis/{apiId}/integrations/{integId} — UpdateIntegration+ DELETE /v2/apis/{apiId}/integrations/{integId} — DeleteIntegration+ POST /v2/apis/{apiId}/stages — CreateStage+ GET /v2/apis/{apiId}/stages — GetStages+ GET /v2/apis/{apiId}/stages/{stageName} — GetStage+ PATCH /v2/apis/{apiId}/stages/{stageName} — UpdateStage+ DELETE /v2/apis/{apiId}/stages/{stageName} — DeleteStage+ POST /v2/apis/{apiId}/deployments — CreateDeployment+ GET /v2/apis/{apiId}/deployments — GetDeployments+ GET /v2/apis/{apiId}/deployments/{deployId} — GetDeployment+ DELETE /v2/apis/{apiId}/deployments/{deployId} — DeleteDeployment+ GET /v2/tags/{resourceArn} — GetTags+ POST /v2/tags/{resourceArn} — TagResource+ DELETE /v2/tags/{resourceArn} — UntagResource+ POST /v2/apis/{apiId}/authorizers — CreateAuthorizer+ GET /v2/apis/{apiId}/authorizers — GetAuthorizers+ GET /v2/apis/{apiId}/authorizers/{authId} — GetAuthorizer+ PATCH /v2/apis/{apiId}/authorizers/{authId} — UpdateAuthorizer+ DELETE /v2/apis/{apiId}/authorizers/{authId} — DeleteAuthorizer++Data plane:+ Requests to /{apiId}.execute-api.localhost/{stage}/{path} are forwarded to+ Lambda (AWS_PROXY) or HTTP backends (HTTP_PROXY) via handle_execute().+"""++import json+import time+import logging+import re++from core.responses import new_uuid, error_response_json++logger = logging.getLogger("apigateway")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++# ---- Module-level state ----+_apis: dict = {} # api_id -> api object+_routes: dict = {} # api_id -> {route_id -> route object}+_integrations: dict = {} # api_id -> {integration_id -> integration object}+_stages: dict = {} # api_id -> {stage_name -> stage object}+_deployments: dict = {} # api_id -> {deployment_id -> deployment object}+_authorizers: dict = {} # api_id -> {authorizer_id -> authorizer object}+_api_tags: dict = {} # resource_arn -> {key -> value}+++# ---- Response helpers ----++def _apigw_response(data: dict, status: int = 200) -> tuple:+ """API Gateway v2 uses application/json (not application/x-amz-json-1.0)."""+ return status, {"Content-Type": "application/json"}, json.dumps(data).encode()+++def _apigw_error(code: str, message: str, status: int) -> tuple:+ return status, {"Content-Type": "application/json"}, json.dumps({"message": message, "__type": code}).encode()+++def _api_arn(api_id: str) -> str:+ return f"arn:aws:apigateway:{REGION}::/apis/{api_id}"+++# ---- Persistence hooks ----++def get_state() -> dict:+ """Return full module state for persistence."""+ return {+ "apis": _apis,+ "routes": _routes,+ "integrations": _integrations,+ "stages": _stages,+ "deployments": _deployments,+ "authorizers": _authorizers,+ "api_tags": _api_tags,+ }+++def load_persisted_state(data: dict) -> None:+ """Restore module state from a previously persisted snapshot."""+ _apis.update(data.get("apis", {}))+ _routes.update(data.get("routes", {}))+ _integrations.update(data.get("integrations", {}))+ _stages.update(data.get("stages", {}))+ _deployments.update(data.get("deployments", {}))+ _authorizers.update(data.get("authorizers", {}))+ _api_tags.update(data.get("api_tags", {}))+++# ---- Control plane router ----++async def handle_request(method, path, headers, body, query_params):+ """Route API Gateway v2 control plane requests."""+ try:+ data = json.loads(body) if body else {}+ except json.JSONDecodeError:+ data = {}++ parts = [p for p in path.strip("/").split("/") if p]+ # Minimum expected: ["v2", <resource>]++ if not parts or parts[0] != "v2":+ return _apigw_error("NotFoundException", f"Unknown path: {path}", 404)++ resource = parts[1] if len(parts) > 1 else ""++ # /v2/tags/{resourceArn} — tags endpoint+ if resource == "tags":+ # resourceArn may contain slashes; rejoin everything after "tags/"+ resource_arn = "/".join(parts[2:]) if len(parts) > 2 else ""+ if method == "GET":+ return _get_tags(resource_arn)+ if method == "POST":+ return _tag_resource(resource_arn, data)+ if method == "DELETE":+ tag_keys = query_params.get("tagKeys", [])+ if isinstance(tag_keys, str):+ tag_keys = [tag_keys]+ return _untag_resource(resource_arn, tag_keys)++ if resource == "apis":+ api_id = parts[2] if len(parts) > 2 else None+ sub = parts[3] if len(parts) > 3 else None+ sub_id = parts[4] if len(parts) > 4 else None++ # /v2/apis+ if not api_id:+ if method == "POST":+ return _create_api(data)+ if method == "GET":+ return _get_apis()++ # /v2/apis/{apiId}+ if api_id and not sub:+ if method == "GET":+ return _get_api(api_id)+ if method == "DELETE":+ return _delete_api(api_id)+ if method == "PATCH":+ return _update_api(api_id, data)++ # /v2/apis/{apiId}/routes[/{routeId}]+ if api_id and sub == "routes":+ if not sub_id:+ if method == "POST":+ return _create_route(api_id, data)+ if method == "GET":+ return _get_routes(api_id)+ else:+ if method == "GET":+ return _get_route(api_id, sub_id)+ if method == "PATCH":+ return _update_route(api_id, sub_id, data)+ if method == "DELETE":+ return _delete_route(api_id, sub_id)++ # /v2/apis/{apiId}/integrations[/{integrationId}]+ if api_id and sub == "integrations":+ if not sub_id:+ if method == "POST":+ return _create_integration(api_id, data)+ if method == "GET":+ return _get_integrations(api_id)+ else:+ if method == "GET":+ return _get_integration(api_id, sub_id)+ if method == "PATCH":+ return _update_integration(api_id, sub_id, data)+ if method == "DELETE":+ return _delete_integration(api_id, sub_id)++ # /v2/apis/{apiId}/stages[/{stageName}]+ if api_id and sub == "stages":+ if not sub_id:+ if method == "POST":+ return _create_stage(api_id, data)+ if method == "GET":+ return _get_stages(api_id)+ else:+ if method == "GET":+ return _get_stage(api_id, sub_id)+ if method == "PATCH":+ return _update_stage(api_id, sub_id, data)+ if method == "DELETE":+ return _delete_stage(api_id, sub_id)++ # /v2/apis/{apiId}/deployments[/{deploymentId}]+ if api_id and sub == "deployments":+ if not sub_id:+ if method == "POST":+ return _create_deployment(api_id, data)+ if method == "GET":+ return _get_deployments(api_id)+ else:+ if method == "GET":+ return _get_deployment(api_id, sub_id)+ if method == "DELETE":+ return _delete_deployment(api_id, sub_id)++ # /v2/apis/{apiId}/authorizers[/{authorizerId}]+ if api_id and sub == "authorizers":+ if not sub_id:+ if method == "POST":+ return _create_authorizer(api_id, data)+ if method == "GET":+ return _get_authorizers(api_id)+ else:+ if method == "GET":+ return _get_authorizer(api_id, sub_id)+ if method == "PATCH":+ return _update_authorizer(api_id, sub_id, data)+ if method == "DELETE":+ return _delete_authorizer(api_id, sub_id)++ return _apigw_error("NotFoundException", f"Unknown API Gateway path: {path}", 404)+++# ---- Data plane ----++async def handle_execute(api_id, stage, path, method, headers, body, query_params):+ """Execute an API request through a deployed API (data plane)."""+ api = _apis.get(api_id)+ if not api:+ return 404, {"Content-Type": "application/json"}, json.dumps({"message": "Not Found"}).encode()++ api_stages = _stages.get(api_id, {})+ if stage not in api_stages and stage != "$default":+ return 404, {"Content-Type": "application/json"}, json.dumps({"message": f"Stage '{stage}' not found"}).encode()++ route = _match_route(api_id, method, path)+ if not route:+ return 404, {"Content-Type": "application/json"}, json.dumps({"message": "No route found"}).encode()++ integration_id = route.get("target", "").replace("integrations/", "")+ integration = _integrations.get(api_id, {}).get(integration_id)+ if not integration:+ return 500, {"Content-Type": "application/json"}, json.dumps({"message": "No integration configured"}).encode()++ integration_type = integration.get("integrationType", "")++ if integration_type == "AWS_PROXY":+ return await _invoke_lambda_proxy(integration, api_id, stage, path, method, headers, body, query_params, route.get("routeKey", "$default"))+ elif integration_type == "HTTP_PROXY":+ return await _invoke_http_proxy(integration, path, method, headers, body, query_params)+ else:+ return 500, {"Content-Type": "application/json"}, json.dumps({"message": f"Unsupported integration type: {integration_type}"}).encode()+++def _match_route(api_id, method, path):+ """Find the best matching route for method+path. $default route is the fallback."""+ routes = _routes.get(api_id, {})+ # First pass: look for a specific method+path match (skip $default)+ for route in routes.values():+ key = route.get("routeKey", "")+ if key == "$default":+ continue+ parts = key.split(" ", 1)+ if len(parts) == 2:+ r_method, r_path = parts+ if (r_method == "ANY" or r_method == method) and _path_matches(r_path, path):+ return route+ # Second pass: $default catch-all+ for route in routes.values():+ if route.get("routeKey") == "$default":+ return route+ return None+++def _path_matches(route_path: str, request_path: str) -> bool:+ """+ Match a route path against a request path.++ Supports:+ {param} — single path segment (no slashes)+ {proxy+} — greedy match (one or more path segments, may include slashes)+ """+ # Build regex by splitting on placeholders+ parts = re.split(r"(\{[^}]+\})", route_path)+ pattern_parts = []+ for part in parts:+ if part.startswith("{") and part.endswith("}"):+ inner = part[1:-1]+ if inner.endswith("+"):+ # greedy — matches one or more characters including slashes+ pattern_parts.append(".+")+ else:+ # single segment — no slashes+ pattern_parts.append("[^/]+")+ else:+ pattern_parts.append(re.escape(part))+ return bool(re.fullmatch("".join(pattern_parts), request_path))+++async def _invoke_lambda_proxy(integration, api_id, stage, path, method, headers, body, query_params, route_key="$default"):+ """Invoke a Lambda function using the API Gateway v2 proxy event format."""+ from services import lambda_svc+ from core.lambda_runtime import get_or_create_worker++ uri = integration.get("integrationUri", "")+ # integrationUri is a Lambda ARN; the function name is the last segment+ func_name = uri.split(":")[-1] if ":" in uri else uri+ # Strip /invocations suffix emitted by some SDKs+ func_name = func_name.replace("/invocations", "")++ if func_name not in lambda_svc._functions:+ return 502, {"Content-Type": "application/json"}, json.dumps({"message": f"Lambda function '{func_name}' not found"}).encode()++ # Build API Gateway v2 proxy event (payload format 2.0)+ qs = {k: v[0] if len(v) == 1 else v for k, v in query_params.items()}+ event = {+ "version": "2.0",+ "routeKey": route_key,+ "rawPath": path,+ "rawQueryString": "&".join(f"{k}={v}" for k, v in query_params.items()),+ "headers": dict(headers),+ "queryStringParameters": qs,+ "requestContext": {+ "accountId": ACCOUNT_ID,+ "apiId": api_id,+ "domainName": f"{api_id}.execute-api.localhost",+ "http": {+ "method": method,+ "path": path,+ "protocol": "HTTP/1.1",+ "sourceIp": "127.0.0.1",+ "userAgent": headers.get("user-agent", ""),+ },+ "requestId": new_uuid(),+ "routeKey": route_key,+ "stage": stage,+ "time": time.strftime("%d/%b/%Y:%H:%M:%S +0000"),+ "timeEpoch": int(time.time() * 1000),+ },+ "body": body.decode("utf-8", errors="replace") if body else None,+ "isBase64Encoded": False,+ }++ func_data = lambda_svc._functions[func_name]+ code_zip = func_data.get("code_zip")++ if code_zip and func_data["config"]["Runtime"].startswith("python"):+ worker = get_or_create_worker(func_name, func_data["config"], code_zip)+ result = worker.invoke(event, new_uuid())+ if result.get("status") == "error":+ return 502, {"Content-Type": "application/json"}, json.dumps({"message": result.get("error")}).encode()+ lambda_response = result.get("result", {})+ else:+ lambda_response = {"statusCode": 200, "body": "Mock response"}++ status = lambda_response.get("statusCode", 200)+ resp_headers = {"Content-Type": "application/json"}+ resp_headers.update(lambda_response.get("headers", {}))+ resp_body = lambda_response.get("body", "")+ if isinstance(resp_body, str):+ resp_body = resp_body.encode()+ elif isinstance(resp_body, dict):+ resp_body = json.dumps(resp_body).encode()++ return status, resp_headers, resp_body+++async def _invoke_http_proxy(integration, path, method, headers, body, query_params):+ """Forward a request to an HTTP backend."""+ import urllib.request+ import urllib.error++ uri = integration.get("integrationUri", "")+ url = uri.rstrip("/") + path++ req = urllib.request.Request(url, data=body or None, method=method)+ for k, v in headers.items():+ if k.lower() not in ("host", "content-length"):+ req.add_header(k, v)+ try:+ with urllib.request.urlopen(req, timeout=30) as resp:+ resp_body = resp.read()+ resp_headers = {"Content-Type": resp.headers.get("Content-Type", "application/json")}+ return resp.status, resp_headers, resp_body+ except urllib.error.HTTPError as e:+ return e.code, {"Content-Type": "application/json"}, e.read()+ except Exception as ex:+ return 502, {"Content-Type": "application/json"}, json.dumps({"message": str(ex)}).encode()+++# ---- Control plane: APIs ----++def _create_api(data):+ api_id = new_uuid()[:8]+ api = {+ "apiId": api_id,+ "name": data.get("name", "unnamed"),+ "protocolType": data.get("protocolType", "HTTP"),+ "apiEndpoint": f"http://{api_id}.execute-api.localhost:4566",+ "createdDate": time.strftime("%Y-%m-%dT%H:%M:%SZ"),+ "routeSelectionExpression": data.get("routeSelectionExpression", "$request.method $request.path"),+ "tags": data.get("tags", {}),+ "corsConfiguration": data.get("corsConfiguration", {}),+ "disableSchemaValidation": data.get("disableSchemaValidation", False),+ "disableExecuteApiEndpoint": data.get("disableExecuteApiEndpoint", False),+ "version": data.get("version", ""),+ }+ _apis[api_id] = api+ _routes[api_id] = {}+ _integrations[api_id] = {}+ _stages[api_id] = {}+ _deployments[api_id] = {}+ _api_tags[_api_arn(api_id)] = dict(data.get("tags", {}))+ return _apigw_response(api, 201)+++def _get_api(api_id):+ api = _apis.get(api_id)+ if not api:+ return _apigw_error("NotFoundException", f"API {api_id} not found", 404)+ return _apigw_response(api)+++def _get_apis():+ return _apigw_response({"items": list(_apis.values()), "nextToken": None})+++def _delete_api(api_id):+ _apis.pop(api_id, None)+ _routes.pop(api_id, None)+ _integrations.pop(api_id, None)+ _stages.pop(api_id, None)+ _deployments.pop(api_id, None)+ _api_tags.pop(_api_arn(api_id), None)+ return 204, {}, b""+++def _update_api(api_id, data):+ api = _apis.get(api_id)+ if not api:+ return _apigw_error("NotFoundException", f"API {api_id} not found", 404)+ for k in ("name", "corsConfiguration", "routeSelectionExpression",+ "disableSchemaValidation", "disableExecuteApiEndpoint", "version"):+ if k in data:+ api[k] = data[k]+ return _apigw_response(api)+++# ---- Control plane: Routes ----++def _create_route(api_id, data):+ if api_id not in _apis:+ return _apigw_error("NotFoundException", f"API {api_id} not found", 404)+ route_id = new_uuid()[:8]+ route = {+ "routeId": route_id,+ "routeKey": data.get("routeKey", "$default"),+ "target": data.get("target", ""),+ "authorizationType": data.get("authorizationType", "NONE"),+ "apiKeyRequired": data.get("apiKeyRequired", False),+ "operationName": data.get("operationName", ""),+ "requestModels": data.get("requestModels", {}),+ "requestParameters": data.get("requestParameters", {}),+ }+ _routes.setdefault(api_id, {})[route_id] = route+ return _apigw_response(route, 201)+++def _get_routes(api_id):+ return _apigw_response({"items": list(_routes.get(api_id, {}).values()), "nextToken": None})+++def _get_route(api_id, route_id):+ route = _routes.get(api_id, {}).get(route_id)+ if not route:+ return _apigw_error("NotFoundException", f"Route {route_id} not found", 404)+ return _apigw_response(route)+++def _update_route(api_id, route_id, data):+ route = _routes.get(api_id, {}).get(route_id)+ if not route:+ return _apigw_error("NotFoundException", f"Route {route_id} not found", 404)+ for k in ("routeKey", "target", "authorizationType", "apiKeyRequired", "operationName"):+ if k in data:+ route[k] = data[k]+ return _apigw_response(route)+++def _delete_route(api_id, route_id):+ _routes.get(api_id, {}).pop(route_id, None)+ return 204, {}, b""+++# ---- Control plane: Integrations ----++def _create_integration(api_id, data):+ if api_id not in _apis:+ return _apigw_error("NotFoundException", f"API {api_id} not found", 404)+ int_id = new_uuid()[:8]+ integration = {+ "integrationId": int_id,+ "integrationType": data.get("integrationType", "AWS_PROXY"),+ "integrationUri": data.get("integrationUri", ""),+ "integrationMethod": data.get("integrationMethod", "POST"),+ "payloadFormatVersion": data.get("payloadFormatVersion", "2.0"),+ "timeoutInMillis": data.get("timeoutInMillis", 30000),+ "connectionType": data.get("connectionType", "INTERNET"),+ "description": data.get("description", ""),+ "requestParameters": data.get("requestParameters", {}),+ "requestTemplates": data.get("requestTemplates", {}),+ "responseParameters": data.get("responseParameters", {}),+ }+ _integrations.setdefault(api_id, {})[int_id] = integration+ return _apigw_response(integration, 201)+++def _get_integrations(api_id):+ return _apigw_response({"items": list(_integrations.get(api_id, {}).values()), "nextToken": None})+++def _get_integration(api_id, int_id):+ integration = _integrations.get(api_id, {}).get(int_id)+ if not integration:+ return _apigw_error("NotFoundException", f"Integration {int_id} not found", 404)+ return _apigw_response(integration)+++def _update_integration(api_id, int_id, data):+ integration = _integrations.get(api_id, {}).get(int_id)+ if not integration:+ return _apigw_error("NotFoundException", f"Integration {int_id} not found", 404)+ for k in ("integrationType", "integrationUri", "integrationMethod",+ "payloadFormatVersion", "timeoutInMillis", "connectionType",+ "description", "requestParameters", "requestTemplates", "responseParameters"):+ if k in data:+ integration[k] = data[k]+ return _apigw_response(integration)+++def _delete_integration(api_id, int_id):+ _integrations.get(api_id, {}).pop(int_id, None)+ return 204, {}, b""+++# ---- Control plane: Stages ----++def _create_stage(api_id, data):+ if api_id not in _apis:+ return _apigw_error("NotFoundException", f"API {api_id} not found", 404)+ stage_name = data.get("stageName", "$default")+ stage = {+ "stageName": stage_name,+ "autoDeploy": data.get("autoDeploy", False),+ "createdDate": time.strftime("%Y-%m-%dT%H:%M:%SZ"),+ "lastUpdatedDate": time.strftime("%Y-%m-%dT%H:%M:%SZ"),+ "stageVariables": data.get("stageVariables", {}),+ "description": data.get("description", ""),+ "defaultRouteSettings": data.get("defaultRouteSettings", {}),+ "routeSettings": data.get("routeSettings", {}),+ "tags": data.get("tags", {}),+ }+ _stages.setdefault(api_id, {})[stage_name] = stage+ return _apigw_response(stage, 201)+++def _get_stages(api_id):+ return _apigw_response({"items": list(_stages.get(api_id, {}).values()), "nextToken": None})+++def _get_stage(api_id, stage_name):+ stage = _stages.get(api_id, {}).get(stage_name)+ if not stage:+ return _apigw_error("NotFoundException", f"Stage '{stage_name}' not found", 404)+ return _apigw_response(stage)+++def _update_stage(api_id, stage_name, data):+ stage = _stages.get(api_id, {}).get(stage_name)+ if not stage:+ return _apigw_error("NotFoundException", f"Stage '{stage_name}' not found", 404)+ for k in ("autoDeploy", "stageVariables", "description",+ "defaultRouteSettings", "routeSettings"):+ if k in data:+ stage[k] = data[k]+ stage["lastUpdatedDate"] = time.strftime("%Y-%m-%dT%H:%M:%SZ")+ return _apigw_response(stage)+++def _delete_stage(api_id, stage_name):+ _stages.get(api_id, {}).pop(stage_name, None)+ return 204, {}, b""+++# ---- Control plane: Deployments ----++def _create_deployment(api_id, data):+ if api_id not in _apis:+ return _apigw_error("NotFoundException", f"API {api_id} not found", 404)+ deployment_id = new_uuid()[:8]+ deployment = {+ "deploymentId": deployment_id,+ "deploymentStatus": "DEPLOYED",+ "createdDate": time.strftime("%Y-%m-%dT%H:%M:%SZ"),+ "description": data.get("description", ""),+ }+ _deployments.setdefault(api_id, {})[deployment_id] = deployment+ return _apigw_response(deployment, 201)+++def _get_deployments(api_id):+ return _apigw_response({"items": list(_deployments.get(api_id, {}).values()), "nextToken": None})+++def _get_deployment(api_id, deployment_id):+ deployment = _deployments.get(api_id, {}).get(deployment_id)+ if not deployment:+ return _apigw_error("NotFoundException", f"Deployment {deployment_id} not found", 404)+ return _apigw_response(deployment)+++def _delete_deployment(api_id, deployment_id):+ _deployments.get(api_id, {}).pop(deployment_id, None)+ return 204, {}, b""+++# ---- Control plane: Tags ----++def _get_tags(resource_arn: str):+ tags = _api_tags.get(resource_arn, {})+ return _apigw_response({"tags": tags})+++def _tag_resource(resource_arn: str, data: dict):+ tags = data.get("tags", {})+ _api_tags.setdefault(resource_arn, {}).update(tags)+ return 201, {}, b""+++def _untag_resource(resource_arn: str, tag_keys: list):+ existing = _api_tags.get(resource_arn, {})+ for key in tag_keys:+ existing.pop(key, None)+ return 204, {}, b""+++# ---- Control plane: Authorizers ----++def _create_authorizer(api_id, data):+ if api_id not in _apis:+ return _apigw_error("NotFoundException", f"API {api_id} not found", 404)+ auth_id = new_uuid()[:8]+ authorizer = {+ "authorizerId": auth_id,+ "authorizerType": data.get("authorizerType", "JWT"),+ "name": data.get("name", ""),+ "identitySource": data.get("identitySource", "$request.header.Authorization"),+ "jwtConfiguration": data.get("jwtConfiguration", {}),+ "authorizerUri": data.get("authorizerUri", ""),+ "authorizerPayloadFormatVersion": data.get("authorizerPayloadFormatVersion", "2.0"),+ "authorizerResultTtlInSeconds": data.get("authorizerResultTtlInSeconds", 300),+ "enableSimpleResponses": data.get("enableSimpleResponses", False),+ "authorizerCredentialsArn": data.get("authorizerCredentialsArn", ""),+ }+ _authorizers.setdefault(api_id, {})[auth_id] = authorizer+ return _apigw_response(authorizer, 201)+++def _get_authorizers(api_id):+ return _apigw_response({"items": list(_authorizers.get(api_id, {}).values()), "nextToken": None})+++def _get_authorizer(api_id, auth_id):+ authorizer = _authorizers.get(api_id, {}).get(auth_id)+ if not authorizer:+ return _apigw_error("NotFoundException", f"Authorizer {auth_id} not found", 404)+ return _apigw_response(authorizer)+++def _update_authorizer(api_id, auth_id, data):+ authorizer = _authorizers.get(api_id, {}).get(auth_id)+ if not authorizer:+ return _apigw_error("NotFoundException", f"Authorizer {auth_id} not found", 404)+ for k in ("name", "identitySource", "jwtConfiguration", "authorizerUri",+ "authorizerPayloadFormatVersion", "authorizerResultTtlInSeconds",+ "enableSimpleResponses", "authorizerCredentialsArn"):+ if k in data:+ authorizer[k] = data[k]+ return _apigw_response(authorizer)+++def _delete_authorizer(api_id, auth_id):+ _authorizers.get(api_id, {}).pop(auth_id, None)+ return 204, {}, b""+++def reset():+ _apis.clear()+ _routes.clear()+ _integrations.clear()+ _stages.clear()+ _deployments.clear()+ _authorizers.clear()+ _api_tags.clear()diff --git a/services/athena.py b/services/athena.pyindex d1ed3289..4bb533e1 100644--- a/services/athena.py+++ b/services/athena.py@@ -4,11 +4,17 @@ JSON-based API via X-Amz-Target (AmazonAthena).Uses DuckDB to actually execute SQL queries against S3 data (CSV/JSON/Parquet).Supports: StartQueryExecution, GetQueryExecution, GetQueryResults,StopQueryExecution, ListQueryExecutions,- CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups,- CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries.+ CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, UpdateWorkGroup,+ CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries,+ BatchGetNamedQuery, BatchGetQueryExecution,+ CreateDataCatalog, GetDataCatalog, ListDataCatalogs, DeleteDataCatalog, UpdateDataCatalog,+ CreatePreparedStatement, GetPreparedStatement, DeletePreparedStatement, ListPreparedStatements,+ GetTableMetadata, ListTableMetadata,+ TagResource, UntagResource, ListTagsForResource."""import os+import reimport jsonimport timeimport logging@@ -22,7 +28,7 @@ ACCOUNT_ID = "000000000000"REGION = "us-east-1"S3_DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/localstack-data/s3")-_executions: dict = {} # query_execution_id -> execution dict+_executions: dict = {}_workgroups: dict = {"primary": {"Name": "primary",@@ -33,8 +39,17 @@ _workgroups: dict = {}}_named_queries: dict = {}+_data_catalogs: dict = {+ "AwsDataCatalog": {+ "Name": "AwsDataCatalog",+ "Description": "AWS Glue Data Catalog",+ "Type": "GLUE",+ "Parameters": {},+ }+}+_prepared_statements: dict = {} # "workgroup/name" -> statement dict+_tags: dict = {} # arn -> {key: value, ...}-# Try to import DuckDBtry:import duckdb_duckdb_available = True@@ -43,6 +58,38 @@ except ImportError:_duckdb_available = Falselogger.warning("Athena: DuckDB not available — install with: pip install duckdb")+_DUCKDB_TYPE_MAP = {+ "BOOLEAN": "boolean",+ "TINYINT": "tinyint",+ "SMALLINT": "smallint",+ "INTEGER": "integer",+ "INT": "integer",+ "BIGINT": "bigint",+ "HUGEINT": "bigint",+ "FLOAT": "float",+ "REAL": "float",+ "DOUBLE": "double",+ "DECIMAL": "decimal",+ "VARCHAR": "varchar",+ "BLOB": "varbinary",+ "DATE": "date",+ "TIME": "time",+ "TIMESTAMP": "timestamp",+ "TIMESTAMP WITH TIME ZONE": "timestamp",+ "INTERVAL": "varchar",+ "LIST": "array",+ "STRUCT": "row",+ "MAP": "map",+}+++def _arn_workgroup(name):+ return f"arn:aws:athena:{REGION}:{ACCOUNT_ID}:workgroup/{name}"+++def _arn_datacatalog(name):+ return f"arn:aws:athena:{REGION}:{ACCOUNT_ID}:datacatalog/{name}"+async def handle_request(method, path, headers, body, query_params):target = headers.get("x-amz-target", "")@@ -70,6 +117,24 @@ async def handle_request(method, path, headers, body, query_params):"ListNamedQueries": _list_named_queries,"BatchGetNamedQuery": _batch_get_named_query,"BatchGetQueryExecution": _batch_get_query_execution,+ # Data Catalogs+ "CreateDataCatalog": _create_data_catalog,+ "GetDataCatalog": _get_data_catalog,+ "ListDataCatalogs": _list_data_catalogs,+ "DeleteDataCatalog": _delete_data_catalog,+ "UpdateDataCatalog": _update_data_catalog,+ # Prepared Statements+ "CreatePreparedStatement": _create_prepared_statement,+ "GetPreparedStatement": _get_prepared_statement,+ "DeletePreparedStatement": _delete_prepared_statement,+ "ListPreparedStatements": _list_prepared_statements,+ # Table Metadata+ "GetTableMetadata": _get_table_metadata,+ "ListTableMetadata": _list_table_metadata,+ # Tags+ "TagResource": _tag_resource,+ "UntagResource": _untag_resource,+ "ListTagsForResource": _list_tags_for_resource,}handler = handlers.get(action)@@ -78,36 +143,50 @@ async def handle_request(method, path, headers, body, query_params):return handler(data)+# ---- Query Execution ----+def _start_query_execution(data):query = data.get("QueryString", "")query_id = new_uuid()workgroup = data.get("WorkGroup", "primary")output_location = (data.get("ResultConfiguration", {}).get("OutputLocation")- or _workgroups.get(workgroup, {}).get("Configuration", {}).get("ResultConfiguration", {}).get("OutputLocation", "s3://athena-results/")+ or _workgroups.get(workgroup, {}).get("Configuration", {})+ .get("ResultConfiguration", {}).get("OutputLocation", "s3://athena-results/"))db = data.get("QueryExecutionContext", {}).get("Database", "default")+ catalog = data.get("QueryExecutionContext", {}).get("Catalog", "AwsDataCatalog")execution = {"QueryExecutionId": query_id,"Query": query,"StatementType": _detect_statement_type(query),"ResultConfiguration": {"OutputLocation": f"{output_location}{query_id}.csv"},- "QueryExecutionContext": {"Database": db},+ "QueryExecutionContext": {"Database": db, "Catalog": catalog},"Status": {- "State": "RUNNING",+ "State": "QUEUED","SubmissionDateTime": time.time(),"CompletionDateTime": None,"StateChangeReason": "",},- "Statistics": {"EngineExecutionTimeInMillis": 0, "DataScannedInBytes": 0},+ "Statistics": {+ "EngineExecutionTimeInMillis": 0,+ "DataScannedInBytes": 0,+ "DataManifestLocation": "",+ "TotalExecutionTimeInMillis": 0,+ "QueryQueueTimeInMillis": 0,+ "QueryPlanningTimeInMillis": 0,+ "ServiceProcessingTimeInMillis": 0,+ },"WorkGroup": workgroup,+ "EngineVersion": {"SelectedEngineVersion": "Athena engine version 3",+ "EffectiveEngineVersion": "Athena engine version 3"},"_results": None,+ "_column_types": None,"_error": None,}_executions[query_id] = execution- # Run query in background threadthread = threading.Thread(target=_execute_query, args=(query_id, query, db), daemon=True)thread.start()@@ -115,81 +194,132 @@ def _start_query_execution(data):def _execute_query(query_id, query, database):- """Execute query using DuckDB in a background thread."""execution = _executions.get(query_id)if not execution:return+ execution["Status"]["State"] = "RUNNING"start = time.time()+try:if _duckdb_available:results = _run_duckdb(query, database)else:results = _mock_query_results(query)- execution["_results"] = results+ execution["_results"] = {"columns": results["columns"], "rows": results["rows"]}+ execution["_column_types"] = results.get("column_types", ["varchar"] * len(results["columns"]))execution["Status"]["State"] = "SUCCEEDED"- execution["Statistics"]["EngineExecutionTimeInMillis"] = int((time.time() - start) * 1000)+ elapsed_ms = int((time.time() - start) * 1000)+ execution["Statistics"]["EngineExecutionTimeInMillis"] = elapsed_ms+ execution["Statistics"]["TotalExecutionTimeInMillis"] = elapsed_ms + 50+ execution["Statistics"]["QueryPlanningTimeInMillis"] = min(20, elapsed_ms)+ execution["Statistics"]["ServiceProcessingTimeInMillis"] = 30execution["Statistics"]["DataScannedInBytes"] = sum(len(str(row)) for row in results.get("rows", []))except Exception as e:logger.error(f"Athena query {query_id} failed: {e}")execution["Status"]["State"] = "FAILED"- execution["Status"]["StateChangeReason"] = str(e)+ execution["Status"]["StateChangeReason"] = str(e)[:2000]execution["_error"] = str(e)execution["Status"]["CompletionDateTime"] = time.time()def _run_duckdb(query, database):- """Execute SQL via DuckDB, with S3 data directory available."""import duckdbconn = duckdb.connect(":memory:")-- # Rewrite s3:// paths to local filesystem paths before executingrewritten = _rewrite_s3_paths(query)try:result = conn.execute(rewritten)- columns = [desc[0] for desc in result.description] if result.description else []+ columns = []+ column_types = []+ if result.description:+ for desc in result.description:+ columns.append(desc[0])+ raw_type = desc[1] if len(desc) > 1 else "VARCHAR"+ if isinstance(raw_type, str):+ type_key = raw_type.upper().split("(")[0].strip()+ else:+ type_key = str(raw_type).upper().split("(")[0].strip()+ athena_type = _DUCKDB_TYPE_MAP.get(type_key, "varchar")+ column_types.append(athena_type)rows = result.fetchall()conn.close()- return {"columns": columns, "rows": [list(r) for r in rows]}+ return {"columns": columns, "column_types": column_types,+ "rows": [list(r) for r in rows]}except Exception as e:conn.close()raise edef _rewrite_s3_paths(query):- """Replace s3://bucket/key references with local file paths."""- import re+ """Replace s3://bucket/key references with local file paths.+ Handles: quoted strings, read_csv/read_parquet/read_json function args,+ and FROM clauses with s3 paths.+ """def replace_s3(match):- s3_path = match.group(1)- parts = s3_path.lstrip("s3://").split("/", 1)+ prefix = match.group(1)+ s3_uri = match.group(2)+ suffix = match.group(3)+ stripped = s3_uri+ if stripped.startswith("s3://"):+ stripped = stripped[5:]+ elif stripped.startswith("s3a://"):+ stripped = stripped[6:]+ parts = stripped.split("/", 1)bucket = parts[0]key = parts[1] if len(parts) > 1 else ""local_path = os.path.join(S3_DATA_DIR, bucket, key)- return f"'{local_path}'"- return re.sub(r"'(s3://[^']+)'", replace_s3, query)+ return f"{prefix}{local_path}{suffix}"++ result = re.sub(+ r"""(["'])(s3a?://[^"']+)(["'])""",+ replace_s3,+ query,+ )+ result = re.sub(+ r"(FROM\s+)(s3a?://\S+)(\s|;|$)",+ replace_s3,+ result,+ flags=re.IGNORECASE,+ )+ return resultdef _mock_query_results(query):- """Return mock results when DuckDB is not available."""query_upper = query.strip().upper()if query_upper.startswith("SELECT"):- return {"columns": ["result"], "rows": [["mock_value"]]}- return {"columns": [], "rows": []}+ match = re.match(r"SELECT\s+'([^']*)'", query.strip(), re.IGNORECASE)+ if match:+ val = match.group(1)+ return {"columns": [val], "column_types": ["varchar"], "rows": [[val]]}+ alias_pattern = re.findall(+ r"""(?:(\d+(?:\.\d+)?)|'([^']*)')\s+AS\s+(\w+)""",+ query.strip(), re.IGNORECASE,+ )+ if alias_pattern:+ cols = [m[2] for m in alias_pattern]+ types = ["integer" if m[0] else "varchar" for m in alias_pattern]+ vals = [m[0] if m[0] else m[1] for m in alias_pattern]+ return {"columns": cols, "column_types": types, "rows": [vals]}+ return {"columns": ["result"], "column_types": ["varchar"],+ "rows": [["mock_value"]]}+ return {"columns": [], "column_types": [], "rows": []}def _detect_statement_type(query):q = query.strip().upper()- if q.startswith("SELECT"):+ if q.startswith("SELECT") or q.startswith("WITH"):return "DML"if q.startswith(("CREATE", "DROP", "ALTER")):return "DDL"- return "DML"+ if q.startswith(("INSERT", "DELETE", "UPDATE", "MERGE")):+ return "DML"+ return "UTILITY"def _get_query_execution(data):@@ -202,47 +332,99 @@ def _get_query_execution(data):def _get_query_results(data):query_id = data.get("QueryExecutionId")+ max_results = data.get("MaxResults", 1000)+ next_token = data.get("NextToken")execution = _executions.get(query_id)if not execution:return error_response_json("InvalidRequestException", f"Query {query_id} not found", 400)- if execution["Status"]["State"] != "SUCCEEDED":+ state = execution["Status"]["State"]+ if state == "FAILED":+ return error_response_json("InvalidRequestException",+ f"Query has failed: {execution['Status'].get('StateChangeReason', 'Unknown')}", 400)+ if state != "SUCCEEDED":return error_response_json("InvalidRequestException",- f"Query is in state {execution['Status']['State']}", 400)+ f"Query is in state {state}", 400)results = execution.get("_results") or {"columns": [], "rows": []}columns = results.get("columns", [])rows = results.get("rows", [])+ column_types = execution.get("_column_types") or ["varchar"] * len(columns)++ start_idx = 0+ if next_token:+ try:+ start_idx = int(next_token)+ except ValueError:+ pass++ page_rows = rows[start_idx:start_idx + max_results]- # Format as Athena ResultSetresult_rows = []- # Header rowresult_rows.append({"Data": [{"VarCharValue": col} for col in columns]})- # Data rows- for row in rows:- result_rows.append({"Data": [{"VarCharValue": str(v) if v is not None else ""} for v in row]})-- return json_response({- "QueryExecution": _execution_out(execution),+ for row in page_rows:+ result_rows.append({+ "Data": [{"VarCharValue": str(v) if v is not None else ""} for v in row]+ })++ column_info = []+ for i, col in enumerate(columns):+ ctype = column_types[i] if i < len(column_types) else "varchar"+ precision, scale = _type_precision_scale(ctype)+ column_info.append({+ "CatalogName": "hive",+ "SchemaName": "",+ "TableName": "",+ "Name": col,+ "Label": col,+ "Type": ctype,+ "Precision": precision,+ "Scale": scale,+ "Nullable": "UNKNOWN",+ "CaseSensitive": ctype == "varchar",+ })++ response = {"ResultSet": {"Rows": result_rows,- "ResultSetMetadata": {- "ColumnInfo": [- {"Name": col, "Type": "varchar", "Label": col, "Nullable": "NULLABLE",- "CaseSensitive": False, "Precision": 0, "Scale": 0}- for col in columns- ]- },+ "ResultSetMetadata": {"ColumnInfo": column_info},},"UpdateCount": 0,- })+ }++ end_idx = start_idx + max_results+ if end_idx < len(rows):+ response["NextToken"] = str(end_idx)++ return json_response(response)+++def _type_precision_scale(athena_type):+ if athena_type in ("integer", "int"):+ return 10, 0+ if athena_type == "bigint":+ return 19, 0+ if athena_type == "smallint":+ return 5, 0+ if athena_type == "tinyint":+ return 3, 0+ if athena_type == "double":+ return 17, 0+ if athena_type == "float":+ return 7, 0+ if athena_type == "boolean":+ return 0, 0+ if athena_type == "decimal":+ return 38, 0+ return 0, 0def _stop_query_execution(data):query_id = data.get("QueryExecutionId")execution = _executions.get(query_id)- if execution and execution["Status"]["State"] == "RUNNING":+ if execution and execution["Status"]["State"] in ("QUEUED", "RUNNING"):execution["Status"]["State"] = "CANCELLED"+ execution["Status"]["StateChangeReason"] = "Query was cancelled by user"execution["Status"]["CompletionDateTime"] = time.time()return json_response({})@@ -253,6 +435,8 @@ def _list_query_executions(data):return json_response({"QueryExecutionIds": ids})+# ---- WorkGroups ----+def _create_workgroup(data):name = data.get("Name")if name in _workgroups:@@ -264,6 +448,10 @@ def _create_workgroup(data):"CreationTime": time.time(),"Configuration": data.get("Configuration", {}),}+ tags = data.get("Tags", [])+ if tags:+ arn = _arn_workgroup(name)+ _tags[arn] = {t["Key"]: t["Value"] for t in tags}return json_response({})@@ -272,6 +460,7 @@ def _delete_workgroup(data):if name == "primary":return error_response_json("InvalidRequestException", "Cannot delete primary workgroup", 400)_workgroups.pop(name, None)+ _tags.pop(_arn_workgroup(name), None)return json_response({})@@ -280,11 +469,18 @@ def _get_workgroup(data):wg = _workgroups.get(name)if not wg:return error_response_json("InvalidRequestException", f"WorkGroup {name} not found", 400)- return json_response({"WorkGroup": wg})+ out = dict(wg)+ out.setdefault("WorkGroupConfiguration", out.get("Configuration", {}))+ return json_response({"WorkGroup": out})def _list_workgroups(data):- return json_response({"WorkGroups": [{"Name": wg["Name"], "State": wg["State"]} for wg in _workgroups.values()]})+ return json_response({+ "WorkGroups": [{"Name": wg["Name"], "State": wg["State"],+ "Description": wg.get("Description", ""),+ "CreationTime": wg.get("CreationTime", 0)}+ for wg in _workgroups.values()]+ })def _update_workgroup(data):@@ -293,12 +489,33 @@ def _update_workgroup(data):if not wg:return error_response_json("InvalidRequestException", f"WorkGroup {name} not found", 400)if "ConfigurationUpdates" in data:- wg["Configuration"].update(data["ConfigurationUpdates"])+ updates = data["ConfigurationUpdates"]+ config = wg.setdefault("Configuration", {})+ if "ResultConfigurationUpdates" in updates:+ rc = config.setdefault("ResultConfiguration", {})+ rcu = updates["ResultConfigurationUpdates"]+ if "OutputLocation" in rcu:+ rc["OutputLocation"] = rcu["OutputLocation"]+ if "EncryptionConfiguration" in rcu:+ rc["EncryptionConfiguration"] = rcu["EncryptionConfiguration"]+ if rcu.get("RemoveOutputLocation"):+ rc.pop("OutputLocation", None)+ if rcu.get("RemoveEncryptionConfiguration"):+ rc.pop("EncryptionConfiguration", None)+ for ck in ("EnforceWorkGroupConfiguration", "PublishCloudWatchMetricsEnabled",+ "BytesScannedCutoffPerQuery", "RequesterPaysEnabled",+ "EngineVersion"):+ if ck in updates:+ config[ck] = updates[ck]if "Description" in data:wg["Description"] = data["Description"]+ if "State" in data:+ wg["State"] = data["State"]return json_response({})+# ---- Named Queries ----+def _create_named_query(data):query_id = new_uuid()_named_queries[query_id] = {@@ -334,16 +551,218 @@ def _list_named_queries(data):def _batch_get_named_query(data):ids = data.get("NamedQueryIds", [])queries = [_named_queries[qid] for qid in ids if qid in _named_queries]- unprocessed = [qid for qid in ids if qid not in _named_queries]+ unprocessed = [{"NamedQueryId": qid, "ErrorCode": "INTERNAL_FAILURE", "ErrorMessage": "Not found"}+ for qid in ids if qid not in _named_queries]return json_response({"NamedQueries": queries, "UnprocessedNamedQueryIds": unprocessed})def _batch_get_query_execution(data):ids = data.get("QueryExecutionIds", [])execs = [_execution_out(_executions[qid]) for qid in ids if qid in _executions]- unprocessed = [qid for qid in ids if qid not in _executions]+ unprocessed = [{"QueryExecutionId": qid, "ErrorCode": "INTERNAL_FAILURE", "ErrorMessage": "Not found"}+ for qid in ids if qid not in _executions]return json_response({"QueryExecutions": execs, "UnprocessedQueryExecutionIds": unprocessed})+# ---- Data Catalogs ----++def _create_data_catalog(data):+ name = data.get("Name")+ if not name:+ return error_response_json("InvalidRequestException", "Name is required", 400)+ if name in _data_catalogs:+ return error_response_json("InvalidRequestException",+ f"Data catalog {name} already exists", 400)+ catalog_type = data.get("Type", "HIVE")+ if catalog_type not in ("HIVE", "LAMBDA", "GLUE"):+ return error_response_json("InvalidRequestException",+ f"Invalid catalog type: {catalog_type}", 400)+ _data_catalogs[name] = {+ "Name": name,+ "Description": data.get("Description", ""),+ "Type": catalog_type,+ "Parameters": data.get("Parameters", {}),+ }+ tags = data.get("Tags", [])+ if tags:+ arn = _arn_datacatalog(name)+ _tags[arn] = {t["Key"]: t["Value"] for t in tags}+ return json_response({})+++def _get_data_catalog(data):+ name = data.get("Name")+ catalog = _data_catalogs.get(name)+ if not catalog:+ return error_response_json("InvalidRequestException",+ f"Data catalog {name} not found", 400)+ return json_response({"DataCatalog": catalog})+++def _list_data_catalogs(data):+ summaries = [{"CatalogName": c["Name"], "Type": c["Type"]}+ for c in _data_catalogs.values()]+ return json_response({"DataCatalogsSummary": summaries})+++def _delete_data_catalog(data):+ name = data.get("Name")+ if name == "AwsDataCatalog":+ return error_response_json("InvalidRequestException",+ "Cannot delete the default AWS data catalog", 400)+ if name not in _data_catalogs:+ return error_response_json("InvalidRequestException",+ f"Data catalog {name} not found", 400)+ del _data_catalogs[name]+ _tags.pop(_arn_datacatalog(name), None)+ return json_response({})+++def _update_data_catalog(data):+ name = data.get("Name")+ catalog = _data_catalogs.get(name)+ if not catalog:+ return error_response_json("InvalidRequestException",+ f"Data catalog {name} not found", 400)+ if "Description" in data:+ catalog["Description"] = data["Description"]+ if "Type" in data:+ catalog["Type"] = data["Type"]+ if "Parameters" in data:+ catalog["Parameters"] = data["Parameters"]+ return json_response({})+++# ---- Prepared Statements ----++def _create_prepared_statement(data):+ name = data.get("StatementName")+ workgroup = data.get("WorkGroup", "primary")+ query = data.get("QueryStatement", "")+ if not name:+ return error_response_json("InvalidRequestException", "StatementName is required", 400)+ key = f"{workgroup}/{name}"+ if key in _prepared_statements:+ return error_response_json("InvalidRequestException",+ f"Prepared statement {name} already exists in {workgroup}", 400)+ _prepared_statements[key] = {+ "StatementName": name,+ "WorkGroupName": workgroup,+ "QueryStatement": query,+ "Description": data.get("Description", ""),+ "LastModifiedTime": time.time(),+ }+ return json_response({})+++def _get_prepared_statement(data):+ name = data.get("StatementName")+ workgroup = data.get("WorkGroup") or data.get("WorkGroupName", "primary")+ key = f"{workgroup}/{name}"+ stmt = _prepared_statements.get(key)+ if not stmt:+ return error_response_json("ResourceNotFoundException",+ f"Prepared statement {name} not found in {workgroup}", 400)+ return json_response({"PreparedStatement": stmt})+++def _delete_prepared_statement(data):+ name = data.get("StatementName")+ workgroup = data.get("WorkGroup") or data.get("WorkGroupName", "primary")+ key = f"{workgroup}/{name}"+ if key not in _prepared_statements:+ return error_response_json("ResourceNotFoundException",+ f"Prepared statement {name} not found", 400)+ del _prepared_statements[key]+ return json_response({})+++def _list_prepared_statements(data):+ workgroup = data.get("WorkGroup") or data.get("WorkGroupName", "primary")+ stmts = [+ {"StatementName": s["StatementName"], "LastModifiedTime": s["LastModifiedTime"]}+ for k, s in _prepared_statements.items()+ if s.get("WorkGroupName") == workgroup+ ]+ return json_response({"PreparedStatements": stmts})+++# ---- Table Metadata (stubs) ----++def _get_table_metadata(data):+ catalog = data.get("CatalogName", "AwsDataCatalog")+ db = data.get("DatabaseName", "default")+ table = data.get("TableName", "")+ return json_response({+ "TableMetadata": {+ "Name": table,+ "CreateTime": time.time(),+ "LastAccessTime": time.time(),+ "TableType": "EXTERNAL_TABLE",+ "Columns": [],+ "PartitionKeys": [],+ "Parameters": {"classification": "csv"},+ }+ })+++def _list_table_metadata(data):+ return json_response({"TableMetadataList": []})+++# ---- Tags ----++def _tag_resource(data):+ arn = data.get("ResourceARN", "")+ tags = data.get("Tags", [])+ tag_dict = _tags.setdefault(arn, {})+ for t in tags:+ tag_dict[t["Key"]] = t["Value"]+ return json_response({})+++def _untag_resource(data):+ arn = data.get("ResourceARN", "")+ keys = data.get("TagKeys", [])+ tag_dict = _tags.get(arn, {})+ for k in keys:+ tag_dict.pop(k, None)+ return json_response({})+++def _list_tags_for_resource(data):+ arn = data.get("ResourceARN", "")+ tag_dict = _tags.get(arn, {})+ tags = [{"Key": k, "Value": v} for k, v in tag_dict.items()]+ return json_response({"Tags": tags})+++# ---- Helpers ----+def _execution_out(ex):return {k: v for k, v in ex.items() if not k.startswith("_")}+++def reset():+ import time as _time+ global _workgroups, _data_catalogs+ _executions.clear()+ _named_queries.clear()+ _prepared_statements.clear()+ _workgroups = {+ "primary": {+ "Name": "primary",+ "State": "ENABLED",+ "Description": "Primary workgroup",+ "CreationTime": _time.time(),+ "Configuration": {"ResultConfiguration": {"OutputLocation": "s3://athena-results/"}},+ }+ }+ _data_catalogs = {+ "AwsDataCatalog": {+ "Name": "AwsDataCatalog",+ "Description": "AWS Glue Data Catalog",+ "Type": "GLUE",+ "Parameters": {},+ }+ }diff --git a/services/cloudwatch.py b/services/cloudwatch.pyindex fd3141a9..9f6721ba 100644--- a/services/cloudwatch.py+++ b/services/cloudwatch.py@@ -1,16 +1,20 @@"""CloudWatch Metrics Service Emulator.Supports legacy Query API (form-encoded), smithy-rpc-v2-cbor (botocore 1.42+),-and JSON/X-Amz-Target protocol (botocore 1.42 with endpoint_url).-Operations: PutMetricData, GetMetricStatistics, ListMetrics,- PutMetricAlarm, DescribeAlarms, DeleteAlarms,- EnableAlarmActions, DisableAlarmActions, SetAlarmState.+and JSON/X-Amz-Target protocol.+Operations: PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics,+ PutMetricAlarm, PutCompositeAlarm, DescribeAlarms, DescribeAlarmsForMetric,+ DescribeAlarmHistory, DeleteAlarms,+ EnableAlarmActions, DisableAlarmActions, SetAlarmState,+ TagResource, UntagResource, ListTagsForResource,+ PutDashboard, GetDashboard, DeleteDashboards, ListDashboards."""import reimport jsonimport timeimport logging+from datetime import datetime, timezonefrom urllib.parse import parse_qsfrom collections import defaultdict@@ -20,11 +24,167 @@ logger = logging.getLogger("cloudwatch")ACCOUNT_ID = "000000000000"REGION = "us-east-1"+TWO_WEEKS_SECONDS = 14 * 24 * 3600_metrics: dict = defaultdict(list)_alarms: dict = {}+_composite_alarms: dict = {}+_alarm_history: list = []+_resource_tags: dict = {}+_dashboards: dict = {} # dashboard_name -> {DashboardName, DashboardBody, LastModified}+# ---------------------------------------------------------------------------+# Timestamp helpers+# ---------------------------------------------------------------------------++def _parse_ts(value):+ """Parse ISO-8601 string, epoch float, or None into a Unix timestamp."""+ if value is None:+ return None+ if isinstance(value, (int, float)):+ return float(value)+ if isinstance(value, str):+ value = value.strip()+ if not value:+ return None+ try:+ return float(value)+ except ValueError:+ pass+ for fmt in ("%Y-%m-%dT%H:%M:%S.%fZ", "%Y-%m-%dT%H:%M:%SZ",+ "%Y-%m-%dT%H:%M:%S.%f%z", "%Y-%m-%dT%H:%M:%S%z",+ "%Y-%m-%dT%H:%M:%S"):+ try:+ dt = datetime.strptime(value, fmt)+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=timezone.utc)+ return dt.timestamp()+ except ValueError:+ continue+ return None+++def _ts_iso(epoch):+ return datetime.fromtimestamp(epoch, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++# ---------------------------------------------------------------------------+# Metric eviction+# ---------------------------------------------------------------------------++def _evict_old_metrics():+ cutoff = time.time() - TWO_WEEKS_SECONDS+ empty_keys = []+ for key, pts in _metrics.items():+ _metrics[key] = [p for p in pts if p["Timestamp"] >= cutoff]+ if not _metrics[key]:+ empty_keys.append(key)+ for key in empty_keys:+ del _metrics[key]+++# ---------------------------------------------------------------------------+# Statistics helpers+# ---------------------------------------------------------------------------++def _calc_stats(values):+ if not values:+ return {}+ return {+ "SampleCount": float(len(values)),+ "Sum": sum(values),+ "Average": sum(values) / len(values),+ "Minimum": min(values),+ "Maximum": max(values),+ }+++def _stat_value(stats, stat_name):+ """Extract a single statistic from a stats dict. Handles pNN percentiles as Average."""+ if stat_name in stats:+ return stats[stat_name]+ if stat_name.startswith("p") and stat_name[1:].replace(".", "").isdigit():+ return stats.get("Average", 0)+ return stats.get("Average", 0)+++# ---------------------------------------------------------------------------+# Alarm evaluation+# ---------------------------------------------------------------------------++def _evaluate_alarm(alarm):+ ns = alarm.get("Namespace")+ mn = alarm.get("MetricName")+ if not ns or not mn:+ return++ all_pts = []+ for (k_ns, k_mn, _), pts in _metrics.items():+ if k_ns == ns and k_mn == mn:+ all_pts.extend(pts)+ if not all_pts:+ return++ period = alarm.get("Period", 60)+ eval_periods = alarm.get("EvaluationPeriods", 1)+ cutoff = time.time() - period * eval_periods+ recent = [p for p in all_pts if p["Timestamp"] >= cutoff]+ if not recent:+ return++ stats = _calc_stats([p["Value"] for p in recent])+ val = _stat_value(stats, alarm.get("Statistic", "Average"))+ threshold = alarm.get("Threshold", 0)+ op = alarm.get("ComparisonOperator", "")++ cmp = {+ "GreaterThanOrEqualToThreshold": val >= threshold,+ "GreaterThanThreshold": val > threshold,+ "LessThanThreshold": val < threshold,+ "LessThanOrEqualToThreshold": val <= threshold,+ "GreaterThanUpperThreshold": val > threshold,+ "LessThanLowerThreshold": val < threshold,+ "LessThanLowerOrGreaterThanUpperThreshold": val < threshold,+ }+ breaching = cmp.get(op, False)+ old_state = alarm["StateValue"]+ new_state = "ALARM" if breaching else "OK"+ if old_state != new_state:+ reason = f"Threshold Crossed: {alarm.get('Statistic','Average')} {val} {op} {threshold}"+ alarm["StateValue"] = new_state+ alarm["StateReason"] = reason+ alarm["StateUpdatedTimestamp"] = time.time()+ _record_history(alarm["AlarmName"], old_state, new_state, reason)+++def _evaluate_all_alarms():+ for alarm in _alarms.values():+ try:+ _evaluate_alarm(alarm)+ except Exception:+ logger.debug("alarm eval error", exc_info=True)+++def _record_history(alarm_name, old_state, new_state, reason):+ _alarm_history.append({+ "AlarmName": alarm_name,+ "AlarmType": "MetricAlarm",+ "Timestamp": _ts_iso(time.time()),+ "HistoryItemType": "StateUpdate",+ "HistorySummary": f"Alarm updated from {old_state} to {new_state}",+ "HistoryData": json.dumps({+ "version": "1.0",+ "oldState": {"stateValue": old_state},+ "newState": {"stateValue": new_state, "stateReason": reason},+ }),+ })+++# ---------------------------------------------------------------------------+# Request dispatcher+# ---------------------------------------------------------------------------+async def handle_request(method, path, headers, body, query_params):content_type = headers.get("content-type", "")target = headers.get("x-amz-target", "")@@ -52,7 +212,6 @@ async def handle_request(method, path, headers, body, query_params):for k, v in parse_qs(body.decode("utf-8", errors="replace")).items():params[k] = v- # Extract action: X-Amz-Target first, then URL path, then form paramsaction = ""if target and "." in target:action = target.split(".")[-1]@@ -63,16 +222,29 @@ async def handle_request(method, path, headers, body, query_params):if not action:action = _p(params, "Action")+ _evict_old_metrics()+handlers = {"PutMetricData": _put_metric_data,"GetMetricStatistics": _get_metric_statistics,+ "GetMetricData": _get_metric_data,"ListMetrics": _list_metrics,"PutMetricAlarm": _put_metric_alarm,+ "PutCompositeAlarm": _put_composite_alarm,"DescribeAlarms": _describe_alarms,+ "DescribeAlarmsForMetric": _describe_alarms_for_metric,+ "DescribeAlarmHistory": _describe_alarm_history,"DeleteAlarms": _delete_alarms,"EnableAlarmActions": _enable_alarm_actions,"DisableAlarmActions": _disable_alarm_actions,"SetAlarmState": _set_alarm_state,+ "TagResource": _tag_resource,+ "UntagResource": _untag_resource,+ "ListTagsForResource": _list_tags_for_resource,+ "PutDashboard": _put_dashboard,+ "GetDashboard": _get_dashboard,+ "DeleteDashboards": _delete_dashboards,+ "ListDashboards": _list_dashboards,}handler = handlers.get(action)@@ -81,38 +253,66 @@ async def handle_request(method, path, headers, body, query_params):return handler(params, cbor_data, is_cbor, is_json)+# ---------------------------------------------------------------------------+# PutMetricData+# ---------------------------------------------------------------------------+def _put_metric_data(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:namespace = cbor_data.get("Namespace", "")for md in cbor_data.get("MetricData", []):- metric_name = md.get("MetricName", "")- value = float(md.get("Value", 0))- unit = md.get("Unit", "None")- ts = time.time()+ mn = md.get("MetricName", "")dims = {d["Name"]: d["Value"] for d in md.get("Dimensions", [])}- _metrics[(namespace, metric_name, _dims_key(dims))].append(- {"Timestamp": ts, "Value": value, "Unit": unit, "Dimensions": dims}- )++ if "Values" in md:+ values = md["Values"]+ counts = md.get("Counts", [1.0] * len(values))+ for v, c in zip(values, counts):+ for _ in range(int(c)):+ _metrics[(namespace, mn, _dims_key(dims))].append({+ "Timestamp": _parse_ts(md.get("Timestamp")) or time.time(),+ "Value": float(v),+ "Unit": md.get("Unit", "None"),+ "Dimensions": dims,+ })+ elif "StatisticValues" in md:+ sv = md["StatisticValues"]+ _metrics[(namespace, mn, _dims_key(dims))].append({+ "Timestamp": _parse_ts(md.get("Timestamp")) or time.time(),+ "Value": sv.get("Sum", 0) / max(sv.get("SampleCount", 1), 1),+ "Unit": md.get("Unit", "None"),+ "Dimensions": dims,+ "_stat": sv,+ })+ else:+ _metrics[(namespace, mn, _dims_key(dims))].append({+ "Timestamp": _parse_ts(md.get("Timestamp")) or time.time(),+ "Value": float(md.get("Value", 0)),+ "Unit": md.get("Unit", "None"),+ "Dimensions": dims,+ })else:namespace = _p(params, "Namespace")i = 1while _p(params, f"MetricData.member.{i}.MetricName"):- metric_name = _p(params, f"MetricData.member.{i}.MetricName")+ mn = _p(params, f"MetricData.member.{i}.MetricName")value = float(_p(params, f"MetricData.member.{i}.Value") or "0")unit = _p(params, f"MetricData.member.{i}.Unit") or "None"ts_str = _p(params, f"MetricData.member.{i}.Timestamp")- ts = float(ts_str) if ts_str else time.time()+ ts = _parse_ts(ts_str) if ts_str else time.time()dims = {}j = 1while _p(params, f"MetricData.member.{i}.Dimensions.member.{j}.Name"):dims[_p(params, f"MetricData.member.{i}.Dimensions.member.{j}.Name")] = \_p(params, f"MetricData.member.{i}.Dimensions.member.{j}.Value")j += 1- _metrics[(namespace, metric_name, _dims_key(dims))].append(- {"Timestamp": ts, "Value": value, "Unit": unit, "Dimensions": dims}- )+ _metrics[(namespace, mn, _dims_key(dims))].append({+ "Timestamp": ts, "Value": value, "Unit": unit, "Dimensions": dims,+ })i += 1+ _evaluate_all_alarms()+if is_cbor:return _cbor_ok({})if is_json:@@ -120,13 +320,19 @@ def _put_metric_data(params, cbor_data, is_cbor, is_json=False):return _xml(200, "PutMetricDataResponse", "")+# ---------------------------------------------------------------------------+# ListMetrics+# ---------------------------------------------------------------------------+def _list_metrics(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:namespace = cbor_data.get("Namespace")metric_name = cbor_data.get("MetricName")+ req_dims = cbor_data.get("Dimensions")else:namespace = _p(params, "Namespace")metric_name = _p(params, "MetricName")+ req_dims = Noneseen = set()result = []@@ -139,7 +345,18 @@ def _list_metrics(params, cbor_data, is_cbor, is_json=False):if key in seen:continueseen.add(key)- dims = [{"Name": k, "Value": v} for k, v in (points[0].get("Dimensions", {}) if points else {}).items()]+ dims = [{"Name": k, "Value": v}+ for k, v in (points[0].get("Dimensions", {}) if points else {}).items()]++ if req_dims:+ match = all(+ any(d["Name"] == rd.get("Name") and (not rd.get("Value") or d["Value"] == rd["Value"])+ for d in dims)+ for rd in req_dims+ )+ if not match:+ continue+result.append({"Namespace": ns, "MetricName": mn, "Dimensions": dims})if is_cbor:@@ -149,58 +366,160 @@ def _list_metrics(params, cbor_data, is_cbor, is_json=False):members = ""for item in result:- dims_xml = "".join(f"<member><Name>{d['Name']}</Name><Value>{d['Value']}</Value></member>"- for d in item["Dimensions"])- members += f"<member><Namespace>{item['Namespace']}</Namespace><MetricName>{item['MetricName']}</MetricName><Dimensions>{dims_xml}</Dimensions></member>"- return _xml(200, "ListMetricsResponse", f"<ListMetricsResult><Metrics>{members}</Metrics></ListMetricsResult>")+ dims_xml = "".join(+ f"<member><Name>{d['Name']}</Name><Value>{d['Value']}</Value></member>"+ for d in item["Dimensions"])+ members += (f"<member><Namespace>{item['Namespace']}</Namespace>"+ f"<MetricName>{item['MetricName']}</MetricName>"+ f"<Dimensions>{dims_xml}</Dimensions></member>")+ return _xml(200, "ListMetricsResponse",+ f"<ListMetricsResult><Metrics>{members}</Metrics></ListMetricsResult>")+# ---------------------------------------------------------------------------+# GetMetricStatistics — with time-range filtering + period aggregation+# ---------------------------------------------------------------------------+def _get_metric_statistics(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:namespace = cbor_data.get("Namespace")metric_name = cbor_data.get("MetricName")period = int(cbor_data.get("Period") or 60)+ start_time = _parse_ts(cbor_data.get("StartTime"))+ end_time = _parse_ts(cbor_data.get("EndTime"))+ req_stats = cbor_data.get("Statistics", [])else:namespace = _p(params, "Namespace")metric_name = _p(params, "MetricName")period = int(_p(params, "Period") or 60)+ start_time = _parse_ts(_p(params, "StartTime"))+ end_time = _parse_ts(_p(params, "EndTime"))+ req_stats = []+ si = 1+ while _p(params, f"Statistics.member.{si}"):+ req_stats.append(_p(params, f"Statistics.member.{si}"))+ si += 1++ if not req_stats:+ req_stats = ["SampleCount", "Sum", "Average", "Minimum", "Maximum"]all_points = []- for (ns, mn, dk), points in _metrics.items():+ for (ns, mn, _), pts in _metrics.items():if ns == namespace and mn == metric_name:- all_points.extend(points)+ all_points.extend(pts)- if is_cbor or is_json:- datapoints = []- buckets = defaultdict(list)- for pt in all_points:- buckets[int(pt["Timestamp"] // period) * period].append(pt["Value"])- for ts, values in sorted(buckets.items()):- datapoints.append({- "Timestamp": ts, "SampleCount": len(values),- "Sum": sum(values), "Average": sum(values) / len(values),- "Minimum": min(values), "Maximum": max(values),- "Unit": all_points[0]["Unit"] if all_points else "None",- })- if is_cbor:- return _cbor_ok({"Datapoints": datapoints, "Label": metric_name})- return _json_ok({"Datapoints": datapoints, "Label": metric_name})+ if start_time is not None:+ all_points = [p for p in all_points if p["Timestamp"] >= start_time]+ if end_time is not None:+ all_points = [p for p in all_points if p["Timestamp"] < end_time]- if not all_points:- return _xml(200, "GetMetricStatisticsResponse",- f"<GetMetricStatisticsResult><Datapoints/><Label>{metric_name}</Label></GetMetricStatisticsResult>")buckets = defaultdict(list)for pt in all_points:- buckets[int(pt["Timestamp"] // period) * period].append(pt["Value"])+ bucket_ts = int(pt["Timestamp"] // period) * period+ buckets[bucket_ts].append(pt["Value"])++ datapoints = []+ for ts in sorted(buckets):+ vals = buckets[ts]+ stats = _calc_stats(vals)+ dp = {"Timestamp": _ts_iso(ts), "Unit": all_points[0]["Unit"] if all_points else "None"}+ for s in req_stats:+ if s in stats:+ dp[s] = stats[s]+ datapoints.append(dp)++ if is_cbor:+ return _cbor_ok({"Datapoints": datapoints, "Label": metric_name})+ if is_json:+ return _json_ok({"Datapoints": datapoints, "Label": metric_name})++ if not datapoints:+ return _xml(200, "GetMetricStatisticsResponse",+ f"<GetMetricStatisticsResult><Datapoints/><Label>{metric_name}</Label>"+ f"</GetMetricStatisticsResult>")dps = ""- for ts, values in sorted(buckets.items()):- dps += (f"<member><Timestamp>{ts}</Timestamp><SampleCount>{len(values)}</SampleCount>"- f"<Sum>{sum(values)}</Sum><Average>{sum(values)/len(values):.6f}</Average>"- f"<Minimum>{min(values)}</Minimum><Maximum>{max(values)}</Maximum>"- f"<Unit>{all_points[0]['Unit']}</Unit></member>")+ for dp in datapoints:+ inner = f"<Timestamp>{dp['Timestamp']}</Timestamp>"+ for k, v in dp.items():+ if k not in ("Timestamp",):+ inner += f"<{k}>{v}</{k}>"+ dps += f"<member>{inner}</member>"return _xml(200, "GetMetricStatisticsResponse",- f"<GetMetricStatisticsResult><Datapoints>{dps}</Datapoints><Label>{metric_name}</Label></GetMetricStatisticsResult>")+ f"<GetMetricStatisticsResult><Datapoints>{dps}</Datapoints>"+ f"<Label>{metric_name}</Label></GetMetricStatisticsResult>")+++# ---------------------------------------------------------------------------+# GetMetricData — modern multi-query API+# ---------------------------------------------------------------------------++def _get_metric_data(params, cbor_data, is_cbor, is_json=False):+ if not (is_cbor or is_json):+ return _error("InvalidParameterValue",+ "GetMetricData is only supported via JSON/CBOR", 400, False)++ queries = cbor_data.get("MetricDataQueries", [])+ start_time = _parse_ts(cbor_data.get("StartTime"))+ end_time = _parse_ts(cbor_data.get("EndTime"))++ results = []+ for q in queries:+ qid = q.get("Id", "")+ label = q.get("Label", qid)+ return_data = q.get("ReturnData", True)++ if q.get("Expression"):+ results.append({+ "Id": qid, "Label": label,+ "StatusCode": "InternalError",+ "Messages": [{"Code": "Unsupported", "Value": "Expressions not implemented"}],+ "Timestamps": [], "Values": [],+ })+ continue++ ms = q.get("MetricStat", {})+ metric = ms.get("Metric", {})+ ns = metric.get("Namespace", "")+ mn = metric.get("MetricName", "")+ period = int(ms.get("Period", 60))+ stat_name = ms.get("Stat", "Average")++ all_pts = []+ for (k_ns, k_mn, _), pts in _metrics.items():+ if k_ns == ns and k_mn == mn:+ all_pts.extend(pts)++ if start_time is not None:+ all_pts = [p for p in all_pts if p["Timestamp"] >= start_time]+ if end_time is not None:+ all_pts = [p for p in all_pts if p["Timestamp"] < end_time]+ buckets = defaultdict(list)+ for pt in all_pts:+ buckets[int(pt["Timestamp"] // period) * period].append(pt["Value"])++ timestamps = []+ values = []+ for ts in sorted(buckets):+ stats = _calc_stats(buckets[ts])+ timestamps.append(_ts_iso(ts))+ values.append(_stat_value(stats, stat_name))++ if return_data:+ results.append({+ "Id": qid, "Label": label,+ "Timestamps": timestamps, "Values": values,+ "StatusCode": "Complete",+ })++ if is_cbor:+ return _cbor_ok({"MetricDataResults": results})+ return _json_ok({"MetricDataResults": results})+++# ---------------------------------------------------------------------------+# Alarms+# ---------------------------------------------------------------------------def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:@@ -208,20 +527,49 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):alarm = {"AlarmName": name,"AlarmArn": f"arn:aws:cloudwatch:{REGION}:{ACCOUNT_ID}:alarm:{name}",- "AlarmDescription": cbor_data.get("AlarmDescription"),+ "AlarmDescription": cbor_data.get("AlarmDescription", ""),"MetricName": cbor_data.get("MetricName"),"Namespace": cbor_data.get("Namespace"),"Statistic": cbor_data.get("Statistic", "Average"),+ "ExtendedStatistic": cbor_data.get("ExtendedStatistic"),"Period": int(cbor_data.get("Period", 60)),"EvaluationPeriods": int(cbor_data.get("EvaluationPeriods", 1)),+ "DatapointsToAlarm": int(cbor_data.get("DatapointsToAlarm")+ or cbor_data.get("EvaluationPeriods", 1)),"Threshold": float(cbor_data.get("Threshold", 0)),"ComparisonOperator": cbor_data.get("ComparisonOperator"),- "StateValue": "OK",- "StateReason": "Threshold Crossed",+ "TreatMissingData": cbor_data.get("TreatMissingData", "missing"),+ "StateValue": _alarms[name]["StateValue"] if name in _alarms else "INSUFFICIENT_DATA",+ "StateReason": _alarms[name]["StateReason"] if name in _alarms else "Unchecked: Initial alarm creation",+ "StateUpdatedTimestamp": time.time(),"ActionsEnabled": cbor_data.get("ActionsEnabled", True),+ "AlarmActions": cbor_data.get("AlarmActions", []),+ "OKActions": cbor_data.get("OKActions", []),+ "InsufficientDataActions": cbor_data.get("InsufficientDataActions", []),+ "Dimensions": cbor_data.get("Dimensions", []),+ "Unit": cbor_data.get("Unit"),+ "AlarmConfigurationUpdatedTimestamp": time.time(),}else:name = _p(params, "AlarmName")+ dims = []+ di = 1+ while _p(params, f"Dimensions.member.{di}.Name"):+ dims.append({+ "Name": _p(params, f"Dimensions.member.{di}.Name"),+ "Value": _p(params, f"Dimensions.member.{di}.Value"),+ })+ di += 1+ alarm_actions = []+ ai = 1+ while _p(params, f"AlarmActions.member.{ai}"):+ alarm_actions.append(_p(params, f"AlarmActions.member.{ai}"))+ ai += 1+ ok_actions = []+ oi = 1+ while _p(params, f"OKActions.member.{oi}"):+ ok_actions.append(_p(params, f"OKActions.member.{oi}"))+ oi += 1alarm = {"AlarmName": name,"AlarmArn": f"arn:aws:cloudwatch:{REGION}:{ACCOUNT_ID}:alarm:{name}",@@ -229,15 +577,35 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):"MetricName": _p(params, "MetricName"),"Namespace": _p(params, "Namespace"),"Statistic": _p(params, "Statistic") or "Average",+ "ExtendedStatistic": _p(params, "ExtendedStatistic") or None,"Period": int(_p(params, "Period") or "60"),"EvaluationPeriods": int(_p(params, "EvaluationPeriods") or "1"),+ "DatapointsToAlarm": int(_p(params, "DatapointsToAlarm")+ or _p(params, "EvaluationPeriods") or "1"),"Threshold": float(_p(params, "Threshold") or "0"),"ComparisonOperator": _p(params, "ComparisonOperator"),- "StateValue": "OK",- "StateReason": "Threshold Crossed",+ "TreatMissingData": _p(params, "TreatMissingData") or "missing",+ "StateValue": _alarms[name]["StateValue"] if name in _alarms else "INSUFFICIENT_DATA",+ "StateReason": _alarms[name]["StateReason"] if name in _alarms else "Unchecked: Initial alarm creation",+ "StateUpdatedTimestamp": time.time(),"ActionsEnabled": _p(params, "ActionsEnabled") != "false",+ "AlarmActions": alarm_actions,+ "OKActions": ok_actions,+ "InsufficientDataActions": [],+ "Dimensions": dims,+ "Unit": _p(params, "Unit") or None,+ "AlarmConfigurationUpdatedTimestamp": time.time(),}++ is_new = name not in _alarms_alarms[name] = alarm++ if is_new:+ _record_history(name, "INSUFFICIENT_DATA", "INSUFFICIENT_DATA",+ "Unchecked: Initial alarm creation")++ _evaluate_alarm(alarm)+if is_cbor:return _cbor_ok({})if is_json:@@ -245,26 +613,104 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):return _xml(200, "PutMetricAlarmResponse", "")+def _put_composite_alarm(params, cbor_data, is_cbor, is_json=False):+ if not (is_cbor or is_json):+ return _error("InvalidParameterValue",+ "PutCompositeAlarm only supported via JSON/CBOR", 400, False)+ name = cbor_data.get("AlarmName", "")+ _composite_alarms[name] = {+ "AlarmName": name,+ "AlarmArn": f"arn:aws:cloudwatch:{REGION}:{ACCOUNT_ID}:alarm:{name}",+ "AlarmDescription": cbor_data.get("AlarmDescription", ""),+ "AlarmRule": cbor_data.get("AlarmRule", ""),+ "StateValue": "INSUFFICIENT_DATA",+ "StateReason": "Unchecked: Initial alarm creation",+ "StateUpdatedTimestamp": time.time(),+ "ActionsEnabled": cbor_data.get("ActionsEnabled", True),+ "AlarmActions": cbor_data.get("AlarmActions", []),+ "OKActions": cbor_data.get("OKActions", []),+ "InsufficientDataActions": cbor_data.get("InsufficientDataActions", []),+ "AlarmConfigurationUpdatedTimestamp": time.time(),+ }+ if is_cbor:+ return _cbor_ok({})+ return _json_ok({})+++# ---------------------------------------------------------------------------+# DescribeAlarms+# ---------------------------------------------------------------------------+def _describe_alarms(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:names = cbor_data.get("AlarmNames", [])prefix = cbor_data.get("AlarmNamePrefix")state = cbor_data.get("StateValue")+ alarm_types = cbor_data.get("AlarmTypes", ["MetricAlarm", "CompositeAlarm"])+ max_records = cbor_data.get("MaxRecords", 100)else:- names = [_p(params, f"AlarmNames.member.{i}") for i in range(1, 100)- if _p(params, f"AlarmNames.member.{i}")]+ names = [_p(params, f"AlarmNames.member.{i}")+ for i in range(1, 101) if _p(params, f"AlarmNames.member.{i}")]prefix = _p(params, "AlarmNamePrefix")state = _p(params, "StateValue")+ alarm_types = ["MetricAlarm", "CompositeAlarm"]+ max_records = int(_p(params, "MaxRecords") or "100")- result = []- for name, alarm in _alarms.items():- if names and name not in names:- continue- if prefix and not name.startswith(prefix):- continue- if state and alarm["StateValue"] != state:- continue- result.append(alarm)+ metric_alarms = []+ composite_results = []++ if "MetricAlarm" in alarm_types:+ for aname, alarm in _alarms.items():+ if names and aname not in names:+ continue+ if prefix and not aname.startswith(prefix):+ continue+ if state and alarm["StateValue"] != state:+ continue+ metric_alarms.append(alarm)++ if "CompositeAlarm" in alarm_types:+ for aname, alarm in _composite_alarms.items():+ if names and aname not in names:+ continue+ if prefix and not aname.startswith(prefix):+ continue+ if state and alarm["StateValue"] != state:+ continue+ composite_results.append(alarm)++ metric_alarms = metric_alarms[:max_records]++ if is_cbor:+ return _cbor_ok({"MetricAlarms": metric_alarms, "CompositeAlarms": composite_results})+ if is_json:+ return _json_ok({"MetricAlarms": metric_alarms, "CompositeAlarms": composite_results})++ members = "".join(+ f"<member><AlarmName>{a['AlarmName']}</AlarmName><AlarmArn>{a['AlarmArn']}</AlarmArn>"+ f"<StateValue>{a['StateValue']}</StateValue><MetricName>{a.get('MetricName','')}</MetricName>"+ f"<Namespace>{a.get('Namespace','')}</Namespace><Threshold>{a.get('Threshold','')}</Threshold>"+ f"<ComparisonOperator>{a.get('ComparisonOperator','')}</ComparisonOperator></member>"+ for a in metric_alarms+ )+ return _xml(200, "DescribeAlarmsResponse",+ f"<DescribeAlarmsResult><MetricAlarms>{members}</MetricAlarms></DescribeAlarmsResult>")+++# ---------------------------------------------------------------------------+# DescribeAlarmsForMetric+# ---------------------------------------------------------------------------++def _describe_alarms_for_metric(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ namespace = cbor_data.get("Namespace", "")+ metric_name = cbor_data.get("MetricName", "")+ else:+ namespace = _p(params, "Namespace")+ metric_name = _p(params, "MetricName")++ result = [a for a in _alarms.values()+ if a.get("Namespace") == namespace and a.get("MetricName") == metric_name]if is_cbor:return _cbor_ok({"MetricAlarms": result})@@ -273,24 +719,79 @@ def _describe_alarms(params, cbor_data, is_cbor, is_json=False):members = "".join(f"<member><AlarmName>{a['AlarmName']}</AlarmName><AlarmArn>{a['AlarmArn']}</AlarmArn>"- f"<StateValue>{a['StateValue']}</StateValue><MetricName>{a['MetricName']}</MetricName>"- f"<Namespace>{a['Namespace']}</Namespace><Threshold>{a['Threshold']}</Threshold>"- f"<ComparisonOperator>{a['ComparisonOperator']}</ComparisonOperator></member>"+ f"<StateValue>{a['StateValue']}</StateValue></member>"for a in result)- return _xml(200, "DescribeAlarmsResponse",- f"<DescribeAlarmsResult><MetricAlarms>{members}</MetricAlarms></DescribeAlarmsResult>")+ return _xml(200, "DescribeAlarmsForMetricResponse",+ f"<DescribeAlarmsForMetricResult><MetricAlarms>{members}</MetricAlarms>"+ f"</DescribeAlarmsForMetricResult>")+++# ---------------------------------------------------------------------------+# DescribeAlarmHistory+# ---------------------------------------------------------------------------++def _describe_alarm_history(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ alarm_name = cbor_data.get("AlarmName")+ history_type = cbor_data.get("HistoryItemType")+ start_date = _parse_ts(cbor_data.get("StartDate"))+ end_date = _parse_ts(cbor_data.get("EndDate"))+ max_records = int(cbor_data.get("MaxRecords", 100))+ else:+ alarm_name = _p(params, "AlarmName")+ history_type = _p(params, "HistoryItemType")+ start_date = _parse_ts(_p(params, "StartDate"))+ end_date = _parse_ts(_p(params, "EndDate"))+ max_records = int(_p(params, "MaxRecords") or "100")++ items = list(_alarm_history)+ if alarm_name:+ items = [h for h in items if h["AlarmName"] == alarm_name]+ if history_type:+ items = [h for h in items if h["HistoryItemType"] == history_type]+ if start_date is not None:+ items = [h for h in items if _parse_ts(h["Timestamp"]) >= start_date]+ if end_date is not None:+ items = [h for h in items if _parse_ts(h["Timestamp"]) <= end_date]+ items = items[:max_records]++ if is_cbor:+ return _cbor_ok({"AlarmHistoryItems": items})+ if is_json:+ return _json_ok({"AlarmHistoryItems": items})+ members = "".join(+ f"<member><AlarmName>{h['AlarmName']}</AlarmName>"+ f"<Timestamp>{h['Timestamp']}</Timestamp>"+ f"<HistoryItemType>{h['HistoryItemType']}</HistoryItemType>"+ f"<HistorySummary>{h['HistorySummary']}</HistorySummary></member>"+ for h in items+ )+ return _xml(200, "DescribeAlarmHistoryResponse",+ f"<DescribeAlarmHistoryResult><AlarmHistoryItems>{members}</AlarmHistoryItems>"+ f"</DescribeAlarmHistoryResult>")+++# ---------------------------------------------------------------------------+# DeleteAlarms / Enable / Disable+# ---------------------------------------------------------------------------def _delete_alarms(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:- for name in cbor_data.get("AlarmNames", []):- _alarms.pop(name, None)+ names = cbor_data.get("AlarmNames", [])else:+ names = []i = 1while _p(params, f"AlarmNames.member.{i}"):- _alarms.pop(_p(params, f"AlarmNames.member.{i}"), None)+ names.append(_p(params, f"AlarmNames.member.{i}"))i += 1++ for n in names:+ _alarms.pop(n, None)+ _composite_alarms.pop(n, None)+ _resource_tags.pop(f"arn:aws:cloudwatch:{REGION}:{ACCOUNT_ID}:alarm:{n}", None)+if is_cbor:return _cbor_ok({})if is_json:@@ -302,11 +803,13 @@ def _enable_alarm_actions(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:names = cbor_data.get("AlarmNames", [])else:- names = [_p(params, f"AlarmNames.member.{i}") for i in range(1, 100)- if _p(params, f"AlarmNames.member.{i}")]- for name in names:- if name in _alarms:- _alarms[name]["ActionsEnabled"] = True+ names = [_p(params, f"AlarmNames.member.{i}")+ for i in range(1, 101) if _p(params, f"AlarmNames.member.{i}")]+ for n in names:+ if n in _alarms:+ _alarms[n]["ActionsEnabled"] = True+ if n in _composite_alarms:+ _composite_alarms[n]["ActionsEnabled"] = Trueif is_cbor:return _cbor_ok({})if is_json:@@ -318,11 +821,13 @@ def _disable_alarm_actions(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:names = cbor_data.get("AlarmNames", [])else:- names = [_p(params, f"AlarmNames.member.{i}") for i in range(1, 100)- if _p(params, f"AlarmNames.member.{i}")]- for name in names:- if name in _alarms:- _alarms[name]["ActionsEnabled"] = False+ names = [_p(params, f"AlarmNames.member.{i}")+ for i in range(1, 101) if _p(params, f"AlarmNames.member.{i}")]+ for n in names:+ if n in _alarms:+ _alarms[n]["ActionsEnabled"] = False+ if n in _composite_alarms:+ _composite_alarms[n]["ActionsEnabled"] = Falseif is_cbor:return _cbor_ok({})if is_json:@@ -330,18 +835,36 @@ def _disable_alarm_actions(params, cbor_data, is_cbor, is_json=False):return _xml(200, "DisableAlarmActionsResponse", "")+# ---------------------------------------------------------------------------+# SetAlarmState — with history recording+# ---------------------------------------------------------------------------+def _set_alarm_state(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:name = cbor_data.get("AlarmName", "")- state = cbor_data.get("StateValue", "")+ new_state = cbor_data.get("StateValue", "")reason = cbor_data.get("StateReason", "")+ reason_data = cbor_data.get("StateReasonData", "")else:name = _p(params, "AlarmName")- state = _p(params, "StateValue")+ new_state = _p(params, "StateValue")reason = _p(params, "StateReason")- if name in _alarms:- _alarms[name]["StateValue"] = state- _alarms[name]["StateReason"] = reason+ reason_data = _p(params, "StateReasonData")++ alarm = _alarms.get(name) or _composite_alarms.get(name)+ if not alarm:+ return _error("ResourceNotFound", f"Alarm {name} not found", 404, is_cbor or is_json)++ old_state = alarm["StateValue"]+ alarm["StateValue"] = new_state+ alarm["StateReason"] = reason+ if reason_data:+ alarm["StateReasonData"] = reason_data+ alarm["StateUpdatedTimestamp"] = time.time()++ if old_state != new_state:+ _record_history(name, old_state, new_state, reason)+if is_cbor:return _cbor_ok({})if is_json:@@ -349,7 +872,198 @@ def _set_alarm_state(params, cbor_data, is_cbor, is_json=False):return _xml(200, "SetAlarmStateResponse", "")-# --- Helpers ---+# ---------------------------------------------------------------------------+# TagResource / UntagResource / ListTagsForResource+# ---------------------------------------------------------------------------++def _tag_resource(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ arn = cbor_data.get("ResourceARN", "")+ tags = cbor_data.get("Tags", [])+ else:+ arn = _p(params, "ResourceARN")+ tags = []+ i = 1+ while _p(params, f"Tags.member.{i}.Key"):+ tags.append({+ "Key": _p(params, f"Tags.member.{i}.Key"),+ "Value": _p(params, f"Tags.member.{i}.Value"),+ })+ i += 1++ if arn not in _resource_tags:+ _resource_tags[arn] = {}+ for t in tags:+ _resource_tags[arn][t["Key"]] = t.get("Value", "")++ if is_cbor:+ return _cbor_ok({})+ if is_json:+ return _json_ok({})+ return _xml(200, "TagResourceResponse", "")+++def _untag_resource(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ arn = cbor_data.get("ResourceARN", "")+ keys = cbor_data.get("TagKeys", [])+ else:+ arn = _p(params, "ResourceARN")+ keys = []+ i = 1+ while _p(params, f"TagKeys.member.{i}"):+ keys.append(_p(params, f"TagKeys.member.{i}"))+ i += 1++ tag_map = _resource_tags.get(arn, {})+ for k in keys:+ tag_map.pop(k, None)++ if is_cbor:+ return _cbor_ok({})+ if is_json:+ return _json_ok({})+ return _xml(200, "UntagResourceResponse", "")+++def _list_tags_for_resource(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ arn = cbor_data.get("ResourceARN", "")+ else:+ arn = _p(params, "ResourceARN")++ tags = [{"Key": k, "Value": v} for k, v in _resource_tags.get(arn, {}).items()]++ if is_cbor:+ return _cbor_ok({"Tags": tags})+ if is_json:+ return _json_ok({"Tags": tags})++ members = "".join(+ f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>" for t in tags)+ return _xml(200, "ListTagsForResourceResponse",+ f"<ListTagsForResourceResult><Tags>{members}</Tags></ListTagsForResourceResult>")+++# ---------------------------------------------------------------------------+# Dashboards+# ---------------------------------------------------------------------------++def _put_dashboard(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ name = cbor_data.get("DashboardName", "")+ body = cbor_data.get("DashboardBody", "")+ else:+ name = _p(params, "DashboardName")+ body = _p(params, "DashboardBody")++ if not name:+ return _error("InvalidParameterValue", "DashboardName is required", 400, is_cbor or is_json)++ _dashboards[name] = {+ "DashboardName": name,+ "DashboardBody": body,+ "DashboardArn": f"arn:aws:cloudwatch::{ACCOUNT_ID}:dashboard/{name}",+ "LastModified": time.time(),+ "Size": len(body),+ }++ if is_cbor:+ return _cbor_ok({"DashboardValidationMessages": []})+ if is_json:+ return _json_ok({"DashboardValidationMessages": []})+ return _xml(200, "PutDashboardResponse",+ "<PutDashboardResult><DashboardValidationMessages/></PutDashboardResult>")+++def _get_dashboard(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ name = cbor_data.get("DashboardName", "")+ else:+ name = _p(params, "DashboardName")++ dash = _dashboards.get(name)+ if not dash:+ return _error("ResourceNotFound", f"Dashboard {name} does not exist", 404, is_cbor or is_json)++ if is_cbor:+ return _cbor_ok({+ "DashboardArn": dash["DashboardArn"],+ "DashboardBody": dash["DashboardBody"],+ "DashboardName": dash["DashboardName"],+ })+ if is_json:+ return _json_ok({+ "DashboardArn": dash["DashboardArn"],+ "DashboardBody": dash["DashboardBody"],+ "DashboardName": dash["DashboardName"],+ })+ return _xml(200, "GetDashboardResponse",+ f"<GetDashboardResult>"+ f"<DashboardArn>{dash['DashboardArn']}</DashboardArn>"+ f"<DashboardBody>{dash['DashboardBody']}</DashboardBody>"+ f"<DashboardName>{dash['DashboardName']}</DashboardName>"+ f"</GetDashboardResult>")+++def _delete_dashboards(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ names = cbor_data.get("DashboardNames", [])+ else:+ names = []+ i = 1+ while _p(params, f"DashboardNames.member.{i}"):+ names.append(_p(params, f"DashboardNames.member.{i}"))+ i += 1++ for n in names:+ _dashboards.pop(n, None)++ if is_cbor:+ return _cbor_ok({})+ if is_json:+ return _json_ok({})+ return _xml(200, "DeleteDashboardsResponse", "")+++def _list_dashboards(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ prefix = cbor_data.get("DashboardNamePrefix", "")+ else:+ prefix = _p(params, "DashboardNamePrefix")++ entries = []+ for name in sorted(_dashboards):+ if prefix and not name.startswith(prefix):+ continue+ dash = _dashboards[name]+ entries.append({+ "DashboardName": dash["DashboardName"],+ "DashboardArn": dash["DashboardArn"],+ "Size": dash["Size"],+ "LastModified": _ts_iso(dash["LastModified"]),+ })++ if is_cbor:+ return _cbor_ok({"DashboardEntries": entries})+ if is_json:+ return _json_ok({"DashboardEntries": entries})++ members = ""+ for e in entries:+ members += (f"<member>"+ f"<DashboardName>{e['DashboardName']}</DashboardName>"+ f"<DashboardArn>{e['DashboardArn']}</DashboardArn>"+ f"<Size>{e['Size']}</Size>"+ f"<LastModified>{e['LastModified']}</LastModified>"+ f"</member>")+ return _xml(200, "ListDashboardsResponse",+ f"<ListDashboardsResult><DashboardEntries>{members}</DashboardEntries></ListDashboardsResult>")+++# ---------------------------------------------------------------------------+# Protocol / encoding helpers+# ---------------------------------------------------------------------------def _dims_key(dims: dict) -> str:return "|".join(f"{k}={v}" for k, v in sorted(dims.items()))@@ -382,17 +1096,26 @@ def _xml(status, root_tag, inner):return status, {"Content-Type": "application/xml"}, body-def _error(code, message, status, is_cbor=False):- if is_cbor:+def _error(code, message, status, use_json=False):+ if use_json:try:import cbor2body = cbor2.dumps({"__type": code, "message": message})+ return status, {"Content-Type": "application/cbor"}, bodyexcept Exception:- body = json.dumps({"__type": code, "message": message}).encode()- return status, {"Content-Type": "application/cbor"}, body+ pass+ return status, {"Content-Type": "application/json"}, \+ json.dumps({"__type": code, "message": message}).encode()body = (f'<?xml version="1.0" encoding="UTF-8"?>\n'f'<ErrorResponse xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">\n'f' <Error><Code>{code}</Code><Message>{message}</Message></Error>\n'f' <RequestId>{new_uuid()}</RequestId>\n'f'</ErrorResponse>').encode("utf-8")return status, {"Content-Type": "application/xml"}, body+++def reset():+ _alarms.clear()+ _composite_alarms.clear()+ _alarm_history.clear()+ _resource_tags.clear()diff --git a/services/cloudwatch_logs.py b/services/cloudwatch_logs.pyindex 4f2a50b0..71cf5d2b 100644--- a/services/cloudwatch_logs.py+++ b/services/cloudwatch_logs.py@@ -3,19 +3,82 @@ CloudWatch Logs Service Emulator.JSON-based API via X-Amz-Target (Logs_20140328).Supports: CreateLogGroup, DeleteLogGroup, DescribeLogGroups,CreateLogStream, DeleteLogStream, DescribeLogStreams,- PutLogEvents, GetLogEvents, FilterLogEvents.+ PutLogEvents, GetLogEvents, FilterLogEvents,+ PutRetentionPolicy, DeleteRetentionPolicy,+ PutSubscriptionFilter, DeleteSubscriptionFilter, DescribeSubscriptionFilters,+ TagLogGroup, UntagLogGroup, ListTagsLogGroup,+ TagResource, UntagResource, ListTagsForResource,+ PutDestination, DeleteDestination, DescribeDestinations,+ PutDestinationPolicy,+ PutMetricFilter, DeleteMetricFilter, DescribeMetricFilters,+ StartQuery, GetQueryResults, StopQuery."""import jsonimport timeimport logging+import base64from core.responses import json_response, error_response_json, new_uuidlogger = logging.getLogger("logs")-_log_groups: dict = {} # group_name -> {arn, streams: {stream_name: {events: [...], upload_seq}}}+ACCOUNT_ID = "000000000000"+REGION = "us-east-1"+_log_groups: dict = {}+# group_name -> {+# arn, creationTime, retentionInDays (int|None), tags: {str: str},+# subscriptionFilters: {filterName: {filterName, logGroupName, filterPattern,+# destinationArn, roleArn, distribution, creationTime}},+# streams: {stream_name: {events: [{timestamp, message, ingestionTime}],+# uploadSequenceToken, creationTime,+# firstEventTimestamp, lastEventTimestamp, lastIngestionTime}},+# }++_destinations: dict = {}+# dest_name -> {destinationName, targetArn, roleArn, accessPolicy, arn, creationTime}++_metric_filters: dict = {}+# (log_group_name, filter_name) -> {filterName, logGroupName, filterPattern, metricTransformations, creationTime}++_queries: dict = {}+# query_id -> {queryId, logGroupName, startTime, endTime, queryString, status}+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _make_group_arn(name):+ return f"arn:aws:logs:{REGION}:{ACCOUNT_ID}:log-group:{name}:*"+++def _resolve_group_by_arn(arn):+ """Return the group name whose ARN matches, or None."""+ for name, g in _log_groups.items():+ if g["arn"] == arn:+ return name+ return None+++def _decode_token(token):+ """Decode a pagination token to an integer offset."""+ if not token:+ return 0+ try:+ return int(base64.b64decode(token))+ except Exception:+ return 0+++def _encode_token(offset):+ return base64.b64encode(str(offset).encode()).decode()+++# ---------------------------------------------------------------------------+# Router+# ---------------------------------------------------------------------------async def handle_request(method, path, headers, body, query_params):target = headers.get("x-amz-target", "")@@ -36,21 +99,54 @@ async def handle_request(method, path, headers, body, query_params):"PutLogEvents": _put_log_events,"GetLogEvents": _get_log_events,"FilterLogEvents": _filter_log_events,+ "PutRetentionPolicy": _put_retention_policy,+ "DeleteRetentionPolicy": _delete_retention_policy,+ "PutSubscriptionFilter": _put_subscription_filter,+ "DeleteSubscriptionFilter": _delete_subscription_filter,+ "DescribeSubscriptionFilters": _describe_subscription_filters,+ "TagLogGroup": _tag_log_group,+ "UntagLogGroup": _untag_log_group,+ "ListTagsLogGroup": _list_tags_log_group,+ "TagResource": _tag_resource,+ "UntagResource": _untag_resource,+ "ListTagsForResource": _list_tags_for_resource,+ "PutDestination": _put_destination,+ "DeleteDestination": _delete_destination,+ "DescribeDestinations": _describe_destinations,+ "PutDestinationPolicy": _put_destination_policy,+ "PutMetricFilter": _put_metric_filter,+ "DeleteMetricFilter": _delete_metric_filter,+ "DescribeMetricFilters": _describe_metric_filters,+ "StartQuery": _start_query,+ "GetQueryResults": _get_query_results,+ "StopQuery": _stop_query,}handler = handlers.get(action)if not handler:- return error_response_json("InvalidOperationException", f"Unknown: {action}", 400)+ return error_response_json("InvalidOperationException", f"Unknown action: {action}", 400)return handler(data)+# ---------------------------------------------------------------------------+# Log groups+# ---------------------------------------------------------------------------+def _create_log_group(data):name = data.get("logGroupName")+ if not name:+ return error_response_json("InvalidParameterException", "logGroupName is required.", 400)if name in _log_groups:- return error_response_json("ResourceAlreadyExistsException", f"Log group {name} already exists", 400)+ return error_response_json(+ "ResourceAlreadyExistsException",+ f"The specified log group already exists: {name}", 400,+ )_log_groups[name] = {- "arn": f"arn:aws:logs:us-east-1:000000000000:log-group:{name}",+ "arn": _make_group_arn(name),"creationTime": int(time.time() * 1000),+ "retentionInDays": None,+ "tags": dict(data.get("tags", {})),+ "subscriptionFilters": {},"streams": {},}return json_response({})@@ -58,55 +154,166 @@ def _create_log_group(data):def _delete_log_group(data):name = data.get("logGroupName")- _log_groups.pop(name, None)+ if name not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {name}", 400,+ )+ del _log_groups[name]return json_response({})def _describe_log_groups(data):- prefix = data.get("logGroupNamePrefix", "")- groups = []- for name, g in _log_groups.items():- if name.startswith(prefix):- groups.append({- "logGroupName": name,- "arn": g["arn"],- "creationTime": g["creationTime"],- "storedBytes": 0,- })- return json_response({"logGroups": groups})+ prefix = data.get("logGroupNamePrefix")+ pattern = data.get("logGroupNamePattern")+ limit = min(data.get("limit", 50), 50)+ token = data.get("nextToken")++ if prefix and pattern:+ return error_response_json(+ "InvalidParameterException",+ "logGroupNamePrefix and logGroupNamePattern are mutually exclusive.", 400,+ )++ names = sorted(_log_groups.keys())+ if prefix:+ names = [n for n in names if n.startswith(prefix)]+ elif pattern:+ pat = pattern.lower()+ names = [n for n in names if pat in n.lower()]++ start = _decode_token(token)+ page = names[start:start + limit]+ groups = []+ for n in page:+ g = _log_groups[n]+ entry = {+ "logGroupName": n,+ "arn": g["arn"],+ "creationTime": g["creationTime"],+ "storedBytes": sum(+ sum(len(e.get("message", "")) for e in s["events"])+ for s in g["streams"].values()+ ),+ "metricFilterCount": sum(1 for k in _metric_filters if k[0] == n),+ }+ if g.get("retentionInDays") is not None:+ entry["retentionInDays"] = g["retentionInDays"]+ groups.append(entry)++ resp: dict = {"logGroups": groups}+ end = start + limit+ if end < len(names):+ resp["nextToken"] = _encode_token(end)+ return json_response(resp)+++# ---------------------------------------------------------------------------+# Log streams+# ---------------------------------------------------------------------------def _create_log_stream(data):group = data.get("logGroupName")stream = data.get("logStreamName")+ if not group or not stream:+ return error_response_json(+ "InvalidParameterException", "logGroupName and logStreamName are required.", 400,+ )if group not in _log_groups:- return error_response_json("ResourceNotFoundException", f"Log group {group} not found", 400)- _log_groups[group]["streams"][stream] = {"events": [], "uploadSequenceToken": "1"}+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )+ if stream in _log_groups[group]["streams"]:+ return error_response_json(+ "ResourceAlreadyExistsException",+ f"The specified log stream already exists: {stream}", 400,+ )+ _log_groups[group]["streams"][stream] = {+ "events": [],+ "uploadSequenceToken": "1",+ "creationTime": int(time.time() * 1000),+ "firstEventTimestamp": None,+ "lastEventTimestamp": None,+ "lastIngestionTime": None,+ }return json_response({})def _delete_log_stream(data):group = data.get("logGroupName")stream = data.get("logStreamName")- if group in _log_groups:- _log_groups[group]["streams"].pop(stream, None)+ if group not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )+ if stream not in _log_groups[group]["streams"]:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log stream does not exist: {stream}", 400,+ )+ del _log_groups[group]["streams"][stream]return json_response({})def _describe_log_streams(data):group = data.get("logGroupName")if group not in _log_groups:- return error_response_json("ResourceNotFoundException", f"Log group {group} not found", 400)+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )++ prefix = data.get("logStreamNamePrefix", "")+ order = data.get("orderBy", "LogStreamName")+ descending = data.get("descending", False)+ limit = min(data.get("limit", 50), 50)+ token = data.get("nextToken")++ all_streams = _log_groups[group]["streams"]+ names = sorted(all_streams.keys())++ if prefix:+ names = [n for n in names if n.startswith(prefix)]++ if order == "LastEventTime":+ names.sort(key=lambda n: all_streams[n].get("lastEventTimestamp") or 0, reverse=descending)+ elif descending:+ names.reverse()++ start = _decode_token(token)+ page = names[start:start + limit]+streams = []- for name, s in _log_groups[group]["streams"].items():- streams.append({- "logStreamName": name,- "creationTime": int(time.time() * 1000),+ for n in page:+ s = all_streams[n]+ entry = {+ "logStreamName": n,+ "creationTime": s["creationTime"],"storedBytes": sum(len(e.get("message", "")) for e in s["events"]),"uploadSequenceToken": s["uploadSequenceToken"],- })- return json_response({"logStreams": streams})-+ "arn": f"arn:aws:logs:{REGION}:{ACCOUNT_ID}:log-group:{group}:log-stream:{n}",+ }+ if s.get("firstEventTimestamp") is not None:+ entry["firstEventTimestamp"] = s["firstEventTimestamp"]+ if s.get("lastEventTimestamp") is not None:+ entry["lastEventTimestamp"] = s["lastEventTimestamp"]+ if s.get("lastIngestionTime") is not None:+ entry["lastIngestionTime"] = s["lastIngestionTime"]+ streams.append(entry)++ resp: dict = {"logStreams": streams}+ end = start + limit+ if end < len(names):+ resp["nextToken"] = _encode_token(end)+ return json_response(resp)+++# ---------------------------------------------------------------------------+# Log events+# ---------------------------------------------------------------------------def _put_log_events(data):group = data.get("logGroupName")@@ -114,13 +321,29 @@ def _put_log_events(data):events = data.get("logEvents", [])if group not in _log_groups:- _log_groups[group] = {"arn": "", "creationTime": int(time.time() * 1000), "streams": {}}+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )if stream not in _log_groups[group]["streams"]:- _log_groups[group]["streams"][stream] = {"events": [], "uploadSequenceToken": "1"}+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log stream does not exist: {stream}", 400,+ )s = _log_groups[group]["streams"][stream]+ now_ms = int(time.time() * 1000)+for e in events:- s["events"].append({"timestamp": e.get("timestamp", int(time.time() * 1000)), "message": e.get("message", ""), "ingestionTime": int(time.time() * 1000)})+ ts = e.get("timestamp", now_ms)+ msg = e.get("message", "")+ s["events"].append({"timestamp": ts, "message": msg, "ingestionTime": now_ms})++ if s["firstEventTimestamp"] is None or ts < s["firstEventTimestamp"]:+ s["firstEventTimestamp"] = ts+ if s["lastEventTimestamp"] is None or ts > s["lastEventTimestamp"]:+ s["lastEventTimestamp"] = ts+ s["lastIngestionTime"] = now_mstoken = str(int(s["uploadSequenceToken"]) + 1)s["uploadSequenceToken"] = token@@ -130,15 +353,38 @@ def _put_log_events(data):def _get_log_events(data):group = data.get("logGroupName")stream = data.get("logStreamName")- limit = data.get("limit", 10000)+ limit = min(data.get("limit", 10000), 10000)+ start_from_head = data.get("startFromHead", False)+ start_time = data.get("startTime")+ end_time = data.get("endTime")++ if group not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )+ if stream not in _log_groups[group]["streams"]:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log stream does not exist: {stream}", 400,+ )- if group not in _log_groups or stream not in _log_groups[group]["streams"]:- return json_response({"events": [], "nextForwardToken": "f/0", "nextBackwardToken": "b/0"})+ all_events = _log_groups[group]["streams"][stream]["events"]++ filtered = all_events+ if start_time is not None:+ filtered = [e for e in filtered if e["timestamp"] >= start_time]+ if end_time is not None:+ filtered = [e for e in filtered if e["timestamp"] <= end_time]++ if start_from_head:+ page = filtered[:limit]+ else:+ page = filtered[-limit:]- events = _log_groups[group]["streams"][stream]["events"][-limit:]return json_response({- "events": events,- "nextForwardToken": f"f/{len(events)}",+ "events": page,+ "nextForwardToken": f"f/{len(all_events)}","nextBackwardToken": "b/0",})@@ -146,19 +392,406 @@ def _get_log_events(data):def _filter_log_events(data):group = data.get("logGroupName")pattern = data.get("filterPattern", "").lower()- limit = data.get("limit", 10000)+ limit = min(data.get("limit", 10000), 10000)+ start_time = data.get("startTime")+ end_time = data.get("endTime")+ stream_names = data.get("logStreamNames")if group not in _log_groups:- return json_response({"events": [], "searchedLogStreams": []})+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )events = []searched = []- for stream_name, s in _log_groups[group]["streams"].items():- searched.append({"logStreamName": stream_name, "searchedCompletely": True})- for e in s["events"]:- if not pattern or pattern in e.get("message", "").lower():- events.append({**e, "logStreamName": stream_name})- if len(events) >= limit:- break-- return json_response({"events": events, "searchedLogStreams": searched})+ streams = _log_groups[group]["streams"]+ target_streams = stream_names if stream_names else list(streams.keys())++ for sn in target_streams:+ if sn not in streams:+ continue+ searched.append({"logStreamName": sn, "searchedCompletely": True})+ for e in streams[sn]["events"]:+ ts = e["timestamp"]+ if start_time is not None and ts < start_time:+ continue+ if end_time is not None and ts > end_time:+ continue+ if pattern and pattern not in e.get("message", "").lower():+ continue+ events.append({**e, "logStreamName": sn})+ if len(events) >= limit:+ break++ events.sort(key=lambda ev: ev["timestamp"])+ return json_response({"events": events[:limit], "searchedLogStreams": searched})+++# ---------------------------------------------------------------------------+# Retention+# ---------------------------------------------------------------------------++_VALID_RETENTION_DAYS = frozenset({+ 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180,+ 365, 400, 545, 731, 1096, 1827, 2192, 2557, 2922, 3288, 3653,+})+++def _put_retention_policy(data):+ group = data.get("logGroupName")+ days = data.get("retentionInDays")+ if group not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )+ if days not in _VALID_RETENTION_DAYS:+ return error_response_json(+ "InvalidParameterException",+ f"Invalid retentionInDays value: {days}.", 400,+ )+ _log_groups[group]["retentionInDays"] = days+ return json_response({})+++def _delete_retention_policy(data):+ group = data.get("logGroupName")+ if group not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )+ _log_groups[group]["retentionInDays"] = None+ return json_response({})+++# ---------------------------------------------------------------------------+# Subscription filters+# ---------------------------------------------------------------------------++def _put_subscription_filter(data):+ group = data.get("logGroupName")+ filter_name = data.get("filterName")+ if not group or not filter_name:+ return error_response_json(+ "InvalidParameterException",+ "logGroupName and filterName are required.", 400,+ )+ if group not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )+ _log_groups[group]["subscriptionFilters"][filter_name] = {+ "filterName": filter_name,+ "logGroupName": group,+ "filterPattern": data.get("filterPattern", ""),+ "destinationArn": data.get("destinationArn", ""),+ "roleArn": data.get("roleArn", ""),+ "distribution": data.get("distribution", "ByLogStream"),+ "creationTime": int(time.time() * 1000),+ }+ return json_response({})+++def _delete_subscription_filter(data):+ group = data.get("logGroupName")+ filter_name = data.get("filterName")+ if group not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )+ if filter_name not in _log_groups[group].get("subscriptionFilters", {}):+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified subscription filter does not exist: {filter_name}", 400,+ )+ del _log_groups[group]["subscriptionFilters"][filter_name]+ return json_response({})+++def _describe_subscription_filters(data):+ group = data.get("logGroupName")+ if group not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )+ prefix = data.get("filterNamePrefix", "")+ limit = min(data.get("limit", 50), 50)+ token = data.get("nextToken")++ all_filters = sorted(+ _log_groups[group]["subscriptionFilters"].values(),+ key=lambda f: f["filterName"],+ )+ if prefix:+ all_filters = [f for f in all_filters if f["filterName"].startswith(prefix)]++ start = _decode_token(token)+ page = all_filters[start:start + limit]++ resp: dict = {"subscriptionFilters": page}+ end = start + limit+ if end < len(all_filters):+ resp["nextToken"] = _encode_token(end)+ return json_response(resp)+++# ---------------------------------------------------------------------------+# Tags – legacy log-group-name APIs+# ---------------------------------------------------------------------------++def _tag_log_group(data):+ group = data.get("logGroupName")+ if group not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )+ _log_groups[group]["tags"].update(data.get("tags", {}))+ return json_response({})+++def _untag_log_group(data):+ group = data.get("logGroupName")+ if group not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )+ for key in data.get("tags", []):+ _log_groups[group]["tags"].pop(key, None)+ return json_response({})+++def _list_tags_log_group(data):+ group = data.get("logGroupName")+ if group not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )+ return json_response({"tags": dict(_log_groups[group]["tags"])})+++# ---------------------------------------------------------------------------+# Tags – modern ARN-based APIs+# ---------------------------------------------------------------------------++def _tag_resource(data):+ arn = data.get("resourceArn", "")+ group = _resolve_group_by_arn(arn)+ if not group:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified resource does not exist: {arn}", 400,+ )+ _log_groups[group]["tags"].update(data.get("tags", {}))+ return json_response({})+++def _untag_resource(data):+ arn = data.get("resourceArn", "")+ group = _resolve_group_by_arn(arn)+ if not group:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified resource does not exist: {arn}", 400,+ )+ for key in data.get("tagKeys", []):+ _log_groups[group]["tags"].pop(key, None)+ return json_response({})+++def _list_tags_for_resource(data):+ arn = data.get("resourceArn", "")+ group = _resolve_group_by_arn(arn)+ if not group:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified resource does not exist: {arn}", 400,+ )+ return json_response({"tags": dict(_log_groups[group]["tags"])})+++# ---------------------------------------------------------------------------+# Destinations (stubs)+# ---------------------------------------------------------------------------++def _put_destination(data):+ name = data.get("destinationName")+ if not name:+ return error_response_json("InvalidParameterException", "destinationName is required.", 400)+ dest_arn = f"arn:aws:logs:{REGION}:{ACCOUNT_ID}:destination:{name}"+ _destinations[name] = {+ "destinationName": name,+ "targetArn": data.get("targetArn", ""),+ "roleArn": data.get("roleArn", ""),+ "accessPolicy": data.get("accessPolicy", ""),+ "arn": dest_arn,+ "creationTime": int(time.time() * 1000),+ }+ return json_response({"destination": _destinations[name]})+++def _delete_destination(data):+ name = data.get("destinationName")+ if name not in _destinations:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified destination does not exist: {name}", 400,+ )+ del _destinations[name]+ return json_response({})+++def _describe_destinations(data):+ prefix = data.get("DestinationNamePrefix", "")+ limit = min(data.get("limit", 50), 50)+ token = data.get("nextToken")++ all_dests = sorted(_destinations.keys())+ if prefix:+ all_dests = [n for n in all_dests if n.startswith(prefix)]++ start = _decode_token(token)+ page = all_dests[start:start + limit]++ resp: dict = {"destinations": [_destinations[n] for n in page]}+ end = start + limit+ if end < len(all_dests):+ resp["nextToken"] = _encode_token(end)+ return json_response(resp)+++def _put_destination_policy(data):+ name = data.get("destinationName") or data.get("DestinationName")+ policy = data.get("accessPolicy") or data.get("AccessPolicy", "")+ if not name:+ return error_response_json("InvalidParameterException", "destinationName is required.", 400)+ if name not in _destinations:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified destination does not exist: {name}", 400,+ )+ _destinations[name]["accessPolicy"] = policy+ return json_response({})+++# ---------------------------------------------------------------------------+# Metric Filters+# ---------------------------------------------------------------------------++def _put_metric_filter(data):+ group = data.get("logGroupName")+ filter_name = data.get("filterName")+ if not group or not filter_name:+ return error_response_json(+ "InvalidParameterException",+ "logGroupName and filterName are required.", 400,+ )+ if group not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )+ _metric_filters[(group, filter_name)] = {+ "filterName": filter_name,+ "logGroupName": group,+ "filterPattern": data.get("filterPattern", ""),+ "metricTransformations": data.get("metricTransformations", []),+ "creationTime": int(time.time() * 1000),+ }+ return json_response({})+++def _delete_metric_filter(data):+ group = data.get("logGroupName")+ filter_name = data.get("filterName")+ key = (group, filter_name)+ if key not in _metric_filters:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified metric filter does not exist: {filter_name}", 400,+ )+ del _metric_filters[key]+ return json_response({})+++def _describe_metric_filters(data):+ group = data.get("logGroupName")+ prefix = data.get("filterNamePrefix", "")+ limit = min(data.get("limit", 50), 50)+ token = data.get("nextToken")++ if group and group not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group}", 400,+ )++ filters = sorted(+ (mf for mf in _metric_filters.values()+ if (not group or mf["logGroupName"] == group)+ and (not prefix or mf["filterName"].startswith(prefix))),+ key=lambda f: f["filterName"],+ )++ start = _decode_token(token)+ page = filters[start:start + limit]++ resp: dict = {"metricFilters": page}+ end = start + limit+ if end < len(filters):+ resp["nextToken"] = _encode_token(end)+ return json_response(resp)+++# ---------------------------------------------------------------------------+# CloudWatch Logs Insights (stubs)+# ---------------------------------------------------------------------------++def _start_query(data):+ query_id = new_uuid()+ _queries[query_id] = {+ "queryId": query_id,+ "logGroupName": data.get("logGroupName", ""),+ "logGroupNames": data.get("logGroupNames", []),+ "startTime": data.get("startTime", 0),+ "endTime": data.get("endTime", 0),+ "queryString": data.get("queryString", ""),+ "status": "Complete",+ }+ return json_response({"queryId": query_id})+++def _get_query_results(data):+ query_id = data.get("queryId")+ query = _queries.get(query_id)+ if not query:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified query does not exist: {query_id}", 400,+ )+ return json_response({+ "status": query["status"],+ "results": [],+ "statistics": {"recordsMatched": 0.0, "recordsScanned": 0.0, "bytesScanned": 0.0},+ })+++def _stop_query(data):+ query_id = data.get("queryId")+ if query_id in _queries:+ _queries[query_id]["status"] = "Cancelled"+ return json_response({"success": True})+++def reset():+ _log_groups.clear()+ _destinations.clear()+ _metric_filters.clear()+ _queries.clear()diff --git a/services/dynamodb.py b/services/dynamodb.pyindex 490d2c7f..c76115e7 100644--- a/services/dynamodb.py+++ b/services/dynamodb.py@@ -1,7 +1,11 @@"""DynamoDB Service Emulator.-Supports: CreateTable, DeleteTable, DescribeTable, ListTables,- PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem.+Supports: CreateTable, DeleteTable, DescribeTable, ListTables, UpdateTable,+ PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan,+ BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems,+ DescribeTimeToLive, UpdateTimeToLive,+ DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints,+ TagResource, UntagResource, ListTagsOfResource.Uses X-Amz-Target header for action routing (JSON API)."""@@ -10,13 +14,61 @@ import timeimport copyimport jsonimport logging+import threadingfrom collections import defaultdict+from decimal import Decimal, InvalidOperationfrom core.responses import json_response, error_response_json, new_uuid, now_isologger = logging.getLogger("dynamodb")-_tables: dict = {} # table_name -> {schema, items: {partition_key_val: {sort_key_val: item}}, ...}+_tables: dict = {}+_tags: dict = {}+_ttl_settings: dict = {}+_pitr_settings: dict = {}++# ---------------------------------------------------------------------------+# TTL background reaper+# ---------------------------------------------------------------------------++def _ttl_reaper():+ """Periodically delete items whose TTL attribute has expired."""+ while True:+ time.sleep(60)+ now = time.time()+ try:+ for table_name, setting in list(_ttl_settings.items()):+ if setting.get("TimeToLiveStatus") != "ENABLED":+ continue+ attr = setting.get("AttributeName", "")+ if not attr:+ continue+ table = _tables.get(table_name)+ if not table:+ continue+ for pk_val, sk_map in list(table["items"].items()):+ for sk_val, item in list(sk_map.items()):+ ttl_attr = item.get(attr)+ if ttl_attr is None:+ continue+ ttl_val = _extract_key_val(ttl_attr)+ try:+ if float(ttl_val) <= now:+ del sk_map[sk_val]+ logger.debug(f"TTL expired item {pk_val}/{sk_val} from {table_name}")+ except (ValueError, TypeError):+ pass+ if not sk_map:+ del table["items"][pk_val]+ _update_counts(table)+ except Exception as exc:+ logger.error(f"TTL reaper error: {exc}")+++threading.Thread(target=_ttl_reaper, daemon=True, name="dynamodb-ttl-reaper").start()++REGION = "us-east-1"+ACCOUNT_ID = "000000000000"async def handle_request(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:@@ -33,6 +85,7 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, que"DeleteTable": _delete_table,"DescribeTable": _describe_table,"ListTables": _list_tables,+ "UpdateTable": _update_table,"PutItem": _put_item,"GetItem": _get_item,"DeleteItem": _delete_item,@@ -41,6 +94,16 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, que"Scan": _scan,"BatchWriteItem": _batch_write_item,"BatchGetItem": _batch_get_item,+ "TransactWriteItems": _transact_write_items,+ "TransactGetItems": _transact_get_items,+ "DescribeTimeToLive": _describe_ttl,+ "UpdateTimeToLive": _update_ttl,+ "DescribeContinuousBackups": _describe_continuous_backups,+ "UpdateContinuousBackups": _update_continuous_backups,+ "DescribeEndpoints": _describe_endpoints,+ "TagResource": _tag_resource,+ "UntagResource": _untag_resource,+ "ListTagsOfResource": _list_tags,}handler = handlers.get(action)@@ -49,58 +112,79 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, quereturn handler(data)+# ---------------------------------------------------------------------------+# Table operations+# ---------------------------------------------------------------------------+def _create_table(data):name = data.get("TableName")if not name:return error_response_json("ValidationException", "TableName is required", 400)if name in _tables:- return error_response_json("ResourceInUseException", f"Table {name} already exists", 400)+ return error_response_json("ResourceInUseException", f"Table already exists: {name}", 400)key_schema = data.get("KeySchema", [])attr_defs = data.get("AttributeDefinitions", [])-- pk_name = None- sk_name = None+ pk_name = sk_name = Nonefor ks in key_schema:if ks["KeyType"] == "HASH":pk_name = ks["AttributeName"]elif ks["KeyType"] == "RANGE":sk_name = ks["AttributeName"]+ gsis = copy.deepcopy(data.get("GlobalSecondaryIndexes", []))+ lsis = copy.deepcopy(data.get("LocalSecondaryIndexes", []))+ for gsi in gsis:+ gsi.setdefault("IndexStatus", "ACTIVE")+ gsi.setdefault("ProvisionedThroughput", {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5})+ gsi["IndexArn"] = f"arn:aws:dynamodb:{REGION}:{ACCOUNT_ID}:table/{name}/index/{gsi['IndexName']}"+ gsi["IndexSizeBytes"] = 0+ gsi["ItemCount"] = 0+ for lsi in lsis:+ lsi["IndexArn"] = f"arn:aws:dynamodb:{REGION}:{ACCOUNT_ID}:table/{name}/index/{lsi['IndexName']}"+ lsi["IndexSizeBytes"] = 0+ lsi["ItemCount"] = 0+_tables[name] = {"TableName": name,"KeySchema": key_schema,"AttributeDefinitions": attr_defs,"pk_name": pk_name,"sk_name": sk_name,- "items": defaultdict(dict), # pk_value -> {sk_value: item}+ "items": defaultdict(dict),"TableStatus": "ACTIVE","CreationDateTime": time.time(),"ItemCount": 0,"TableSizeBytes": 0,- "TableArn": f"arn:aws:dynamodb:us-east-1:000000000000:table/{name}",- "GlobalSecondaryIndexes": data.get("GlobalSecondaryIndexes", []),- "LocalSecondaryIndexes": data.get("LocalSecondaryIndexes", []),+ "TableArn": f"arn:aws:dynamodb:{REGION}:{ACCOUNT_ID}:table/{name}",+ "TableId": new_uuid(),+ "GlobalSecondaryIndexes": gsis,+ "LocalSecondaryIndexes": lsis,"ProvisionedThroughput": data.get("ProvisionedThroughput", {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}),"BillingModeSummary": {"BillingMode": data.get("BillingMode", "PROVISIONED")},+ "StreamSpecification": data.get("StreamSpecification"),+ "SSEDescription": data.get("SSESpecification"),}-return json_response({"TableDescription": _table_description(name)})def _delete_table(data):name = data.get("TableName")if name not in _tables:- return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)+ return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)desc = _table_description(name)+ desc["TableStatus"] = "DELETING"del _tables[name]+ _tags.pop(desc.get("TableArn", ""), None)+ _ttl_settings.pop(name, None)+ _pitr_settings.pop(name, None)return json_response({"TableDescription": desc})def _describe_table(data):name = data.get("TableName")if name not in _tables:- return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)+ return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)return json_response({"Table": _table_description(name)})@@ -112,29 +196,104 @@ def _list_tables(data):names = [n for n in names if n > start]names = names[:limit]result = {"TableNames": names}- if len(names) == limit:+ if len(names) == limit and names:result["LastEvaluatedTableName"] = names[-1]return json_response(result)+def _update_table(data):+ name = data.get("TableName")+ if name not in _tables:+ return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)+ table = _tables[name]++ if "ProvisionedThroughput" in data:+ table["ProvisionedThroughput"] = data["ProvisionedThroughput"]+ if "BillingMode" in data:+ table["BillingModeSummary"] = {"BillingMode": data["BillingMode"]}+ if "AttributeDefinitions" in data:+ table["AttributeDefinitions"] = data["AttributeDefinitions"]+ if "StreamSpecification" in data:+ table["StreamSpecification"] = data["StreamSpecification"]++ for update in data.get("GlobalSecondaryIndexUpdates", []):+ if "Create" in update:+ gsi_def = copy.deepcopy(update["Create"])+ gsi_def.setdefault("IndexStatus", "ACTIVE")+ gsi_def.setdefault("ProvisionedThroughput", {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5})+ gsi_def["IndexArn"] = f"arn:aws:dynamodb:{REGION}:{ACCOUNT_ID}:table/{name}/index/{gsi_def['IndexName']}"+ gsi_def["IndexSizeBytes"] = 0+ gsi_def["ItemCount"] = 0+ table["GlobalSecondaryIndexes"].append(gsi_def)+ elif "Delete" in update:+ idx_name = update["Delete"]["IndexName"]+ table["GlobalSecondaryIndexes"] = [g for g in table["GlobalSecondaryIndexes"] if g["IndexName"] != idx_name]+ elif "Update" in update:+ idx_name = update["Update"]["IndexName"]+ for gsi in table["GlobalSecondaryIndexes"]:+ if gsi["IndexName"] == idx_name:+ if "ProvisionedThroughput" in update["Update"]:+ gsi["ProvisionedThroughput"] = update["Update"]["ProvisionedThroughput"]++ return json_response({"TableDescription": _table_description(name)})+++def _table_description(name):+ t = _tables[name]+ desc = {+ "TableName": t["TableName"],+ "KeySchema": t["KeySchema"],+ "AttributeDefinitions": t["AttributeDefinitions"],+ "TableStatus": t["TableStatus"],+ "CreationDateTime": t["CreationDateTime"],+ "ItemCount": t["ItemCount"],+ "TableSizeBytes": t["TableSizeBytes"],+ "TableArn": t["TableArn"],+ "TableId": t.get("TableId", new_uuid()),+ "ProvisionedThroughput": t["ProvisionedThroughput"],+ }+ if t.get("BillingModeSummary"):+ desc["BillingModeSummary"] = t["BillingModeSummary"]+ if t.get("GlobalSecondaryIndexes"):+ desc["GlobalSecondaryIndexes"] = t["GlobalSecondaryIndexes"]+ if t.get("LocalSecondaryIndexes"):+ desc["LocalSecondaryIndexes"] = t["LocalSecondaryIndexes"]+ if t.get("StreamSpecification"):+ desc["StreamSpecification"] = t["StreamSpecification"]+ desc["LatestStreamLabel"] = now_iso()+ desc["LatestStreamArn"] = f"{t['TableArn']}/stream/{now_iso()}"+ if t.get("SSEDescription"):+ desc["SSEDescription"] = t["SSEDescription"]+ return desc+++# ---------------------------------------------------------------------------+# Item operations+# ---------------------------------------------------------------------------+def _put_item(data):name = data.get("TableName")table = _tables.get(name)if not table:- return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)+ return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)item = data.get("Item", {})pk_val = _extract_key_val(item.get(table["pk_name"]))sk_val = _extract_key_val(item.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"-old_item = table["items"].get(pk_val, {}).get(sk_val)+ cond_expr = data.get("ConditionExpression")+ if cond_expr:+ if not _evaluate_condition(cond_expr, old_item or {}, data.get("ExpressionAttributeValues", {}), data.get("ExpressionAttributeNames", {})):+ return error_response_json("ConditionalCheckFailedException", "The conditional request failed", 400)+table["items"][pk_val][sk_val] = item_update_counts(table)result = {}if data.get("ReturnValues") == "ALL_OLD" and old_item:result["Attributes"] = old_item+ _add_consumed_capacity(result, data, name)return json_response(result)@@ -142,22 +301,17 @@ def _get_item(data):name = data.get("TableName")table = _tables.get(name)if not table:- return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)+ return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)key = data.get("Key", {})pk_val = _extract_key_val(key.get(table["pk_name"]))sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"-item = table["items"].get(pk_val, {}).get(sk_val)result = {}if item:- projection = data.get("ProjectionExpression")- if projection:- attrs = [a.strip() for a in projection.split(",")]- result["Item"] = {k: v for k, v in item.items() if k in attrs}- else:- result["Item"] = item+ result["Item"] = _apply_projection(item, data)+ _add_consumed_capacity(result, data, name)return json_response(result)@@ -165,18 +319,26 @@ def _delete_item(data):name = data.get("TableName")table = _tables.get(name)if not table:- return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)+ return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)key = data.get("Key", {})pk_val = _extract_key_val(key.get(table["pk_name"]))sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"+ old_item = table["items"].get(pk_val, {}).get(sk_val)- old_item = table["items"].get(pk_val, {}).pop(sk_val, None)+ cond_expr = data.get("ConditionExpression")+ if cond_expr:+ if not _evaluate_condition(cond_expr, old_item or {}, data.get("ExpressionAttributeValues", {}), data.get("ExpressionAttributeNames", {})):+ return error_response_json("ConditionalCheckFailedException", "The conditional request failed", 400)++ if old_item is not None:+ table["items"].get(pk_val, {}).pop(sk_val, None)_update_counts(table)result = {}if data.get("ReturnValues") == "ALL_OLD" and old_item:result["Attributes"] = old_item+ _add_consumed_capacity(result, data, name)return json_response(result)@@ -184,100 +346,186 @@ def _update_item(data):name = data.get("TableName")table = _tables.get(name)if not table:- return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)+ return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)key = data.get("Key", {})pk_val = _extract_key_val(key.get(table["pk_name"]))sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"- item = table["items"].get(pk_val, {}).get(sk_val, dict(key))- expr_attr_values = data.get("ExpressionAttributeValues", {})- expr_attr_names = data.get("ExpressionAttributeNames", {})+ existing = table["items"].get(pk_val, {}).get(sk_val)+ old_item = copy.deepcopy(existing) if existing else None+ item = copy.deepcopy(existing) if existing else dict(key)++ cond_expr = data.get("ConditionExpression")+ if cond_expr:+ if not _evaluate_condition(cond_expr, item, data.get("ExpressionAttributeValues", {}), data.get("ExpressionAttributeNames", {})):+ return error_response_json("ConditionalCheckFailedException", "The conditional request failed", 400)+update_expr = data.get("UpdateExpression", "")+ eav = data.get("ExpressionAttributeValues", {})+ ean = data.get("ExpressionAttributeNames", {})- # Basic SET/REMOVE parsingif update_expr:- item = _apply_update_expression(item, update_expr, expr_attr_values, expr_attr_names)+ item = _apply_update_expression(item, update_expr, eav, ean)table["items"][pk_val][sk_val] = item_update_counts(table)result = {}- ret = data.get("ReturnValues", "NONE")- if ret == "ALL_NEW":+ rv = data.get("ReturnValues", "NONE")+ if rv == "ALL_NEW":result["Attributes"] = item- elif ret == "ALL_OLD":- result["Attributes"] = item # Simplified+ elif rv == "ALL_OLD" and old_item:+ result["Attributes"] = old_item+ elif rv == "UPDATED_OLD" and old_item:+ result["Attributes"] = _diff_attributes(old_item, item, return_old=True)+ elif rv == "UPDATED_NEW":+ result["Attributes"] = _diff_attributes(old_item or {}, item, return_old=False)+ _add_consumed_capacity(result, data, name)return json_response(result)+# ---------------------------------------------------------------------------+# Query / Scan+# ---------------------------------------------------------------------------+def _query(data):name = data.get("TableName")table = _tables.get(name)if not table:- return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)+ return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)- expr_attr_values = data.get("ExpressionAttributeValues", {})- expr_attr_names = data.get("ExpressionAttributeNames", {})- key_condition = data.get("KeyConditionExpression", "")+ eav = data.get("ExpressionAttributeValues", {})+ ean = data.get("ExpressionAttributeNames", {})+ key_cond = data.get("KeyConditionExpression", "")filter_expr = data.get("FilterExpression", "")- limit = data.get("Limit", 1000000)+ limit = data.get("Limit")scan_forward = data.get("ScanIndexForward", True)+ esk = data.get("ExclusiveStartKey")+ index_name = data.get("IndexName")+ select = data.get("Select", "ALL_ATTRIBUTES")++ pk_name, sk_name, is_gsi = _resolve_index_keys(table, index_name)+ pk_val = _extract_pk_from_condition(key_cond, eav, ean, pk_name)+ if pk_val is None:+ return error_response_json("ValidationException", "Query condition missed key schema element", 400)++ if is_gsi or index_name:+ candidates = []+ for pk_bucket in table["items"].values():+ for it in pk_bucket.values():+ if pk_name in it and _extract_key_val(it[pk_name]) == pk_val:+ candidates.append(it)+ else:+ candidates = list(table["items"].get(pk_val, {}).values())++ if sk_name:+ sk_type = _get_attr_type(table, sk_name)+ candidates.sort(key=lambda it: _sort_key_value(it.get(sk_name), sk_type), reverse=not scan_forward)++ if key_cond:+ candidates = [it for it in candidates if _evaluate_condition(key_cond, it, eav, ean)]- # Extract partition key value from KeyConditionExpression- pk_val = _extract_pk_from_condition(key_condition, expr_attr_values, expr_attr_names, table["pk_name"])-- items = []- if pk_val and pk_val in table["items"]:- sk_items = table["items"][pk_val]- for sk, item in sorted(sk_items.items(), reverse=not scan_forward):- if _matches_condition(item, key_condition, expr_attr_values, expr_attr_names, table):- if not filter_expr or _matches_filter(item, filter_expr, expr_attr_values, expr_attr_names):- items.append(item)- if len(items) >= limit:- break+ if esk:+ candidates = _apply_exclusive_start_key(candidates, esk, pk_name, sk_name, scan_forward)++ has_more = False+ if limit is not None and len(candidates) > limit:+ has_more = True+ candidates = candidates[:limit]++ scanned_count = len(candidates)+ if filter_expr:+ filtered = [it for it in candidates if _evaluate_condition(filter_expr, it, eav, ean)]else:- # Fallback: scan all items for the matching partition key- for pk, sk_dict in table["items"].items():- for sk, item in sk_dict.items():- if _matches_condition(item, key_condition, expr_attr_values, expr_attr_names, table):- if not filter_expr or _matches_filter(item, filter_expr, expr_attr_values, expr_attr_names):- items.append(item)- if len(items) >= limit:- break+ filtered = candidates- return json_response({"Items": items, "Count": len(items), "ScannedCount": len(items)})+ if select == "COUNT":+ result = {"Count": len(filtered), "ScannedCount": scanned_count}+ else:+ result = {+ "Items": [_apply_projection(it, data) for it in filtered],+ "Count": len(filtered),+ "ScannedCount": scanned_count,+ }++ if has_more and candidates:+ lek = _build_key(candidates[-1], table["pk_name"], table["sk_name"])+ if index_name:+ ik = _build_key(candidates[-1], pk_name, sk_name)+ for k, v in ik.items():+ lek.setdefault(k, v)+ result["LastEvaluatedKey"] = lek++ _add_consumed_capacity(result, data, name)+ return json_response(result)def _scan(data):name = data.get("TableName")table = _tables.get(name)if not table:- return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)+ return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)filter_expr = data.get("FilterExpression", "")- expr_attr_values = data.get("ExpressionAttributeValues", {})- expr_attr_names = data.get("ExpressionAttributeNames", {})- limit = data.get("Limit", 1000000)-- items = []- scanned = 0- for pk, sk_dict in table["items"].items():- for sk, item in sk_dict.items():- scanned += 1- if not filter_expr or _matches_filter(item, filter_expr, expr_attr_values, expr_attr_names):- items.append(item)- if len(items) >= limit:- break+ eav = data.get("ExpressionAttributeValues", {})+ ean = data.get("ExpressionAttributeNames", {})+ limit = data.get("Limit")+ esk = data.get("ExclusiveStartKey")+ index_name = data.get("IndexName")+ select = data.get("Select", "ALL_ATTRIBUTES")++ all_items = []+ for pk in sorted(table["items"].keys()):+ for sk in sorted(table["items"][pk].keys()):+ all_items.append(table["items"][pk][sk])++ if index_name:+ pk_name_idx, _, is_gsi = _resolve_index_keys(table, index_name)+ if is_gsi:+ all_items = [it for it in all_items if pk_name_idx in it]++ if esk:+ all_items = _apply_exclusive_start_key_scan(all_items, esk, table)++ has_more = False+ if limit is not None and len(all_items) > limit:+ has_more = True+ all_items = all_items[:limit]++ scanned_count = len(all_items)+ if filter_expr:+ filtered = [it for it in all_items if _evaluate_condition(filter_expr, it, eav, ean)]+ else:+ filtered = all_items++ if select == "COUNT":+ result = {"Count": len(filtered), "ScannedCount": scanned_count}+ else:+ result = {+ "Items": [_apply_projection(it, data) for it in filtered],+ "Count": len(filtered),+ "ScannedCount": scanned_count,+ }- return json_response({"Items": items, "Count": len(items), "ScannedCount": scanned})+ if has_more and all_items:+ result["LastEvaluatedKey"] = _build_key(all_items[-1], table["pk_name"], table["sk_name"])++ _add_consumed_capacity(result, data, name)+ return json_response(result)+# ---------------------------------------------------------------------------+# Batch operations+# ---------------------------------------------------------------------------+def _batch_write_item(data):request_items = data.get("RequestItems", {})+ unprocessed = {}for table_name, requests in request_items.items():table = _tables.get(table_name)if not table:+ unprocessed[table_name] = requestscontinuefor req in requests:if "PutRequest" in req:@@ -291,134 +539,1119 @@ def _batch_write_item(data):sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"table["items"].get(pk_val, {}).pop(sk_val, None)_update_counts(table)-- return json_response({"UnprocessedItems": {}})+ return json_response({"UnprocessedItems": unprocessed})def _batch_get_item(data):request_items = data.get("RequestItems", {})responses = {}+ unprocessed = {}for table_name, config in request_items.items():table = _tables.get(table_name)if not table:+ unprocessed[table_name] = configcontinueresponses[table_name] = []+ proj = config.get("ProjectionExpression")+ config_ean = config.get("ExpressionAttributeNames", {})for key in config.get("Keys", []):pk_val = _extract_key_val(key.get(table["pk_name"]))sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"item = table["items"].get(pk_val, {}).get(sk_val)if item:+ if proj:+ item = _project_item(item, proj, config_ean)responses[table_name].append(item)+ return json_response({"Responses": responses, "UnprocessedKeys": unprocessed})- return json_response({"Responses": responses, "UnprocessedKeys": {}})+# ---------------------------------------------------------------------------+# Transaction operations+# ----------------------------------------------------------------------------# --- Helpers ---+def _transact_write_items(data):+ items_list = data.get("TransactItems", [])-def _table_description(name):- t = _tables[name]- return {- "TableName": t["TableName"],- "KeySchema": t["KeySchema"],- "AttributeDefinitions": t["AttributeDefinitions"],- "TableStatus": t["TableStatus"],- "CreationDateTime": t["CreationDateTime"],- "ItemCount": t["ItemCount"],- "TableSizeBytes": t["TableSizeBytes"],- "TableArn": t["TableArn"],- "ProvisionedThroughput": t["ProvisionedThroughput"],- "BillingModeSummary": t.get("BillingModeSummary", {}),+ for idx, transact in enumerate(items_list):+ op_type, op = _extract_transact_op(transact)+ if op is None:+ continue+ tbl = _tables.get(op.get("TableName", ""))+ if not tbl:+ return error_response_json("ResourceNotFoundException", f"Table {op.get('TableName')} not found", 400)+ cond = op.get("ConditionExpression", "")+ if cond:+ if op_type == "Put":+ existing = _get_item_by_key(tbl, _extract_key_from_item(tbl, op.get("Item", {})))+ else:+ existing = _get_item_by_key(tbl, op.get("Key", {}))+ if not _evaluate_condition(cond, existing or {}, op.get("ExpressionAttributeValues", {}), op.get("ExpressionAttributeNames", {})):+ return _transact_cancel_response(len(items_list), idx, "ConditionalCheckFailed")++ for transact in items_list:+ op_type, op = _extract_transact_op(transact)+ if op is None or op_type == "ConditionCheck":+ continue+ tbl = _tables.get(op.get("TableName", ""))+ if not tbl:+ continue+ if op_type == "Put":+ item = op["Item"]+ pk_val = _extract_key_val(item.get(tbl["pk_name"]))+ sk_val = _extract_key_val(item.get(tbl["sk_name"])) if tbl["sk_name"] else "__no_sort__"+ tbl["items"][pk_val][sk_val] = item+ elif op_type == "Delete":+ key = op["Key"]+ pk_val = _extract_key_val(key.get(tbl["pk_name"]))+ sk_val = _extract_key_val(key.get(tbl["sk_name"])) if tbl["sk_name"] else "__no_sort__"+ tbl["items"].get(pk_val, {}).pop(sk_val, None)+ elif op_type == "Update":+ key = op["Key"]+ pk_val = _extract_key_val(key.get(tbl["pk_name"]))+ sk_val = _extract_key_val(key.get(tbl["sk_name"])) if tbl["sk_name"] else "__no_sort__"+ item = copy.deepcopy(tbl["items"].get(pk_val, {}).get(sk_val, dict(key)))+ ue = op.get("UpdateExpression", "")+ if ue:+ item = _apply_update_expression(item, ue, op.get("ExpressionAttributeValues", {}), op.get("ExpressionAttributeNames", {}))+ tbl["items"][pk_val][sk_val] = item+ _update_counts(tbl)++ return json_response({})+++def _transact_get_items(data):+ items_list = data.get("TransactItems", [])+ responses = []+ for transact in items_list:+ get_op = transact.get("Get", {})+ tbl = _tables.get(get_op.get("TableName", ""))+ if not tbl:+ responses.append({})+ continue+ item = _get_item_by_key(tbl, get_op.get("Key", {}))+ if item:+ proj = get_op.get("ProjectionExpression")+ ean = get_op.get("ExpressionAttributeNames", {})+ if proj:+ item = _project_item(item, proj, ean)+ responses.append({"Item": item})+ else:+ responses.append({})+ return json_response({"Responses": responses})+++def _extract_transact_op(transact):+ for op_type in ("ConditionCheck", "Put", "Delete", "Update"):+ if op_type in transact:+ return op_type, transact[op_type]+ return None, None+++def _transact_cancel_response(total, failed_idx, reason):+ reasons = []+ for i in range(total):+ if i == failed_idx:+ reasons.append({"Code": reason, "Message": "The conditional request failed"})+ else:+ reasons.append({"Code": "None"})+ data = {+ "__type": "TransactionCanceledException",+ "message": f"Transaction cancelled, please refer cancellation reasons for specific reasons [{', '.join(r['Code'] for r in reasons)}]",+ "CancellationReasons": reasons,}+ return json_response(data, 400)-def _extract_key_val(attr):- if not attr:- return ""- if "S" in attr:- return attr["S"]- if "N" in attr:- return attr["N"]- if "B" in attr:- return attr["B"]- return str(attr)+# ---------------------------------------------------------------------------+# TTL operations+# ---------------------------------------------------------------------------+def _describe_ttl(data):+ name = data.get("TableName")+ if name not in _tables:+ return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)+ setting = _ttl_settings.get(name, {"TimeToLiveStatus": "DISABLED"})+ desc = {"TimeToLiveStatus": setting.get("TimeToLiveStatus", "DISABLED")}+ if "AttributeName" in setting:+ desc["AttributeName"] = setting["AttributeName"]+ return json_response({"TimeToLiveDescription": desc})-def _update_counts(table):- count = sum(len(sk_dict) for sk_dict in table["items"].values())- table["ItemCount"] = count- table["TableSizeBytes"] = count * 100 # rough estimate++def _update_ttl(data):+ name = data.get("TableName")+ if name not in _tables:+ return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)+ spec = data.get("TimeToLiveSpecification", {})+ enabled = spec.get("Enabled", False)+ _ttl_settings[name] = {+ "TimeToLiveStatus": "ENABLED" if enabled else "DISABLED",+ "AttributeName": spec.get("AttributeName", ""),+ }+ return json_response({"TimeToLiveSpecification": spec})+++# ---------------------------------------------------------------------------+# Continuous backups / PITR+# ---------------------------------------------------------------------------++def _describe_continuous_backups(data):+ name = data.get("TableName")+ if name not in _tables:+ return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)+ pitr_enabled = _pitr_settings.get(name, False)+ return json_response({+ "ContinuousBackupsDescription": {+ "ContinuousBackupsStatus": "ENABLED",+ "PointInTimeRecoveryDescription": {+ "PointInTimeRecoveryStatus": "ENABLED" if pitr_enabled else "DISABLED",+ "EarliestRestorableDateTime": 0,+ "LatestRestorableDateTime": 0,+ }+ }+ })+++def _update_continuous_backups(data):+ name = data.get("TableName")+ if name not in _tables:+ return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)+ spec = data.get("PointInTimeRecoverySpecification", {})+ enabled = spec.get("PointInTimeRecoveryEnabled", False)+ _pitr_settings[name] = enabled+ return json_response({+ "ContinuousBackupsDescription": {+ "ContinuousBackupsStatus": "ENABLED",+ "PointInTimeRecoveryDescription": {+ "PointInTimeRecoveryStatus": "ENABLED" if enabled else "DISABLED",+ }+ }+ })+++# ---------------------------------------------------------------------------+# Endpoint discovery+# ---------------------------------------------------------------------------++def _describe_endpoints(data):+ return json_response({+ "Endpoints": [{"Address": "dynamodb.us-east-1.amazonaws.com", "CachePeriodInMinutes": 1440}]+ })+++# ---------------------------------------------------------------------------+# Tag operations+# ---------------------------------------------------------------------------++def _tag_resource(data):+ arn = data.get("ResourceArn", "")+ tags = data.get("Tags", [])+ existing = _tags.setdefault(arn, [])+ key_map = {t["Key"]: i for i, t in enumerate(existing)}+ for tag in tags:+ if tag["Key"] in key_map:+ existing[key_map[tag["Key"]]] = tag+ else:+ existing.append(tag)+ return json_response({})+++def _untag_resource(data):+ arn = data.get("ResourceArn", "")+ keys = set(data.get("TagKeys", []))+ if arn in _tags:+ _tags[arn] = [t for t in _tags[arn] if t["Key"] not in keys]+ return json_response({})+++def _list_tags(data):+ arn = data.get("ResourceArn", "")+ return json_response({"Tags": _tags.get(arn, [])})+++# ---------------------------------------------------------------------------+# Expression tokenizer+# ---------------------------------------------------------------------------++def _tokenize(expr):+ tokens = []+ i = 0+ n = len(expr)+ while i < n:+ c = expr[i]+ if c.isspace():+ i += 1+ elif c == '(':+ tokens.append(('LPAREN', '(')); i += 1+ elif c == ')':+ tokens.append(('RPAREN', ')')); i += 1+ elif c == '[':+ tokens.append(('LBRACKET', '[')); i += 1+ elif c == ']':+ tokens.append(('RBRACKET', ']')); i += 1+ elif c == ',':+ tokens.append(('COMMA', ',')); i += 1+ elif c == '.':+ tokens.append(('DOT', '.')); i += 1+ elif c == '+':+ tokens.append(('PLUS', '+')); i += 1+ elif c == '-':+ tokens.append(('MINUS', '-')); i += 1+ elif c == '=':+ tokens.append(('EQ', '=')); i += 1+ elif c == '<':+ if i + 1 < n and expr[i + 1] == '>':+ tokens.append(('NE', '<>')); i += 2+ elif i + 1 < n and expr[i + 1] == '=':+ tokens.append(('LE', '<=')); i += 2+ else:+ tokens.append(('LT', '<')); i += 1+ elif c == '>':+ if i + 1 < n and expr[i + 1] == '=':+ tokens.append(('GE', '>=')); i += 2+ else:+ tokens.append(('GT', '>')); i += 1+ elif c == ':':+ j = i + 1+ while j < n and (expr[j].isalnum() or expr[j] == '_'):+ j += 1+ tokens.append(('VALUE_REF', expr[i:j])); i = j+ elif c == '#':+ j = i + 1+ while j < n and (expr[j].isalnum() or expr[j] == '_'):+ j += 1+ tokens.append(('NAME_REF', expr[i:j])); i = j+ elif c.isdigit():+ j = i+ while j < n and (expr[j].isdigit() or expr[j] == '.'):+ j += 1+ tokens.append(('NUMBER', expr[i:j])); i = j+ elif c.isalpha() or c == '_':+ j = i+ while j < n and (expr[j].isalnum() or expr[j] == '_'):+ j += 1+ tokens.append(('IDENT', expr[i:j])); i = j+ else:+ i += 1+ tokens.append(('EOF', ''))+ return tokens+++# ---------------------------------------------------------------------------+# Condition / filter expression evaluator (recursive descent)+# ---------------------------------------------------------------------------++class _ExprEval:+ __slots__ = ('tokens', 'pos', 'item', 'av', 'an')++ def __init__(self, tokens, item, attr_values, attr_names):+ self.tokens = tokens+ self.pos = 0+ self.item = item+ self.av = attr_values+ self.an = attr_names++ def peek(self, offset=0):+ p = self.pos + offset+ return self.tokens[p] if p < len(self.tokens) else ('EOF', '')++ def advance(self):+ tok = self.tokens[self.pos]+ self.pos += 1+ return tok++ def expect(self, ttype):+ tok = self.advance()+ if tok[0] != ttype:+ raise ValueError(f"Expected {ttype}, got {tok}")+ return tok++ def _is_kw(self, kw):+ t = self.peek()+ return t[0] == 'IDENT' and t[1].upper() == kw++ def evaluate(self):+ return self._or_expr()++ def _or_expr(self):+ left = self._and_expr()+ while self._is_kw('OR'):+ self.advance()+ left = left or self._and_expr()+ return left++ def _and_expr(self):+ left = self._not_expr()+ while self._is_kw('AND'):+ self.advance()+ left = self._not_expr() and left+ return left++ def _not_expr(self):+ if self._is_kw('NOT'):+ self.advance()+ return not self._not_expr()+ return self._primary()++ def _primary(self):+ tok = self.peek()+ if tok[0] == 'LPAREN':+ self.advance()+ result = self._or_expr()+ self.expect('RPAREN')+ return result++ if tok[0] == 'IDENT':+ fn = tok[1].lower()+ if fn == 'attribute_exists' and self.peek(1)[0] == 'LPAREN':+ return self._fn_attr_exists(True)+ if fn == 'attribute_not_exists' and self.peek(1)[0] == 'LPAREN':+ return self._fn_attr_exists(False)+ if fn == 'attribute_type' and self.peek(1)[0] == 'LPAREN':+ return self._fn_attr_type()+ if fn == 'begins_with' and self.peek(1)[0] == 'LPAREN':+ return self._fn_begins_with()+ if fn == 'contains' and self.peek(1)[0] == 'LPAREN':+ return self._fn_contains()++ left = self._operand()+ tok = self.peek()++ if tok[0] in ('EQ', 'NE', 'LT', 'GT', 'LE', 'GE'):+ op = self.advance()[1]+ right = self._operand()+ return _compare_ddb(left, op, right)++ if self._is_kw('BETWEEN'):+ self.advance()+ low = self._operand()+ if self._is_kw('AND'):+ self.advance()+ high = self._operand()+ return _compare_ddb(low, '<=', left) and _compare_ddb(left, '<=', high)++ if self._is_kw('IN'):+ self.advance()+ self.expect('LPAREN')+ values = [self._operand()]+ while self.peek()[0] == 'COMMA':+ self.advance()+ values.append(self._operand())+ self.expect('RPAREN')+ return any(_compare_ddb(left, '=', v) for v in values)++ return left is not None++ def _operand(self):+ tok = self.peek()+ if tok[0] == 'IDENT' and tok[1].lower() == 'size' and self.peek(1)[0] == 'LPAREN':+ return self._fn_size()+ if tok[0] == 'VALUE_REF':+ self.advance()+ return self.av.get(tok[1])+ path = self._parse_path()+ return _get_at_path(self.item, path)++ def _parse_path(self):+ parts = []+ tok = self.peek()+ if tok[0] == 'NAME_REF':+ self.advance()+ parts.append(self.an.get(tok[1], tok[1]))+ elif tok[0] == 'IDENT':+ self.advance()+ parts.append(tok[1])+ else:+ return parts+ while True:+ if self.peek()[0] == 'DOT':+ self.advance()+ tok = self.peek()+ if tok[0] == 'NAME_REF':+ self.advance(); parts.append(self.an.get(tok[1], tok[1]))+ elif tok[0] == 'IDENT':+ self.advance(); parts.append(tok[1])+ else:+ break+ elif self.peek()[0] == 'LBRACKET':+ self.advance()+ idx = self.expect('NUMBER')+ parts.append(int(idx[1]))+ self.expect('RBRACKET')+ else:+ break+ return parts++ # --- built-in functions ---++ def _fn_attr_exists(self, should_exist):+ self.advance(); self.expect('LPAREN')+ path = self._parse_path()+ self.expect('RPAREN')+ exists = _get_at_path(self.item, path) is not None+ return exists if should_exist else not exists++ def _fn_attr_type(self):+ self.advance(); self.expect('LPAREN')+ path = self._parse_path()+ self.expect('COMMA')+ type_val = self._operand()+ self.expect('RPAREN')+ attr = _get_at_path(self.item, path)+ if attr is None or type_val is None:+ return False+ return _ddb_type(attr) == (type_val.get("S", "") if isinstance(type_val, dict) else "")++ def _fn_begins_with(self):+ self.advance(); self.expect('LPAREN')+ path = self._parse_path()+ self.expect('COMMA')+ substr = self._operand()+ self.expect('RPAREN')+ attr = _get_at_path(self.item, path)+ if attr is None or substr is None:+ return False+ if "S" in attr and "S" in substr:+ return attr["S"].startswith(substr["S"])+ if "B" in attr and "B" in substr:+ return str(attr["B"]).startswith(str(substr["B"]))+ return False++ def _fn_contains(self):+ self.advance(); self.expect('LPAREN')+ path = self._parse_path()+ self.expect('COMMA')+ val = self._operand()+ self.expect('RPAREN')+ attr = _get_at_path(self.item, path)+ if attr is None or val is None:+ return False+ if "S" in attr and "S" in val:+ return val["S"] in attr["S"]+ if "SS" in attr and "S" in val:+ return val["S"] in attr["SS"]+ if "NS" in attr and "N" in val:+ return val["N"] in attr["NS"]+ if "BS" in attr and "B" in val:+ return val["B"] in attr["BS"]+ if "L" in attr:+ return any(_ddb_equals(e, val) for e in attr["L"])+ return False++ def _fn_size(self):+ self.advance(); self.expect('LPAREN')+ path = self._parse_path()+ self.expect('RPAREN')+ attr = _get_at_path(self.item, path)+ if attr is None:+ return None+ return {"N": str(_ddb_size(attr))}+++def _evaluate_condition(expr, item, attr_values, attr_names):+ if not expr or not expr.strip():+ return True+ try:+ tokens = _tokenize(expr)+ return _ExprEval(tokens, item, attr_values, attr_names).evaluate()+ except Exception as e:+ logger.warning("Expression evaluation error: %s for expr: %s", e, expr)+ raise ValueError(f"Invalid expression: {e}")+# ---------------------------------------------------------------------------+# Update expression+# ---------------------------------------------------------------------------+def _apply_update_expression(item, expr, attr_values, attr_names):- """Basic SET and REMOVE expression support."""- item = dict(item)-- # Handle SET- set_match = re.search(r'SET\s+(.+?)(?=\s+REMOVE|\s+ADD|\s+DELETE|$)', expr, re.IGNORECASE)- if set_match:- assignments = set_match.group(1).split(",")- for assign in assignments:- parts = assign.strip().split("=", 1)+ item = copy.deepcopy(item)+ tokens = _tokenize(expr)+ clauses = {}+ current_clause = None+ current_tokens = []+ for tok in tokens:+ if tok[0] == 'IDENT' and tok[1].upper() in ('SET', 'REMOVE', 'ADD', 'DELETE'):+ if current_clause is not None:+ clauses[current_clause] = current_tokens+ current_clause = tok[1].upper()+ current_tokens = []+ elif tok[0] != 'EOF':+ current_tokens.append(tok)+ if current_clause is not None:+ clauses[current_clause] = current_tokens++ if 'SET' in clauses:+ _apply_set(item, clauses['SET'], attr_values, attr_names)+ if 'REMOVE' in clauses:+ _apply_remove(item, clauses['REMOVE'], attr_names)+ if 'ADD' in clauses:+ _apply_add(item, clauses['ADD'], attr_values, attr_names)+ if 'DELETE' in clauses:+ _apply_delete(item, clauses['DELETE'], attr_values, attr_names)+ return item+++def _apply_set(item, tokens, attr_values, attr_names):+ for assignment in _split_by_comma(tokens):+ eq_idx = None+ for i, tok in enumerate(assignment):+ if tok[0] == 'EQ':+ eq_idx = i+ break+ if eq_idx is None:+ continue+ path_parts = _parse_path_from_tokens(assignment[:eq_idx], attr_names)+ value = _eval_set_value(assignment[eq_idx + 1:], item, attr_values, attr_names)+ if path_parts and value is not None:+ _set_at_path(item, path_parts, value)+++def _eval_set_value(tokens, item, attr_values, attr_names):+ if not tokens:+ return None++ paren_depth = 0+ for i, tok in enumerate(tokens):+ if tok[0] == 'LPAREN':+ paren_depth += 1+ elif tok[0] == 'RPAREN':+ paren_depth -= 1+ elif paren_depth == 0 and tok[0] in ('PLUS', 'MINUS') and i > 0:+ left = _eval_set_value(tokens[:i], item, attr_values, attr_names)+ right = _eval_set_value(tokens[i + 1:], item, attr_values, attr_names)+ if left and right and "N" in left and "N" in right:+ lv, rv = Decimal(left["N"]), Decimal(right["N"])+ return {"N": str(lv + rv if tok[0] == 'PLUS' else lv - rv)}+ return left++ if len(tokens) >= 2 and tokens[0][0] == 'IDENT' and tokens[1][0] == 'LPAREN':+ fn = tokens[0][1].lower()+ inner_end = _find_matching_paren(tokens, 1)+ if fn == 'if_not_exists' and inner_end is not None:+ inner = tokens[2:inner_end]+ parts = _split_by_comma(inner)+ if len(parts) == 2:+ path = _parse_path_from_tokens(parts[0], attr_names)+ existing = _get_at_path(item, path)+ if existing is not None:+ return existing+ return _eval_set_value(parts[1], item, attr_values, attr_names)+ if fn == 'list_append' and inner_end is not None:+ inner = tokens[2:inner_end]+ parts = _split_by_comma(inner)if len(parts) == 2:- path = _resolve_name(parts[0].strip(), attr_names)- val_ref = parts[1].strip()- if val_ref in attr_values:- item[path] = attr_values[val_ref]-- # Handle REMOVE- remove_match = re.search(r'REMOVE\s+(.+?)(?=\s+SET|\s+ADD|\s+DELETE|$)', expr, re.IGNORECASE)- if remove_match:- fields = remove_match.group(1).split(",")- for f in fields:- path = _resolve_name(f.strip(), attr_names)- item.pop(path, None)+ a = _eval_set_value(parts[0], item, attr_values, attr_names)+ b = _eval_set_value(parts[1], item, attr_values, attr_names)+ al = a.get("L", []) if isinstance(a, dict) else []+ bl = b.get("L", []) if isinstance(b, dict) else []+ return {"L": al + bl}++ if len(tokens) == 1:+ tok = tokens[0]+ if tok[0] == 'VALUE_REF':+ return attr_values.get(tok[1])++ path = _parse_path_from_tokens(tokens, attr_names)+ if path:+ val = _get_at_path(item, path)+ if val is not None:+ return val++ if len(tokens) == 1 and tokens[0][0] == 'VALUE_REF':+ return attr_values.get(tokens[0][1])- return item+ return None-def _resolve_name(name, attr_names):- return attr_names.get(name, name)+def _apply_remove(item, tokens, attr_names):+ for path_tokens in _split_by_comma(tokens):+ path = _parse_path_from_tokens(path_tokens, attr_names)+ if path:+ _remove_at_path(item, path)-def _extract_pk_from_condition(condition, attr_values, attr_names, pk_name):- """Try to extract partition key value from KeyConditionExpression."""- resolved_pk = pk_name- for alias, real_name in attr_names.items():- if real_name == pk_name:- resolved_pk = alias- break+def _apply_add(item, tokens, attr_values, attr_names):+ for part in _split_by_comma(tokens):+ val_idx = None+ for i in range(len(part) - 1, -1, -1):+ if part[i][0] == 'VALUE_REF':+ val_idx = i+ break+ if val_idx is None:+ continue+ path = _parse_path_from_tokens(part[:val_idx], attr_names)+ add_val = attr_values.get(part[val_idx][1])+ if not path or add_val is None:+ continue++ existing = _get_at_path(item, path)++ if "N" in add_val:+ inc = Decimal(add_val["N"])+ cur = Decimal(existing["N"]) if existing and "N" in existing else Decimal(0)+ _set_at_path(item, path, {"N": str(cur + inc)})+ elif "SS" in add_val:+ cur = set(existing["SS"]) if existing and "SS" in existing else set()+ _set_at_path(item, path, {"SS": sorted(cur | set(add_val["SS"]))})+ elif "NS" in add_val:+ cur = set(existing["NS"]) if existing and "NS" in existing else set()+ _set_at_path(item, path, {"NS": sorted(cur | set(add_val["NS"]))})+ elif "BS" in add_val:+ cur = set(existing["BS"]) if existing and "BS" in existing else set()+ _set_at_path(item, path, {"BS": sorted(cur | set(add_val["BS"]))})+++def _apply_delete(item, tokens, attr_values, attr_names):+ for part in _split_by_comma(tokens):+ val_idx = None+ for i in range(len(part) - 1, -1, -1):+ if part[i][0] == 'VALUE_REF':+ val_idx = i+ break+ if val_idx is None:+ continue+ path = _parse_path_from_tokens(part[:val_idx], attr_names)+ del_val = attr_values.get(part[val_idx][1])+ if not path or del_val is None:+ continue++ existing = _get_at_path(item, path)+ if existing is None:+ continue- # Match patterns like "#pk = :val" or "pk = :val"- pattern = rf'{re.escape(resolved_pk)}\s*=\s*(:\w+)'- match = re.search(pattern, condition)- if match:- val_ref = match.group(1)- if val_ref in attr_values:- return _extract_key_val(attr_values[val_ref])+ for set_type in ("SS", "NS", "BS"):+ if set_type in del_val and set_type in existing:+ remaining = [s for s in existing[set_type] if s not in del_val[set_type]]+ if remaining:+ _set_at_path(item, path, {set_type: remaining})+ else:+ _remove_at_path(item, path)+ break+++# ---------------------------------------------------------------------------+# Token helpers+# ---------------------------------------------------------------------------++def _split_by_comma(tokens):+ parts = []+ current = []+ depth = 0+ for tok in tokens:+ if tok[0] == 'LPAREN':+ depth += 1; current.append(tok)+ elif tok[0] == 'RPAREN':+ depth -= 1; current.append(tok)+ elif tok[0] == 'COMMA' and depth == 0:+ if current:+ parts.append(current)+ current = []+ else:+ current.append(tok)+ if current:+ parts.append(current)+ return parts+++def _find_matching_paren(tokens, start):+ depth = 0+ for i in range(start, len(tokens)):+ if tokens[i][0] == 'LPAREN':+ depth += 1+ elif tokens[i][0] == 'RPAREN':+ depth -= 1+ if depth == 0:+ return ireturn None-def _matches_condition(item, condition, attr_values, attr_names, table):- """Simplified condition matching — checks basic equality."""- if not condition:+def _parse_path_from_tokens(tokens, attr_names):+ parts = []+ i = 0+ while i < len(tokens):+ tok = tokens[i]+ if tok[0] == 'NAME_REF':+ parts.append(attr_names.get(tok[1], tok[1]))+ elif tok[0] == 'IDENT':+ parts.append(tok[1])+ elif tok[0] == 'LBRACKET':+ i += 1+ if i < len(tokens) and tokens[i][0] == 'NUMBER':+ parts.append(int(tokens[i][1]))+ i += 1+ elif tok[0] not in ('DOT', 'RBRACKET'):+ break+ i += 1+ return parts+++# ---------------------------------------------------------------------------+# Path operations on DynamoDB-typed items+# ---------------------------------------------------------------------------++def _get_at_path(item, path_parts):+ if not path_parts or not item:+ return None+ current = item.get(path_parts[0])+ for part in path_parts[1:]:+ if current is None:+ return None+ if isinstance(part, int):+ if isinstance(current, dict) and "L" in current:+ lst = current["L"]+ if 0 <= part < len(lst):+ current = lst[part]+ else:+ return None+ else:+ return None+ else:+ if isinstance(current, dict) and "M" in current:+ current = current["M"].get(part)+ else:+ return None+ return current+++def _set_at_path(item, path_parts, value):+ if not path_parts:+ return+ if len(path_parts) == 1:+ part = path_parts[0]+ if isinstance(part, int):+ if isinstance(item, dict) and "L" in item:+ lst = item["L"]+ while len(lst) <= part:+ lst.append({"NULL": True})+ lst[part] = value+ else:+ if isinstance(item, dict):+ if "M" in item:+ item["M"][part] = value+ else:+ item[part] = value+ return++ first, rest = path_parts[0], path_parts[1:]+ if isinstance(first, int):+ if isinstance(item, dict) and "L" in item:+ lst = item["L"]+ while len(lst) <= first:+ lst.append({"NULL": True})+ child = lst[first]+ if not isinstance(child, dict):+ child = {"M": {}} if isinstance(rest[0], str) else {"L": []}+ lst[first] = child+ _set_at_path(child, rest, value)+ else:+ if isinstance(item, dict):+ container = item.get("M") if "M" in item else item+ if first not in container:+ container[first] = {"L": []} if isinstance(rest[0], int) else {"M": {}}+ _set_at_path(container[first], rest, value)+++def _remove_at_path(item, path_parts):+ if not path_parts or not item:+ return+ if len(path_parts) == 1:+ part = path_parts[0]+ if isinstance(part, int):+ if isinstance(item, dict) and "L" in item:+ lst = item["L"]+ if 0 <= part < len(lst):+ lst.pop(part)+ elif isinstance(item, dict):+ if "M" in item:+ item["M"].pop(part, None)+ else:+ item.pop(part, None)+ return++ first, rest = path_parts[0], path_parts[1:]+ if isinstance(first, int):+ if isinstance(item, dict) and "L" in item and 0 <= first < len(item["L"]):+ _remove_at_path(item["L"][first], rest)+ elif isinstance(item, dict):+ child = item["M"].get(first) if "M" in item else item.get(first)+ if child is not None:+ _remove_at_path(child, rest)+++# ---------------------------------------------------------------------------+# DynamoDB value comparison helpers+# ---------------------------------------------------------------------------++def _compare_ddb(left, op, right):+ if left is None or right is None:+ if op == '=':+ return left is None and right is None+ if op == '<>':+ return not (left is None and right is None)+ return False++ lt, lv = _ddb_comparable(left)+ rt, rv = _ddb_comparable(right)++ if lt != rt:+ return op == '<>'++ if op in ('<', '>', '<=', '>=') and lt not in ('S', 'N', 'B'):+ return False++ try:+ if op == '=': return lv == rv+ if op == '<>': return lv != rv+ if op == '<': return lv < rv+ if op == '>': return lv > rv+ if op == '<=': return lv <= rv+ if op == '>=': return lv >= rv+ except TypeError:+ return False+ return False+++def _ddb_comparable(val):+ if isinstance(val, dict):+ if "S" in val:+ return ("S", val["S"])+ if "N" in val:+ try:+ return ("N", Decimal(val["N"]))+ except (InvalidOperation, TypeError, ValueError):+ return ("N", Decimal(0))+ if "B" in val:+ return ("B", val["B"])+ if "BOOL" in val:+ return ("BOOL", val["BOOL"])+ if "NULL" in val:+ return ("NULL", None)+ if "SS" in val:+ return ("SS", frozenset(val["SS"]))+ if "NS" in val:+ return ("NS", frozenset(val["NS"]))+ if "BS" in val:+ return ("BS", frozenset(val["BS"]))+ return ("UNKNOWN", None)+++def _ddb_equals(a, b):+ if a is None and b is None:return True- # For now, just return True (items are already filtered by pk)- return True+ if a is None or b is None:+ return False+ ta, va = _ddb_comparable(a)+ tb, vb = _ddb_comparable(b)+ return ta == tb and va == vb-def _matches_filter(item, filter_expr, attr_values, attr_names):- """Simplified filter expression matching."""- if not filter_expr:- return True- # Basic attribute_exists / = support- for alias, real_name in attr_names.items():- filter_expr = filter_expr.replace(alias, real_name)-- # Check equality: "field = :val"- eq_match = re.search(r'(\w+)\s*=\s*(:\w+)', filter_expr)- if eq_match:- field = eq_match.group(1)- val_ref = eq_match.group(2)- if field in item and val_ref in attr_values:- return item[field] == attr_values[val_ref]- return True+def _ddb_type(val):+ if isinstance(val, dict):+ for t in ("S", "N", "B", "SS", "NS", "BS", "BOOL", "NULL", "L", "M"):+ if t in val:+ return t+ return ""+++def _ddb_size(val):+ if isinstance(val, dict):+ if "S" in val: return len(val["S"])+ if "B" in val: return len(val["B"])+ if "SS" in val: return len(val["SS"])+ if "NS" in val: return len(val["NS"])+ if "BS" in val: return len(val["BS"])+ if "L" in val: return len(val["L"])+ if "M" in val: return len(val["M"])+ return 0+++# ---------------------------------------------------------------------------+# Key / index helpers+# ---------------------------------------------------------------------------++def _extract_key_val(attr):+ if not attr:+ return ""+ if isinstance(attr, dict):+ if "S" in attr: return attr["S"]+ if "N" in attr: return attr["N"]+ if "B" in attr: return attr["B"]+ return str(attr)+++def _resolve_index_keys(table, index_name):+ if not index_name:+ return table["pk_name"], table["sk_name"], False+ for gsi in table.get("GlobalSecondaryIndexes", []):+ if gsi["IndexName"] == index_name:+ pk = sk = None+ for ks in gsi["KeySchema"]:+ if ks["KeyType"] == "HASH": pk = ks["AttributeName"]+ elif ks["KeyType"] == "RANGE": sk = ks["AttributeName"]+ return pk, sk, True+ for lsi in table.get("LocalSecondaryIndexes", []):+ if lsi["IndexName"] == index_name:+ pk = sk = None+ for ks in lsi["KeySchema"]:+ if ks["KeyType"] == "HASH": pk = ks["AttributeName"]+ elif ks["KeyType"] == "RANGE": sk = ks["AttributeName"]+ return pk, sk, False+ return table["pk_name"], table["sk_name"], False+++def _get_attr_type(table, attr_name):+ for ad in table.get("AttributeDefinitions", []):+ if ad["AttributeName"] == attr_name:+ return ad["AttributeType"]+ return "S"+++def _sort_key_value(attr, sk_type):+ if attr is None:+ return "" if sk_type != "N" else Decimal(0)+ val = _extract_key_val(attr)+ if sk_type == "N":+ try:+ return Decimal(val)+ except (InvalidOperation, TypeError, ValueError):+ return Decimal(0)+ return val+++def _extract_pk_from_condition(condition, attr_values, attr_names, pk_name):+ if not condition:+ return None+ pk_refs = [pk_name]+ for alias, real in attr_names.items():+ if real == pk_name:+ pk_refs.append(alias)+ for ref in pk_refs:+ m = re.search(rf'(?:^|[\s(]){re.escape(ref)}\s*=\s*(:\w+)', condition)+ if m and m.group(1) in attr_values:+ return _extract_key_val(attr_values[m.group(1)])+ m = re.search(rf'(:\w+)\s*=\s*{re.escape(ref)}(?:$|[\s)])', condition)+ if m and m.group(1) in attr_values:+ return _extract_key_val(attr_values[m.group(1)])+ return None+++# ---------------------------------------------------------------------------+# Pagination helpers+# ---------------------------------------------------------------------------++def _apply_exclusive_start_key(candidates, esk, pk_name, sk_name, scan_forward=True):+ if not esk or not candidates:+ return candidates+ if not sk_name or sk_name not in esk:+ return []+ start_sk = esk[sk_name]+ result = []+ for item in candidates:+ item_sk = item.get(sk_name)+ if item_sk is None:+ continue+ if scan_forward:+ if _compare_ddb(item_sk, '>', start_sk):+ result.append(item)+ else:+ if _compare_ddb(item_sk, '<', start_sk):+ result.append(item)+ return result+++def _apply_exclusive_start_key_scan(all_items, esk, table):+ pk_name = table["pk_name"]+ sk_name = table["sk_name"]+ start_pk = _extract_key_val(esk.get(pk_name, {}))+ start_sk = _extract_key_val(esk.get(sk_name, {})) if sk_name and sk_name in esk else ""+ result = []+ for item in all_items:+ item_pk = _extract_key_val(item.get(pk_name, {}))+ item_sk = _extract_key_val(item.get(sk_name, {})) if sk_name and sk_name in item else ""+ if (item_pk, item_sk) > (start_pk, start_sk):+ result.append(item)+ return result+++def _build_key(item, pk_name, sk_name):+ key = {}+ if pk_name and pk_name in item:+ key[pk_name] = item[pk_name]+ if sk_name and sk_name in item:+ key[sk_name] = item[sk_name]+ return key+++# ---------------------------------------------------------------------------+# Projection helpers+# ---------------------------------------------------------------------------++def _apply_projection(item, data):+ proj = data.get("ProjectionExpression")+ ean = data.get("ExpressionAttributeNames", {})+ if not proj:+ return item+ return _project_item(item, proj, ean)+++def _project_item(item, proj_expr, attr_names):+ attrs = [a.strip() for a in proj_expr.split(",")]+ result = {}+ for attr in attrs:+ first = attr.split(".")[0].split("[")[0]+ resolved = attr_names.get(first, first) if first.startswith("#") else first+ if resolved in item:+ result[resolved] = item[resolved]+ return result+++# ---------------------------------------------------------------------------+# Misc helpers+# ---------------------------------------------------------------------------++def _update_counts(table):+ count = sum(len(v) for v in table["items"].values())+ table["ItemCount"] = count+ table["TableSizeBytes"] = count * 200+++def _add_consumed_capacity(result, data, table_name):+ rc = data.get("ReturnConsumedCapacity", "NONE")+ if rc == "NONE":+ return+ cap = {"TableName": table_name, "CapacityUnits": 1.0}+ if rc == "INDEXES":+ cap["Table"] = {"CapacityUnits": 1.0}+ result["ConsumedCapacity"] = cap+++def _get_item_by_key(table, key):+ pk_val = _extract_key_val(key.get(table["pk_name"]))+ sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"+ return table["items"].get(pk_val, {}).get(sk_val)+++def _extract_key_from_item(table, item):+ key = {}+ if table["pk_name"] in item:+ key[table["pk_name"]] = item[table["pk_name"]]+ if table["sk_name"] and table["sk_name"] in item:+ key[table["sk_name"]] = item[table["sk_name"]]+ return key+++def _diff_attributes(old_item, new_item, return_old=True):+ result = {}+ all_keys = set(list(old_item.keys()) + list(new_item.keys()))+ for k in all_keys:+ ov = old_item.get(k)+ nv = new_item.get(k)+ if ov != nv:+ result[k] = ov if return_old and ov is not None else nv if nv is not None else {}+ return result+++def reset():+ _tables.clear()+ _tags.clear()+ _ttl_settings.clear()+ _pitr_settings.clear()diff --git a/services/ecs.py b/services/ecs.pyindex b6880fe3..d5286636 100644--- a/services/ecs.py+++ b/services/ecs.py@@ -1,10 +1,15 @@"""ECS (Elastic Container Service) Emulator.-REST JSON API — path-based routing like real ECS.-Supports: CreateCluster, DeleteCluster, DescribeCluster, ListClusters,+REST JSON API — X-Amz-Target header routing with path-based fallback.+Supports: CreateCluster, DeleteCluster, DescribeClusters, ListClusters,+ UpdateCluster, UpdateClusterSettings,RegisterTaskDefinition, DeregisterTaskDefinition, DescribeTaskDefinition, ListTaskDefinitions,CreateService, DeleteService, DescribeServices, UpdateService, ListServices,- RunTask, StopTask, DescribeTasks, ListTasks.+ RunTask, StopTask, DescribeTasks, ListTasks,+ TagResource, UntagResource, ListTagsForResource,+ ExecuteCommand, ListAccountSettings, PutAccountSetting,+ CreateCapacityProvider, DeleteCapacityProvider, DescribeCapacityProviders,+ PutClusterCapacityProviders.Container execution: if Docker socket is available, RunTask actually runs containers."""@@ -14,21 +19,25 @@ import jsonimport timeimport logging-from core.responses import json_response, error_response_json, new_uuid+from core.responses import json_response, error_response_json, new_uuid, now_isologger = logging.getLogger("ecs")-ACCOUNT_ID = "000000000000"-REGION = "us-east-1"+ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")-_clusters: dict = {} # cluster_name -> cluster dict-_task_defs: dict = {} # family:revision -> task def dict-_task_def_latest: dict = {} # family -> latest revision number-_services: dict = {} # cluster_name/service_name -> service dict-_tasks: dict = {} # task_arn -> task dict+_clusters: dict = {}+_task_defs: dict = {}+_task_def_latest: dict = {}+_services: dict = {}+_tasks: dict = {}+_tags: dict = {}+_account_settings: dict = {}+_capacity_providers: dict = {}-# Docker client (optional)_docker = None++def _get_docker():global _dockerif _docker is None:@@ -40,58 +49,73 @@ def _get_docker():return _docker+def _ts():+ return time.time()+++def _iso():+ return now_iso()+++# ---------------------------------------------------------------------------+# Request routing+# ---------------------------------------------------------------------------+async def handle_request(method, path, headers, body, query_params):try:data = json.loads(body) if body else {}except json.JSONDecodeError:data = {}- # ECS uses path-based routing: /clusters, /taskdefinitions, etc.- # Strip leading slash and split- parts = [p for p in path.strip("/").split("/") if p]+ if method == "GET":+ for k, v in query_params.items():+ if k not in data:+ data[k] = v[0] if isinstance(v, list) and len(v) == 1 else v- # Also support X-Amz-Target for some SDKs- target = headers.get("x-amz-target", "")+ target = headers.get("x-amz-target", "") or headers.get("X-Amz-Target", "")if target:action = target.split(".")[-1]- return _dispatch_action(action, data, parts, method)+ return _dispatch_action(action, data)- # Path-based dispatch+ parts = [p for p in path.strip("/").split("/") if p]if not parts:return error_response_json("InvalidRequest", "Missing path", 400)+ return _dispatch_path(method, parts, data)+++def _dispatch_action(action, data):+ handler = _ACTION_MAP.get(action)+ if not handler:+ return error_response_json("InvalidAction", f"Unknown ECS action: {action}", 400)+ return handler(data)+++def _dispatch_path(method, parts, data):resource = parts[0]- # POST /clusters -> CreateCluster- # GET /clusters -> ListClustersif resource == "clusters":- if method == "POST" and len(parts) == 1:- return _create_cluster(data)if method == "GET" and len(parts) == 1:return _list_clusters(data)if method == "POST" and len(parts) == 2 and parts[1] == "delete":return _delete_cluster(data)- if method == "POST" and len(parts) == 1 and "describe" in data:- return _describe_clusters(data)- # POST /clusters with clusters key = describe- if method == "POST" and "clusters" in data:- return _describe_clusters(data)+ if method == "POST" and len(parts) == 1:+ if "clusters" in data and isinstance(data["clusters"], list):+ return _describe_clusters(data)+ return _create_cluster(data)- # /taskdefinitionsif resource == "taskdefinitions":if method == "POST" and len(parts) == 1:return _register_task_definition(data)if method == "GET" and len(parts) == 1:return _list_task_definitions(data)if method == "GET" and len(parts) == 2:- return _describe_task_definition(parts[1])+ return _describe_task_definition({"taskDefinition": parts[1]})if method == "DELETE" and len(parts) == 2:- return _deregister_task_definition(parts[1])+ return _deregister_task_definition({"taskDefinition": parts[1]})- # /tasksif resource == "tasks":if method == "POST" and len(parts) == 1:- # Could be RunTask or DescribeTasks depending on bodyif "taskDefinition" in data:return _run_task(data)if "tasks" in data:@@ -99,271 +123,577 @@ async def handle_request(method, path, headers, body, query_params):if method == "GET" and len(parts) == 1:return _list_tasks(data)- # /servicesif resource == "services":- if method == "POST" and len(parts) == 1:- if "serviceName" in data and "taskDefinition" in data:- return _create_service(data)- if "services" in data:- return _describe_services(data)if method == "GET" and len(parts) == 1:return _list_services(data)+ if method == "POST" and len(parts) == 1:+ if "services" in data and isinstance(data["services"], list):+ return _describe_services(data)+ if "serviceName" in data:+ return _create_service(data)if method == "PUT" and len(parts) == 2:- return _update_service(parts[1], data)+ data.setdefault("service", parts[1])+ return _update_service(data)if method == "DELETE" and len(parts) == 2:- return _delete_service(parts[1], data)+ data.setdefault("service", parts[1])+ return _delete_service(data)- # /stoptaskif resource == "stoptask":return _stop_task(data)- return error_response_json("InvalidRequest", f"Unknown ECS path: {path}", 400)---def _dispatch_action(action, data, parts, method):- """Handle X-Amz-Target based dispatch."""- handlers = {- "CreateCluster": _create_cluster,- "DeleteCluster": _delete_cluster,- "DescribeClusters": _describe_clusters,- "ListClusters": _list_clusters,- "RegisterTaskDefinition": _register_task_definition,- "DeregisterTaskDefinition": lambda d: _deregister_task_definition(d.get("taskDefinition", "")),- "DescribeTaskDefinition": lambda d: _describe_task_definition(d.get("taskDefinition", "")),- "ListTaskDefinitions": _list_task_definitions,- "CreateService": _create_service,- "DeleteService": lambda d: _delete_service(d.get("service", ""), d),- "DescribeServices": _describe_services,- "UpdateService": lambda d: _update_service(d.get("service", ""), d),- "ListServices": _list_services,- "RunTask": _run_task,- "StopTask": _stop_task,- "DescribeTasks": _describe_tasks,- "ListTasks": _list_tasks,- }- handler = handlers.get(action)- if not handler:- return error_response_json("InvalidAction", f"Unknown ECS action: {action}", 400)- return handler(data)+ if resource == "tags":+ if method == "POST":+ return _tag_resource(data)+ if method == "DELETE":+ return _untag_resource(data)+ if method == "GET":+ return _list_tags_for_resource(data)++ return error_response_json("InvalidRequest", f"Unknown ECS path: /{'/'.join(parts)}", 400)-# ---- Clusters ----+# ---------------------------------------------------------------------------+# Clusters+# ---------------------------------------------------------------------------def _create_cluster(data):name = data.get("clusterName", "default")+ if name in _clusters and _clusters[name]["status"] == "ACTIVE":+ return json_response({"cluster": _clusters[name]})+arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:cluster/{name}"- _clusters[name] = {- "clusterArn": arn, "clusterName": name,- "status": "ACTIVE", "registeredContainerInstancesCount": 0,- "runningTasksCount": 0, "pendingTasksCount": 0,- "activeServicesCount": 0, "tags": data.get("tags", []),- "settings": data.get("settings", []),+ cluster = {+ "clusterArn": arn,+ "clusterName": name,+ "status": "ACTIVE",+ "registeredContainerInstancesCount": 0,+ "runningTasksCount": 0,+ "pendingTasksCount": 0,+ "activeServicesCount": 0,+ "tags": data.get("tags", []),+ "settings": data.get("settings", [+ {"name": "containerInsights", "value": "disabled"},+ ]),"capacityProviders": data.get("capacityProviders", []),+ "defaultCapacityProviderStrategy": data.get("defaultCapacityProviderStrategy", []),+ "statistics": [],+ "attachments": [],+ "attachmentsStatus": "",}- return json_response({"cluster": _clusters[name]})+ _clusters[name] = cluster+ if cluster["tags"]:+ _tags[arn] = list(cluster["tags"])+ return json_response({"cluster": cluster})def _delete_cluster(data):- name = data.get("cluster", "default")- name = _resolve_cluster_name(name)+ name = _resolve_cluster_name(data.get("cluster", "default"))cluster = _clusters.pop(name, None)if not cluster:- return error_response_json("ClusterNotFoundException", f"Cluster {name} not found", 400)+ return error_response_json("ClusterNotFoundException", f"Cluster not found.", 400)+ cluster["status"] = "INACTIVE"+ _tags.pop(cluster["clusterArn"], None)return json_response({"cluster": cluster})def _describe_clusters(data):names = data.get("clusters", ["default"])+ include = set(data.get("include", []))result = []failures = []- for name in names:- n = _resolve_cluster_name(name)+ for ref in names:+ n = _resolve_cluster_name(ref)if n in _clusters:- result.append(_clusters[n])+ c = dict(_clusters[n])+ if "TAGS" in include:+ c["tags"] = _tags.get(c["clusterArn"], [])+ _recount_cluster(n)+ c.update({+ "runningTasksCount": _clusters[n]["runningTasksCount"],+ "pendingTasksCount": _clusters[n]["pendingTasksCount"],+ "activeServicesCount": _clusters[n]["activeServicesCount"],+ })+ result.append(c)else:- failures.append({"arn": name, "reason": "MISSING"})+ arn = ref if ref.startswith("arn:") else f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:cluster/{ref}"+ failures.append({"arn": arn, "reason": "MISSING"})return json_response({"clusters": result, "failures": failures})def _list_clusters(data):- arns = [c["clusterArn"] for c in _clusters.values()]+ arns = [c["clusterArn"] for c in _clusters.values() if c["status"] == "ACTIVE"]return json_response({"clusterArns": arns})-# ---- Task Definitions ----+def _recount_cluster(cluster_name):+ """Recompute cluster-level counts from live tasks and services."""+ cluster = _clusters.get(cluster_name)+ if not cluster:+ return+ cluster_arn = cluster["clusterArn"]+ running = 0+ pending = 0+ for t in _tasks.values():+ if t.get("clusterArn") != cluster_arn:+ continue+ if t["lastStatus"] == "RUNNING":+ running += 1+ elif t["lastStatus"] == "PENDING":+ pending += 1+ cluster["runningTasksCount"] = running+ cluster["pendingTasksCount"] = pending+ active_svcs = sum(+ 1 for k, s in _services.items()+ if k.startswith(f"{cluster_name}/") and s["status"] == "ACTIVE"+ )+ cluster["activeServicesCount"] = active_svcs+++# ---------------------------------------------------------------------------+# Task Definitions+# ---------------------------------------------------------------------------def _register_task_definition(data):family = data.get("family")if not family:- return error_response_json("ValidationException", "family is required", 400)+ return error_response_json("ClientException", "family is required", 400)++ container_defs = data.get("containerDefinitions", [])+ if not container_defs:+ return error_response_json("ClientException",+ "TaskDefinition must contain at least one container definition.", 400)+ for idx, cdef in enumerate(container_defs):+ if "name" not in cdef:+ return error_response_json("ClientException",+ f"Container definition {idx}: name is required.", 400)+ if "image" not in cdef:+ return error_response_json("ClientException",+ f"Container definition {idx} ({cdef['name']}): image is required.", 400)+ cdef.setdefault("cpu", 0)+ cdef.setdefault("memory", 0)+ cdef.setdefault("memoryReservation", 0)+ cdef.setdefault("essential", True)+ cdef.setdefault("portMappings", [])+ cdef.setdefault("environment", [])+ cdef.setdefault("mountPoints", [])+ cdef.setdefault("volumesFrom", [])+ cdef.setdefault("logConfiguration", None)rev = _task_def_latest.get(family, 0) + 1_task_def_latest[family] = revtd_key = f"{family}:{rev}"arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:task-definition/{td_key}"+ compat = data.get("requiresCompatibilities", ["EC2"])+ network_mode = data.get("networkMode", "awsvpc" if "FARGATE" in compat else "bridge")+td = {"taskDefinitionArn": arn,"family": family,"revision": rev,"status": "ACTIVE",- "containerDefinitions": data.get("containerDefinitions", []),+ "containerDefinitions": container_defs,"volumes": data.get("volumes", []),- "networkMode": data.get("networkMode", "bridge"),- "requiresCompatibilities": data.get("requiresCompatibilities", ["EC2"]),+ "placementConstraints": data.get("placementConstraints", []),+ "networkMode": network_mode,+ "requiresCompatibilities": compat,"cpu": data.get("cpu", "256"),"memory": data.get("memory", "512"),"executionRoleArn": data.get("executionRoleArn", ""),"taskRoleArn": data.get("taskRoleArn", ""),- "registeredAt": time.time(),+ "pidMode": data.get("pidMode", ""),+ "ipcMode": data.get("ipcMode", ""),+ "proxyConfiguration": data.get("proxyConfiguration", None),+ "runtimePlatform": data.get("runtimePlatform", None),+ "ephemeralStorage": data.get("ephemeralStorage", None),+ "registeredAt": _iso(),+ "registeredBy": f"arn:aws:iam::{ACCOUNT_ID}:root",+ "compatibilities": compat + (["EC2"] if "FARGATE" in compat and "EC2" not in compat else []),}_task_defs[td_key] = td- return json_response({"taskDefinition": td, "tags": data.get("tags", [])})++ req_tags = data.get("tags", [])+ if req_tags:+ _tags[arn] = list(req_tags)+ return json_response({"taskDefinition": td, "tags": req_tags})-def _deregister_task_definition(td_ref):+def _deregister_task_definition(data):+ td_ref = data.get("taskDefinition", "")key = _resolve_td_key(td_ref)td = _task_defs.get(key)if not td:- return error_response_json("InvalidParameterException", f"Task definition {td_ref} not found", 400)+ return error_response_json("ClientException",+ f"Unable to describe task definition: {td_ref}", 400)td["status"] = "INACTIVE"+ td["deregisteredAt"] = _iso()return json_response({"taskDefinition": td})-def _describe_task_definition(td_ref):- if isinstance(td_ref, dict):- td_ref = td_ref.get("taskDefinition", "")+def _describe_task_definition(data):+ td_ref = data.get("taskDefinition", "") if isinstance(data, dict) else datakey = _resolve_td_key(td_ref)td = _task_defs.get(key)if not td:- return error_response_json("InvalidParameterException", f"Task definition {td_ref} not found", 400)- return json_response({"taskDefinition": td, "tags": []})+ return error_response_json("ClientException",+ f"Unable to describe task definition: {td_ref}", 400)+ include = set(data.get("include", [])) if isinstance(data, dict) else set()+ resp = {"taskDefinition": td}+ if "TAGS" in include:+ resp["tags"] = _tags.get(td["taskDefinitionArn"], [])+ else:+ resp["tags"] = []+ return json_response(resp)def _list_task_definitions(data):- family = data.get("familyPrefix", "")- status = data.get("status", "ACTIVE")+ family_prefix = data.get("familyPrefix", "")+ status_filter = data.get("status", "ACTIVE")+ sort = data.get("sort", "ASC")arns = [td["taskDefinitionArn"] for td in _task_defs.values()- if (not family or td["family"].startswith(family)) and td["status"] == status+ if (not family_prefix or td["family"].startswith(family_prefix))+ and td["status"] == status_filter]- return json_response({"taskDefinitionArns": arns})-+ if sort == "DESC":+ arns.reverse()+ max_results = data.get("maxResults", 100)+ next_token = data.get("nextToken")+ start = int(next_token) if next_token else 0+ page = arns[start:start + max_results]+ resp = {"taskDefinitionArns": page}+ if start + max_results < len(arns):+ resp["nextToken"] = str(start + max_results)+ return json_response(resp)+++# ---------------------------------------------------------------------------+# Services+# ---------------------------------------------------------------------------++def _make_deployment(task_definition, desired_count, status="PRIMARY"):+ dep_id = f"ecs-svc/{new_uuid().replace('-', '')[:20]}"+ now = _iso()+ return {+ "id": dep_id,+ "status": status,+ "taskDefinition": task_definition,+ "desiredCount": desired_count,+ "runningCount": desired_count if status == "PRIMARY" else 0,+ "pendingCount": 0,+ "failedTasks": 0,+ "launchType": "EC2",+ "createdAt": now,+ "updatedAt": now,+ "rolloutState": "COMPLETED" if status == "PRIMARY" else "IN_PROGRESS",+ "rolloutStateReason": "ECS deployment completed." if status == "PRIMARY" else "",+ }-# ---- Services ----def _create_service(data):- cluster = _resolve_cluster_name(data.get("cluster", "default"))- if cluster not in _clusters:- _create_cluster({"clusterName": cluster})+ cluster_name = _resolve_cluster_name(data.get("cluster", "default"))+ if cluster_name not in _clusters:+ _create_cluster({"clusterName": cluster_name})name = data.get("serviceName")- td_key = _resolve_td_key(data.get("taskDefinition", ""))- arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:service/{cluster}/{name}"- svc_key = f"{cluster}/{name}"-- _services[svc_key] = {- "serviceArn": arn, "serviceName": name, "clusterArn": _clusters[cluster]["clusterArn"],- "taskDefinition": _task_defs.get(td_key, {}).get("taskDefinitionArn", data.get("taskDefinition", "")),- "desiredCount": data.get("desiredCount", 1),- "runningCount": 0, "pendingCount": 0,+ if not name:+ return error_response_json("ClientException", "serviceName is required", 400)++ svc_key = f"{cluster_name}/{name}"+ if svc_key in _services and _services[svc_key]["status"] == "ACTIVE":+ return error_response_json("ServiceAlreadyExists",+ f"Creation of service was not idempotent.", 400)++ td_ref = data.get("taskDefinition", "")+ td_key = _resolve_td_key(td_ref)+ td_arn = _task_defs[td_key]["taskDefinitionArn"] if td_key in _task_defs else td_ref++ desired = data.get("desiredCount", 1)+ arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:service/{cluster_name}/{name}"+ now = _iso()+ launch_type = data.get("launchType", "EC2")++ deployment = _make_deployment(td_arn, desired)+ deployment["launchType"] = launch_type++ svc = {+ "serviceArn": arn,+ "serviceName": name,+ "clusterArn": _clusters[cluster_name]["clusterArn"],+ "taskDefinition": td_arn,+ "desiredCount": desired,+ "runningCount": desired,+ "pendingCount": 0,"status": "ACTIVE",- "launchType": data.get("launchType", "EC2"),+ "launchType": launch_type,+ "platformVersion": data.get("platformVersion", ""),+ "platformFamily": data.get("platformFamily", ""),"networkConfiguration": data.get("networkConfiguration", {}),"loadBalancers": data.get("loadBalancers", []),- "createdAt": time.time(),- "deployments": [],- "events": [],+ "serviceRegistries": data.get("serviceRegistries", []),+ "healthCheckGracePeriodSeconds": data.get("healthCheckGracePeriodSeconds", 0),+ "schedulingStrategy": data.get("schedulingStrategy", "REPLICA"),+ "deploymentController": data.get("deploymentController", {"type": "ECS"}),+ "deploymentConfiguration": data.get("deploymentConfiguration", {+ "maximumPercent": 200,+ "minimumHealthyPercent": 100,+ "deploymentCircuitBreaker": {"enable": False, "rollback": False},+ }),+ "deployments": [deployment],+ "events": [{+ "id": new_uuid(),+ "createdAt": now,+ "message": f"(service {name}) has started 1 tasks: (task placeholder).",+ }],+ "roleArn": data.get("role", ""),+ "createdAt": now,+ "createdBy": f"arn:aws:iam::{ACCOUNT_ID}:root",+ "enableECSManagedTags": data.get("enableECSManagedTags", False),+ "propagateTags": data.get("propagateTags", "NONE"),+ "enableExecuteCommand": data.get("enableExecuteCommand", False),+ "tags": data.get("tags", []),}- _clusters[cluster]["activeServicesCount"] += 1- return json_response({"service": _services[svc_key]})+ _services[svc_key] = svc+ if svc["tags"]:+ _tags[arn] = list(svc["tags"])-def _delete_service(service_name, data):- cluster = _resolve_cluster_name(data.get("cluster", "default"))- svc_key = f"{cluster}/{service_name}"- svc = _services.pop(svc_key, None)+ _recount_cluster(cluster_name)+ return json_response({"service": _sanitize(svc)})+++def _delete_service(data):+ cluster_name = _resolve_cluster_name(data.get("cluster", "default"))+ service_ref = data.get("service", "")+ svc_name = _resolve_service_name(service_ref)+ svc_key = f"{cluster_name}/{svc_name}"+ svc = _services.get(svc_key)if not svc:- return error_response_json("ServiceNotFoundException", f"Service {service_name} not found", 400)- if cluster in _clusters:- _clusters[cluster]["activeServicesCount"] = max(0, _clusters[cluster]["activeServicesCount"] - 1)- return json_response({"service": svc})+ return error_response_json("ServiceNotFoundException",+ f"Service not found.", 400)++ force = data.get("force", False)+ if not force and svc.get("desiredCount", 0) > 0:+ return error_response_json("InvalidParameterException",+ "The service cannot be stopped while it is scaled above 0.", 400)++ svc["status"] = "DRAINING"+ svc["runningCount"] = 0+ svc["desiredCount"] = 0+ _tags.pop(svc["serviceArn"], None)+ del _services[svc_key]++ _recount_cluster(cluster_name)+ return json_response({"service": _sanitize(svc)})def _describe_services(data):- cluster = _resolve_cluster_name(data.get("cluster", "default"))- services = data.get("services", [])+ cluster_name = _resolve_cluster_name(data.get("cluster", "default"))+ refs = data.get("services", [])+ include = set(data.get("include", []))result = []failures = []- for svc_name in services:- svc_key = f"{cluster}/{_resolve_service_name(svc_name)}"+ for ref in refs:+ svc_name = _resolve_service_name(ref)+ svc_key = f"{cluster_name}/{svc_name}"if svc_key in _services:- result.append(_services[svc_key])+ s = dict(_services[svc_key])+ if "TAGS" in include:+ s["tags"] = _tags.get(s["serviceArn"], [])+ result.append(_sanitize(s))else:- failures.append({"arn": svc_name, "reason": "MISSING"})+ arn = ref if ref.startswith("arn:") else \+ f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:service/{cluster_name}/{ref}"+ failures.append({"arn": arn, "reason": "MISSING"})return json_response({"services": result, "failures": failures})-def _update_service(service_name, data):- cluster = _resolve_cluster_name(data.get("cluster", "default"))- svc_key = f"{cluster}/{_resolve_service_name(service_name)}"+def _update_service(data):+ cluster_name = _resolve_cluster_name(data.get("cluster", "default"))+ service_ref = data.get("service", "")+ svc_name = _resolve_service_name(service_ref)+ svc_key = f"{cluster_name}/{svc_name}"svc = _services.get(svc_key)if not svc:- return error_response_json("ServiceNotFoundException", f"Service {service_name} not found", 400)- if "desiredCount" in data:- svc["desiredCount"] = data["desiredCount"]- if "taskDefinition" in data:- svc["taskDefinition"] = data["taskDefinition"]- return json_response({"service": svc})+ return error_response_json("ServiceNotFoundException", "Service not found.", 400)++ changed = False+ new_td = data.get("taskDefinition")+ new_desired = data.get("desiredCount")++ if new_td is not None:+ td_key = _resolve_td_key(new_td)+ td_arn = _task_defs[td_key]["taskDefinitionArn"] if td_key in _task_defs else new_td+ if td_arn != svc["taskDefinition"]:+ for dep in svc["deployments"]:+ if dep["status"] == "PRIMARY":+ dep["status"] = "ACTIVE"+ new_dep = _make_deployment(td_arn, svc["desiredCount"])+ svc["deployments"].insert(0, new_dep)+ svc["taskDefinition"] = td_arn+ changed = True++ if new_desired is not None:+ svc["desiredCount"] = new_desired+ svc["runningCount"] = new_desired+ if svc["deployments"]:+ svc["deployments"][0]["desiredCount"] = new_desired+ svc["deployments"][0]["runningCount"] = new_desired+ svc["deployments"][0]["updatedAt"] = _iso()+ changed = True++ if "networkConfiguration" in data:+ svc["networkConfiguration"] = data["networkConfiguration"]+ if "healthCheckGracePeriodSeconds" in data:+ svc["healthCheckGracePeriodSeconds"] = data["healthCheckGracePeriodSeconds"]+ if "enableExecuteCommand" in data:+ svc["enableExecuteCommand"] = data["enableExecuteCommand"]+ if "deploymentConfiguration" in data:+ svc["deploymentConfiguration"] = data["deploymentConfiguration"]+ if "platformVersion" in data:+ svc["platformVersion"] = data["platformVersion"]+ if "loadBalancers" in data:+ svc["loadBalancers"] = data["loadBalancers"]+ if "capacityProviderStrategy" in data:+ svc["capacityProviderStrategy"] = data["capacityProviderStrategy"]++ if changed:+ svc["events"].insert(0, {+ "id": new_uuid(),+ "createdAt": _iso(),+ "message": f"(service {svc['serviceName']}) has begun draining connections on 1 tasks.",+ })++ _recount_cluster(cluster_name)+ return json_response({"service": _sanitize(svc)})def _list_services(data):- cluster = _resolve_cluster_name(data.get("cluster", "default"))- arns = [s["serviceArn"] for k, s in _services.items() if k.startswith(f"{cluster}/")]+ cluster_name = _resolve_cluster_name(data.get("cluster", "default"))+ launch_type = data.get("launchType")+ scheduling = data.get("schedulingStrategy")+ arns = []+ for k, s in _services.items():+ if not k.startswith(f"{cluster_name}/"):+ continue+ if s["status"] != "ACTIVE":+ continue+ if launch_type and s.get("launchType") != launch_type:+ continue+ if scheduling and s.get("schedulingStrategy") != scheduling:+ continue+ arns.append(s["serviceArn"])return json_response({"serviceArns": arns})-# ---- Tasks ----+# ---------------------------------------------------------------------------+# Tasks+# ---------------------------------------------------------------------------++def _build_task_containers(td, container_overrides):+ """Build the containers list for a task from its task definition."""+ containers = []+ if not td:+ return containers+ for cdef in td.get("containerDefinitions", []):+ env_override = {}+ for ov in container_overrides:+ if ov.get("name") == cdef["name"]:+ for e in ov.get("environment", []):+ env_override[e["name"]] = e["value"]++ env = {e["name"]: e["value"] for e in cdef.get("environment", [])}+ env.update(env_override)++ containers.append({+ "containerArn": f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:container/{new_uuid()}",+ "taskArn": "",+ "name": cdef["name"],+ "image": cdef.get("image", ""),+ "lastStatus": "RUNNING",+ "exitCode": None,+ "networkBindings": [],+ "networkInterfaces": [],+ "cpu": str(cdef.get("cpu", 0)),+ "memory": str(cdef.get("memory") or cdef.get("memoryReservation", 0)),+ "runtimeId": new_uuid()[:12],+ "healthStatus": "UNKNOWN",+ })+ return containers+def _run_task(data):- cluster = _resolve_cluster_name(data.get("cluster", "default"))- if cluster not in _clusters:- _create_cluster({"clusterName": cluster})+ cluster_name = _resolve_cluster_name(data.get("cluster", "default"))+ if cluster_name not in _clusters:+ _create_cluster({"clusterName": cluster_name})td_ref = data.get("taskDefinition", "")td_key = _resolve_td_key(td_ref)td = _task_defs.get(td_key)+ if not td:+ return error_response_json("ClientException",+ f"Unable to find task definition: {td_ref}", 400)count = data.get("count", 1)+ container_overrides = data.get("overrides", {}).get("containerOverrides", [])+ launch_type = data.get("launchType", "EC2")+ group = data.get("group", "")+ started_by = data.get("startedBy", "")+ enable_exec = data.get("enableExecuteCommand", False)+ network_cfg = data.get("networkConfiguration", {})+ req_tags = data.get("tags", [])+tasks = []failures = []for _ in range(count):task_id = new_uuid()- task_arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:task/{cluster}/{task_id}"- container_overrides = data.get("overrides", {}).get("containerOverrides", [])+ task_arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:task/{cluster_name}/{task_id}"+ now = _iso()++ containers = _build_task_containers(td, container_overrides)+ for c in containers:+ c["taskArn"] = task_arntask = {"taskArn": task_arn,- "clusterArn": f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:cluster/{cluster}",- "taskDefinitionArn": td["taskDefinitionArn"] if td else td_ref,+ "clusterArn": _clusters[cluster_name]["clusterArn"],+ "taskDefinitionArn": td["taskDefinitionArn"],+ "containerInstanceArn": f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:container-instance/{cluster_name}/{new_uuid()}",+ "overrides": data.get("overrides", {"containerOverrides": [], "inferenceAcceleratorOverrides": []}),"lastStatus": "RUNNING","desiredStatus": "RUNNING",- "launchType": data.get("launchType", "EC2"),- "cpu": td.get("cpu", "256") if td else "256",- "memory": td.get("memory", "512") if td else "512",- "createdAt": time.time(),- "startedAt": time.time(),- "group": data.get("group", ""),- "containers": [],+ "launchType": launch_type,+ "cpu": td.get("cpu", "256"),+ "memory": td.get("memory", "512"),+ "platformVersion": data.get("platformVersion", ""),+ "platformFamily": "",+ "connectivity": "CONNECTED",+ "connectivityAt": now,+ "pullStartedAt": now,+ "pullStoppedAt": now,+ "createdAt": now,+ "startedAt": now,+ "stoppingAt": None,+ "stoppedAt": None,+ "stoppedReason": "",+ "stopCode": "",+ "group": group,+ "startedBy": started_by,+ "version": 1,+ "containers": containers,+ "attachments": [],+ "availabilityZone": f"{REGION}a",+ "enableExecuteCommand": enable_exec,+ "tags": req_tags,+ "healthStatus": "UNKNOWN",+ "ephemeralStorage": td.get("ephemeralStorage", {"sizeInGiB": 20}),"_docker_ids": [],}- # Try to actually run containers via Dockerdocker_client = _get_docker()if docker_client and td:- for cdef in td.get("containerDefinitions", []):- # Apply overrides+ for i, cdef in enumerate(td.get("containerDefinitions", [])):env_override = {}for ov in container_overrides:if ov.get("name") == cdef["name"]:@@ -380,103 +710,88 @@ def _run_task(data):try:container = docker_client.containers.run(- cdef["image"],- detach=True,+ cdef["image"], detach=True,environment=env,- ports=port_bindings if port_bindings else None,+ ports=port_bindings or None,name=f"ministack-ecs-{task_id[:8]}-{cdef['name']}",labels={"ministack": "ecs", "task_arn": task_arn},)- task["containers"].append({- "name": cdef["name"], "image": cdef["image"],- "lastStatus": "RUNNING", "exitCode": None,- "networkBindings": [],- "containerArn": f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:container/{new_uuid()}",- "_docker_id": container.id,- })task["_docker_ids"].append(container.id)+ if i < len(task["containers"]):+ task["containers"][i]["runtimeId"] = container.id[:12]logger.info(f"ECS: started container {cdef['image']} for task {task_id[:8]}")except Exception as e:logger.warning(f"ECS: Docker run failed for {cdef.get('image')}: {e}")- task["containers"].append({- "name": cdef["name"], "image": cdef["image"],- "lastStatus": "RUNNING", "exitCode": None,- "networkBindings": [],- "containerArn": f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:container/{new_uuid()}",- })- elif td:- for cdef in td.get("containerDefinitions", []):- task["containers"].append({- "name": cdef["name"], "image": cdef["image"],- "lastStatus": "RUNNING", "exitCode": None,- "networkBindings": [],- "containerArn": f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:container/{new_uuid()}",- })_tasks[task_arn] = task- _clusters[cluster]["runningTasksCount"] += 1- tasks.append({k: v for k, v in task.items() if not k.startswith("_")})+ if req_tags:+ _tags[task_arn] = list(req_tags)+ tasks.append(_sanitize(task))+ _recount_cluster(cluster_name)return json_response({"tasks": tasks, "failures": failures})def _stop_task(data):task_ref = data.get("task", "")- cluster = _resolve_cluster_name(data.get("cluster", "default"))- reason = data.get("reason", "")+ cluster_name = _resolve_cluster_name(data.get("cluster", "default"))+ reason = data.get("reason", "Task stopped by user")- # Resolve by ARN or short ID- task = _tasks.get(task_ref)+ task = _resolve_task(task_ref, cluster_name)if not task:- for arn, t in _tasks.items():- if arn.endswith(task_ref):- task = t- task_ref = arn- break+ return error_response_json("InvalidParameterException",+ f"The referenced task was not found.", 400)- if not task:- return error_response_json("InvalidParameterException", f"Task {task_ref} not found", 400)+ if task["lastStatus"] == "STOPPED":+ return json_response({"task": _sanitize(task)})- # Stop Docker containersdocker_client = _get_docker()if docker_client:for docker_id in task.get("_docker_ids", []):try:- container = docker_client.containers.get(docker_id)- container.stop(timeout=5)- container.remove()+ c = docker_client.containers.get(docker_id)+ c.stop(timeout=5)+ c.remove()except Exception as e:logger.warning(f"ECS: failed to stop container {docker_id}: {e}")+ now = _iso()task["lastStatus"] = "STOPPED"task["desiredStatus"] = "STOPPED"- task["stoppedAt"] = time.time()+ task["stoppingAt"] = now+ task["stoppedAt"] = nowtask["stoppedReason"] = reason+ task["stopCode"] = "UserInitiated"+ for c in task.get("containers", []):+ c["lastStatus"] = "STOPPED"+ c["exitCode"] = 0- cluster_name = _resolve_cluster_name(cluster)- if cluster_name in _clusters:- _clusters[cluster_name]["runningTasksCount"] = max(0, _clusters[cluster_name]["runningTasksCount"] - 1)+ cname = _cluster_name_from_arn(task.get("clusterArn", ""))+ if cname:+ _recount_cluster(cname)- return json_response({"task": {k: v for k, v in task.items() if not k.startswith("_")}})+ return json_response({"task": _sanitize(task)})def _describe_tasks(data):- cluster = _resolve_cluster_name(data.get("cluster", "default"))+ cluster_name = _resolve_cluster_name(data.get("cluster", "default"))task_refs = data.get("tasks", [])+ include = set(data.get("include", []))result = []failures = []for ref in task_refs:- task = _tasks.get(ref)- if not task:- for arn, t in _tasks.items():- if arn.endswith(ref):- task = t- break+ task = _resolve_task(ref, cluster_name)if task:+ t = _sanitize(task)+ if "TAGS" in include:+ t["tags"] = _tags.get(task["taskArn"], [])+ result.append(t)_maybe_mark_stopped(task)result.append({k: v for k, v in task.items() if not k.startswith("_")})else:- failures.append({"arn": ref, "reason": "MISSING"})+ arn = ref if ref.startswith("arn:") else \+ f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:task/{cluster_name}/{ref}"+ failures.append({"arn": arn, "reason": "MISSING"})return json_response({"tasks": result, "failures": failures})@@ -521,40 +836,381 @@ def _maybe_mark_stopped(task):def _list_tasks(data):- cluster = _resolve_cluster_name(data.get("cluster", "default"))- cluster_arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:cluster/{cluster}"- status = data.get("desiredStatus", "RUNNING")- arns = [- arn for arn, t in _tasks.items()- if t.get("clusterArn") == cluster_arn and t.get("desiredStatus") == status+ cluster_name = _resolve_cluster_name(data.get("cluster", "default"))+ cluster_arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:cluster/{cluster_name}"+ status_filter = data.get("desiredStatus", "RUNNING")+ family = data.get("family", "")+ service_name = data.get("serviceName", "")+ started_by = data.get("startedBy", "")++ arns = []+ for arn, t in _tasks.items():+ if t.get("clusterArn") != cluster_arn:+ continue+ if t.get("desiredStatus") != status_filter:+ continue+ if family:+ td_arn = t.get("taskDefinitionArn", "")+ if f"/{family}:" not in td_arn:+ continue+ if service_name and t.get("group") != f"service:{service_name}":+ if t.get("startedBy") != service_name:+ continue+ if started_by and t.get("startedBy") != started_by:+ continue+ arns.append(arn)++ max_results = data.get("maxResults", 100)+ next_token = data.get("nextToken")+ start = int(next_token) if next_token else 0+ page = arns[start:start + max_results]+ resp = {"taskArns": page}+ if start + max_results < len(arns):+ resp["nextToken"] = str(start + max_results)+ return json_response(resp)+++# ---------------------------------------------------------------------------+# Tags+# ---------------------------------------------------------------------------++def _tag_resource(data):+ arn = data.get("resourceArn", "")+ new_tags = data.get("tags", [])+ if not arn:+ return error_response_json("InvalidParameterException", "resourceArn is required", 400)+ existing = _tags.get(arn, [])+ existing_keys = {t["key"]: i for i, t in enumerate(existing)}+ for tag in new_tags:+ k = tag.get("key", "")+ if k in existing_keys:+ existing[existing_keys[k]] = tag+ else:+ existing.append(tag)+ existing_keys[k] = len(existing) - 1+ _tags[arn] = existing+ return json_response({})+++def _untag_resource(data):+ arn = data.get("resourceArn", "")+ keys_to_remove = set(data.get("tagKeys", []))+ if not arn:+ return error_response_json("InvalidParameterException", "resourceArn is required", 400)+ existing = _tags.get(arn, [])+ _tags[arn] = [t for t in existing if t.get("key") not in keys_to_remove]+ return json_response({})+++def _list_tags_for_resource(data):+ arn = data.get("resourceArn", "")+ if not arn:+ return error_response_json("InvalidParameterException", "resourceArn is required", 400)+ return json_response({"tags": _tags.get(arn, [])})+++# ---------------------------------------------------------------------------+# Stubs+# ---------------------------------------------------------------------------++def _execute_command(data):+ cluster_name = _resolve_cluster_name(data.get("cluster", "default"))+ task_ref = data.get("task", "")+ task = _resolve_task(task_ref, cluster_name)+ if not task:+ return error_response_json("InvalidParameterException",+ "The referenced task was not found.", 400)+ container_name = data.get("container", "")+ if not container_name and task.get("containers"):+ container_name = task["containers"][0]["name"]+ return json_response({+ "clusterArn": task["clusterArn"],+ "taskArn": task["taskArn"],+ "containerArn": next(+ (c["containerArn"] for c in task.get("containers", []) if c["name"] == container_name),+ "",+ ),+ "containerName": container_name,+ "interactive": data.get("interactive", True),+ "session": {+ "sessionId": new_uuid(),+ "streamUrl": f"wss://ssmmessages.{REGION}.amazonaws.com/v1/data-channel/{new_uuid()}",+ "tokenValue": new_uuid(),+ },+ })+++def _list_account_settings(data):+ name = data.get("name", "")+ effective = data.get("effectiveSettings", False)+ settings = []+ all_names = [+ "serviceLongArnFormat", "taskLongArnFormat",+ "containerInstanceLongArnFormat", "awsvpcTrunking",+ "containerInsights", "fargateTaskRetirementWaitPeriod",+ "dualStackIPv6", "fargateFIPSMode", "tagResourceAuthorization",+ "guardDutyActivate",+ ]+ for setting_name in all_names:+ if name and setting_name != name:+ continue+ settings.append({+ "name": setting_name,+ "value": _account_settings.get(setting_name, "enabled"),+ "principalArn": f"arn:aws:iam::{ACCOUNT_ID}:root",+ "type": "user" if setting_name in _account_settings else "aws",+ })+ return json_response({"settings": settings})+++def _put_account_setting(data):+ name = data.get("name", "")+ value = data.get("value", "enabled")+ if not name:+ return error_response_json("InvalidParameterException", "name is required", 400)+ _account_settings[name] = value+ return json_response({"setting": {+ "name": name,+ "value": value,+ "principalArn": f"arn:aws:iam::{ACCOUNT_ID}:root",+ "type": "user",+ }})+++def _describe_capacity_providers(data):+ names = data.get("capacityProviders", [])+ include = data.get("include", [])+ providers = []+ defaults = [+ {"name": "FARGATE", "status": "ACTIVE", "autoScalingGroupProvider": {}},+ {"name": "FARGATE_SPOT", "status": "ACTIVE", "autoScalingGroupProvider": {}},]- return json_response({"taskArns": arns})+ for p in defaults:+ if not names or p["name"] in names:+ cp = {+ "capacityProviderArn": f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:capacity-provider/{p['name']}",+ "name": p["name"],+ "status": p["status"],+ "autoScalingGroupProvider": p["autoScalingGroupProvider"],+ "updateStatus": "UPDATE_COMPLETE",+ }+ if "TAGS" in include:+ cp["tags"] = _tags.get(cp["capacityProviderArn"], [])+ providers.append(cp)++ for cp_name, cp in _capacity_providers.items():+ if not names or cp_name in names:+ entry = dict(cp)+ if "TAGS" in include:+ entry["tags"] = _tags.get(cp["capacityProviderArn"], [])+ providers.append(entry)++ return json_response({"capacityProviders": providers})+++def _create_capacity_provider(data):+ name = data.get("name", "")+ if not name:+ return error_response_json("InvalidParameterException", "name is required", 400)+ if name in _capacity_providers:+ return error_response_json("InvalidParameterException",+ f"Capacity provider {name} already exists.", 400)++ arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:capacity-provider/{name}"+ asg_provider = data.get("autoScalingGroupProvider", {})++ cp = {+ "capacityProviderArn": arn,+ "name": name,+ "status": "ACTIVE",+ "autoScalingGroupProvider": {+ "autoScalingGroupArn": asg_provider.get("autoScalingGroupArn", ""),+ "managedScaling": asg_provider.get("managedScaling", {+ "status": "DISABLED",+ "targetCapacity": 100,+ "minimumScalingStepSize": 1,+ "maximumScalingStepSize": 10000,+ "instanceWarmupPeriod": 300,+ }),+ "managedTerminationProtection": asg_provider.get("managedTerminationProtection", "DISABLED"),+ },+ "updateStatus": "UPDATE_COMPLETE",+ "tags": data.get("tags", []),+ }+ _capacity_providers[name] = cp++ if cp["tags"]:+ _tags[arn] = list(cp["tags"])++ return json_response({"capacityProvider": cp})-# ---- Helpers ----+def _delete_capacity_provider(data):+ name = data.get("capacityProvider", "")+ if name.startswith("arn:"):+ name = name.split("/")[-1]++ cp = _capacity_providers.pop(name, None)+ if not cp:+ return error_response_json("InvalidParameterException",+ f"Capacity provider {name} not found.", 400)++ _tags.pop(cp.get("capacityProviderArn", ""), None)+ cp["status"] = "INACTIVE"+ return json_response({"capacityProvider": cp})+++def _put_cluster_capacity_providers(data):+ cluster_name = _resolve_cluster_name(data.get("cluster", "default"))+ cluster = _clusters.get(cluster_name)+ if not cluster:+ return error_response_json("ClusterNotFoundException", "Cluster not found.", 400)++ cluster["capacityProviders"] = data.get("capacityProviders", [])+ cluster["defaultCapacityProviderStrategy"] = data.get("defaultCapacityProviderStrategy", [])++ return json_response({"cluster": cluster})+++def _update_cluster(data):+ cluster_name = _resolve_cluster_name(data.get("cluster", "default"))+ cluster = _clusters.get(cluster_name)+ if not cluster:+ return error_response_json("ClusterNotFoundException", "Cluster not found.", 400)++ if "configuration" in data:+ cluster["configuration"] = data["configuration"]+ if "settings" in data:+ cluster["settings"] = data["settings"]+ if "serviceConnectDefaults" in data:+ cluster["serviceConnectDefaults"] = data["serviceConnectDefaults"]++ return json_response({"cluster": cluster})+++def _update_cluster_settings(data):+ cluster_name = _resolve_cluster_name(data.get("cluster", "default"))+ cluster = _clusters.get(cluster_name)+ if not cluster:+ return error_response_json("ClusterNotFoundException", "Cluster not found.", 400)++ settings = data.get("settings", [])+ if settings:+ cluster["settings"] = settings++ return json_response({"cluster": cluster})+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------def _resolve_cluster_name(ref):if not ref:return "default"+ if ref.startswith("arn:"):+ return ref.split("/")[-1]if "/" in ref:return ref.split("/")[-1]return refdef _resolve_service_name(ref):+ if ref.startswith("arn:"):+ return ref.split("/")[-1]if "/" in ref:return ref.split("/")[-1]return refdef _resolve_td_key(ref):- """Resolve task definition ARN or family[:revision] to internal key."""if not ref:return ""if "task-definition/" in ref:ref = ref.split("task-definition/")[-1]if ":" not in ref:- # Latest revision- rev = _task_def_latest.get(ref, 1)+ rev = _task_def_latest.get(ref)+ if rev is None:+ return refreturn f"{ref}:{rev}"return ref+++def _resolve_task(ref, cluster_name="default"):+ """Look up a task by full ARN or short ID, optionally scoped to a cluster."""+ task = _tasks.get(ref)+ if task:+ return task+ cluster_arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:cluster/{cluster_name}"+ for arn, t in _tasks.items():+ if t.get("clusterArn") != cluster_arn:+ continue+ if arn.endswith(f"/{ref}") or arn.endswith(ref):+ return t+ for arn, t in _tasks.items():+ if arn.endswith(f"/{ref}") or arn.endswith(ref):+ return t+ return None+++def _cluster_name_from_arn(arn):+ if not arn:+ return ""+ return arn.split("/")[-1] if "/" in arn else arn+++def _sanitize(obj):+ """Remove internal keys (prefixed with _) from a dict for API responses."""+ if isinstance(obj, dict):+ return {k: _sanitize(v) for k, v in obj.items() if not k.startswith("_")}+ if isinstance(obj, list):+ return [_sanitize(i) for i in obj]+ return obj+++# ---------------------------------------------------------------------------+# Action map (X-Amz-Target dispatch)+# ---------------------------------------------------------------------------++_ACTION_MAP = {+ "CreateCluster": _create_cluster,+ "DeleteCluster": _delete_cluster,+ "DescribeClusters": _describe_clusters,+ "ListClusters": _list_clusters,+ "UpdateCluster": _update_cluster,+ "UpdateClusterSettings": _update_cluster_settings,+ "RegisterTaskDefinition": _register_task_definition,+ "DeregisterTaskDefinition": _deregister_task_definition,+ "DescribeTaskDefinition": _describe_task_definition,+ "ListTaskDefinitions": _list_task_definitions,+ "CreateService": _create_service,+ "DeleteService": _delete_service,+ "DescribeServices": _describe_services,+ "UpdateService": _update_service,+ "ListServices": _list_services,+ "RunTask": _run_task,+ "StopTask": _stop_task,+ "DescribeTasks": _describe_tasks,+ "ListTasks": _list_tasks,+ "TagResource": _tag_resource,+ "UntagResource": _untag_resource,+ "ListTagsForResource": _list_tags_for_resource,+ "ExecuteCommand": _execute_command,+ "ListAccountSettings": _list_account_settings,+ "PutAccountSetting": _put_account_setting,+ "CreateCapacityProvider": _create_capacity_provider,+ "DeleteCapacityProvider": _delete_capacity_provider,+ "DescribeCapacityProviders": _describe_capacity_providers,+ "PutClusterCapacityProviders": _put_cluster_capacity_providers,+}+++def reset():+ _clusters.clear()+ _task_defs.clear()+ _task_def_latest.clear()+ _services.clear()+ _tasks.clear()+ _tags.clear()+ _account_settings.clear()+ _capacity_providers.clear()diff --git a/services/elasticache.py b/services/elasticache.pyindex 93694714..72312e41 100644--- a/services/elasticache.py+++ b/services/elasticache.py@@ -2,10 +2,19 @@ElastiCache Service Emulator.Query API (Action=...) for control plane.Supports: CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters,+ ModifyCacheCluster, RebootCacheCluster,CreateReplicationGroup, DeleteReplicationGroup, DescribeReplicationGroups,- CreateCacheSubnetGroup, DescribeCacheSubnetGroups,- CreateCacheParameterGroup, DescribeCacheParameterGroups,- ListTagsForResource, AddTagsToResource.+ ModifyReplicationGroup, IncreaseReplicaCount, DecreaseReplicaCount,+ CreateCacheSubnetGroup, DescribeCacheSubnetGroups, DeleteCacheSubnetGroup,+ ModifyCacheSubnetGroup,+ CreateCacheParameterGroup, DescribeCacheParameterGroups, DeleteCacheParameterGroup,+ DescribeCacheParameters, ModifyCacheParameterGroup, ResetCacheParameterGroup,+ CreateUser, DescribeUsers, DeleteUser, ModifyUser,+ CreateUserGroup, DescribeUserGroups, DeleteUserGroup, ModifyUserGroup,+ DescribeCacheEngineVersions,+ ListTagsForResource, AddTagsToResource, RemoveTagsFromResource,+ CreateSnapshot, DeleteSnapshot, DescribeSnapshots,+ DescribeEvents.When Docker is available, CreateCacheCluster spins up a real Redis/Memcached container.Otherwise returns localhost:6379 (assumes Redis sidecar in docker-compose).@@ -30,9 +39,17 @@ _clusters: dict = {}_replication_groups: dict = {}_subnet_groups: dict = {}_param_groups: dict = {}+_param_group_params: dict = {} # group_name -> {param_name -> param_dict}+_tags: dict = {} # arn -> [{"Key": ..., "Value": ...}, ...]+_snapshots: dict = {}+_users: dict = {}+_user_groups: dict = {}+_events: list = []_port_counter = [BASE_PORT]_docker = None++def _get_docker():global _dockerif _docker is None:@@ -44,6 +61,37 @@ def _get_docker():return _docker+def _arn_cluster(cluster_id):+ return f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:cluster:{cluster_id}"+++def _arn_replication_group(rg_id):+ return f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:replicationgroup:{rg_id}"+++def _arn_subnet_group(name):+ return f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:subnetgroup:{name}"+++def _arn_param_group(name):+ return f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:parametergroup:{name}"+++def _arn_snapshot(name):+ return f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:snapshot:{name}"+++def _record_event(source_id, source_type, message):+ _events.append({+ "SourceIdentifier": source_id,+ "SourceType": source_type,+ "Message": message,+ "Date": time.time(),+ })+ if len(_events) > 500:+ _events[:] = _events[-500:]++async def handle_request(method, path, headers, body, query_params):params = dict(query_params)if method == "POST" and body:@@ -63,16 +111,34 @@ async def handle_request(method, path, headers, body, query_params):"DeleteReplicationGroup": _delete_replication_group,"DescribeReplicationGroups": _describe_replication_groups,"ModifyReplicationGroup": _modify_replication_group,+ "IncreaseReplicaCount": _increase_replica_count,+ "DecreaseReplicaCount": _decrease_replica_count,"CreateCacheSubnetGroup": _create_subnet_group,"DescribeCacheSubnetGroups": _describe_subnet_groups,"DeleteCacheSubnetGroup": _delete_subnet_group,+ "ModifyCacheSubnetGroup": _modify_subnet_group,"CreateCacheParameterGroup": _create_param_group,"DescribeCacheParameterGroups": _describe_param_groups,"DeleteCacheParameterGroup": _delete_param_group,+ "DescribeCacheParameters": _describe_cache_parameters,+ "ModifyCacheParameterGroup": _modify_cache_parameter_group,+ "ResetCacheParameterGroup": _reset_cache_parameter_group,"DescribeCacheEngineVersions": _describe_engine_versions,+ "CreateUser": _create_user,+ "DescribeUsers": _describe_users,+ "DeleteUser": _delete_user,+ "ModifyUser": _modify_user,+ "CreateUserGroup": _create_user_group,+ "DescribeUserGroups": _describe_user_groups,+ "DeleteUserGroup": _delete_user_group,+ "ModifyUserGroup": _modify_user_group,"ListTagsForResource": _list_tags,"AddTagsToResource": _add_tags,"RemoveTagsFromResource": _remove_tags,+ "CreateSnapshot": _create_snapshot,+ "DeleteSnapshot": _delete_snapshot,+ "DescribeSnapshots": _describe_snapshots,+ "DescribeEvents": _describe_events,}handler = handlers.get(action)@@ -81,6 +147,8 @@ async def handle_request(method, path, headers, body, query_params):return handler(params)+# ---- Cache Clusters ----+def _create_cache_cluster(p):cluster_id = _p(p, "CacheClusterId")engine = _p(p, "Engine") or "redis"@@ -91,12 +159,11 @@ def _create_cache_cluster(p):if cluster_id in _clusters:return _error("CacheClusterAlreadyExists", f"Cluster {cluster_id} already exists", 400)- arn = f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:cluster:{cluster_id}"+ arn = _arn_cluster(cluster_id)endpoint_host = REDIS_DEFAULT_HOSTendpoint_port = REDIS_DEFAULT_PORT if engine == "redis" else 11211docker_container_id = None- # Try to spin up a real containerdocker_client = _get_docker()if docker_client:host_port = _port_counter[0]@@ -125,6 +192,9 @@ def _create_cache_cluster(p):endpoint_host = REDIS_DEFAULT_HOSTendpoint_port = REDIS_DEFAULT_PORT+ subnet_group = _p(p, "CacheSubnetGroupName") or "default"+ param_group_name = _p(p, "CacheParameterGroupName") or f"default.{engine}{engine_version[:3]}"+_clusters[cluster_id] = {"CacheClusterId": cluster_id,"CacheClusterArn": arn,@@ -135,13 +205,17 @@ def _create_cache_cluster(p):"NumCacheNodes": num_nodes,"CacheClusterCreateTime": time.time(),"PreferredAvailabilityZone": f"{REGION}a",- "CacheParameterGroup": {"CacheParameterGroupName": f"default.{engine}{engine_version[:3]}", "ParameterApplyStatus": "in-sync"},- "CacheSubnetGroupName": _p(p, "CacheSubnetGroupName") or "default",+ "CacheParameterGroup": {+ "CacheParameterGroupName": param_group_name,+ "ParameterApplyStatus": "in-sync",+ },+ "CacheSubnetGroupName": subnet_group,"AutoMinorVersionUpgrade": True,"SecurityGroups": [],- "ReplicationGroupId": "",- "SnapshotRetentionLimit": 0,- "SnapshotWindow": "05:00-06:00",+ "ReplicationGroupId": _p(p, "ReplicationGroupId") or "",+ "SnapshotRetentionLimit": int(_p(p, "SnapshotRetentionLimit") or "0"),+ "SnapshotWindow": _p(p, "SnapshotWindow") or "05:00-06:00",+ "PreferredMaintenanceWindow": _p(p, "PreferredMaintenanceWindow") or "sun:05:00-sun:06:00","CacheNodes": [{"CacheNodeId": f"{i:04d}",@@ -156,6 +230,12 @@ def _create_cache_cluster(p):"_docker_container_id": docker_container_id,"_endpoint": {"Address": endpoint_host, "Port": endpoint_port},}++ tags = _extract_tags(p)+ if tags:+ _tags[arn] = tags++ _record_event(cluster_id, "cache-cluster", "Cache cluster created")return _xml_cluster_response("CreateCacheClusterResponse", "CreateCacheClusterResult", _clusters[cluster_id])@@ -176,6 +256,8 @@ def _delete_cache_cluster(p):cluster["CacheClusterStatus"] = "deleting"del _clusters[cluster_id]+ _tags.pop(cluster.get("CacheClusterArn", ""), None)+ _record_event(cluster_id, "cache-cluster", "Cache cluster deleted")return _xml_cluster_response("DeleteCacheClusterResponse", "DeleteCacheClusterResult", cluster)@@ -198,8 +280,38 @@ def _modify_cache_cluster(p):cluster = _clusters.get(cluster_id)if not cluster:return _error("CacheClusterNotFound", f"Cluster {cluster_id} not found", 404)+if _p(p, "NumCacheNodes"):- cluster["NumCacheNodes"] = int(_p(p, "NumCacheNodes"))+ new_count = int(_p(p, "NumCacheNodes"))+ old_count = cluster["NumCacheNodes"]+ cluster["NumCacheNodes"] = new_count+ ep = cluster.get("_endpoint", {})+ if new_count > old_count:+ for i in range(old_count + 1, new_count + 1):+ cluster["CacheNodes"].append({+ "CacheNodeId": f"{i:04d}",+ "CacheNodeStatus": "available",+ "CacheNodeCreateTime": time.time(),+ "Endpoint": {"Address": ep.get("Address", "localhost"), "Port": ep.get("Port", 6379)},+ "ParameterGroupStatus": "in-sync",+ "SourceCacheNodeId": "",+ })+ elif new_count < old_count:+ cluster["CacheNodes"] = cluster["CacheNodes"][:new_count]+ if _p(p, "CacheNodeType"):+ cluster["CacheNodeType"] = _p(p, "CacheNodeType")+ if _p(p, "EngineVersion"):+ cluster["EngineVersion"] = _p(p, "EngineVersion")+ if _p(p, "SnapshotRetentionLimit"):+ cluster["SnapshotRetentionLimit"] = int(_p(p, "SnapshotRetentionLimit"))+ if _p(p, "SnapshotWindow"):+ cluster["SnapshotWindow"] = _p(p, "SnapshotWindow")+ if _p(p, "PreferredMaintenanceWindow"):+ cluster["PreferredMaintenanceWindow"] = _p(p, "PreferredMaintenanceWindow")+ if _p(p, "CacheParameterGroupName"):+ cluster["CacheParameterGroup"]["CacheParameterGroupName"] = _p(p, "CacheParameterGroupName")++ _record_event(cluster_id, "cache-cluster", "Cache cluster modified")return _xml_cluster_response("ModifyCacheClusterResponse", "ModifyCacheClusterResult", cluster)@@ -208,36 +320,76 @@ def _reboot_cache_cluster(p):cluster = _clusters.get(cluster_id)if not cluster:return _error("CacheClusterNotFound", f"Cluster {cluster_id} not found", 404)+ _record_event(cluster_id, "cache-cluster", "Cache cluster rebooted")return _xml_cluster_response("RebootCacheClusterResponse", "RebootCacheClusterResult", cluster)+# ---- Replication Groups ----+def _create_replication_group(p):rg_id = _p(p, "ReplicationGroupId")- desc = _p(p, "ReplicationGroupDescription")- arn = f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:replicationgroup:{rg_id}"+ desc = _p(p, "ReplicationGroupDescription") or ""+ node_type = _p(p, "CacheNodeType") or "cache.t3.micro"+ num_node_groups = int(_p(p, "NumNodeGroups") or "1")+ replicas_per_node_group = int(_p(p, "ReplicasPerNodeGroup") or "1")+ arn = _arn_replication_group(rg_id)endpoint_host = REDIS_DEFAULT_HOSTendpoint_port = REDIS_DEFAULT_PORT+ if rg_id in _replication_groups:+ return _error("ReplicationGroupAlreadyExistsFault",+ f"Replication group {rg_id} already exists", 400)++ node_groups = []+ for ng_idx in range(1, num_node_groups + 1):+ ng_id = f"{ng_idx:04d}"+ members = []+ for r in range(replicas_per_node_group + 1):+ role = "primary" if r == 0 else "replica"+ members.append({+ "CacheClusterId": f"{rg_id}-{ng_id}-{r + 1:03d}",+ "CacheNodeId": "0001",+ "CurrentRole": role,+ "PreferredAvailabilityZone": f"{REGION}{'abcdef'[r % 6]}",+ "ReadEndpoint": {"Address": endpoint_host, "Port": endpoint_port},+ })+ node_groups.append({+ "NodeGroupId": ng_id,+ "Status": "available",+ "PrimaryEndpoint": {"Address": endpoint_host, "Port": endpoint_port},+ "ReaderEndpoint": {"Address": endpoint_host, "Port": endpoint_port},+ "NodeGroupMembers": members,+ })+_replication_groups[rg_id] = {"ReplicationGroupId": rg_id,"Description": desc,"Status": "available","MemberClusters": [],- "NodeGroups": [{"NodeGroupId": "0001", "Status": "available",- "PrimaryEndpoint": {"Address": endpoint_host, "Port": endpoint_port},- "ReaderEndpoint": {"Address": endpoint_host, "Port": endpoint_port}}],- "SnapshotRetentionLimit": 0,- "SnapshotWindow": "05:00-06:00",- "ClusterEnabled": False,- "CacheNodeType": _p(p, "CacheNodeType") or "cache.t3.micro",- "AuthTokenEnabled": False,- "TransitEncryptionEnabled": False,- "AtRestEncryptionEnabled": False,+ "NodeGroups": node_groups,+ "SnapshottingClusterId": "",+ "SnapshotRetentionLimit": int(_p(p, "SnapshotRetentionLimit") or "0"),+ "SnapshotWindow": _p(p, "SnapshotWindow") or "05:00-06:00",+ "ClusterEnabled": num_node_groups > 1,+ "CacheNodeType": node_type,+ "AuthTokenEnabled": _p(p, "AuthToken") != "",+ "TransitEncryptionEnabled": _p(p, "TransitEncryptionEnabled", "false").lower() == "true",+ "AtRestEncryptionEnabled": _p(p, "AtRestEncryptionEnabled", "false").lower() == "true",+ "AutomaticFailover": _p(p, "AutomaticFailoverEnabled", "false"),+ "MultiAZ": _p(p, "MultiAZEnabled", "false"),+ "ConfigurationEndpoint": {"Address": endpoint_host, "Port": endpoint_port} if num_node_groups > 1 else None,"ARN": arn,+ "_num_node_groups": num_node_groups,+ "_replicas_per_node_group": replicas_per_node_group,}- members = _rg_xml(_replication_groups[rg_id])++ tags = _extract_tags(p)+ if tags:+ _tags[arn] = tags++ _record_event(rg_id, "replication-group", "Replication group created")return _xml(200, "CreateReplicationGroupResponse",- f"<CreateReplicationGroupResult><ReplicationGroup>{members}</ReplicationGroup></CreateReplicationGroupResult>")+ f"<CreateReplicationGroupResult><ReplicationGroup>{_rg_xml(_replication_groups[rg_id])}</ReplicationGroup></CreateReplicationGroupResult>")def _delete_replication_group(p):@@ -245,9 +397,10 @@ def _delete_replication_group(p):rg = _replication_groups.pop(rg_id, None)if not rg:return _error("ReplicationGroupNotFoundFault", f"Replication group {rg_id} not found", 404)- members = _rg_xml(rg)+ _tags.pop(rg.get("ARN", ""), None)+ _record_event(rg_id, "replication-group", "Replication group deleted")return _xml(200, "DeleteReplicationGroupResponse",- f"<DeleteReplicationGroupResult><ReplicationGroup>{members}</ReplicationGroup></DeleteReplicationGroupResult>")+ f"<DeleteReplicationGroupResult><ReplicationGroup>{_rg_xml(rg)}</ReplicationGroup></DeleteReplicationGroupResult>")def _describe_replication_groups(p):@@ -269,106 +422,824 @@ def _modify_replication_group(p):rg = _replication_groups.get(rg_id)if not rg:return _error("ReplicationGroupNotFoundFault", f"Replication group {rg_id} not found", 404)++ if _p(p, "ReplicationGroupDescription"):+ rg["Description"] = _p(p, "ReplicationGroupDescription")+ if _p(p, "CacheNodeType"):+ rg["CacheNodeType"] = _p(p, "CacheNodeType")+ if _p(p, "SnapshotRetentionLimit"):+ rg["SnapshotRetentionLimit"] = int(_p(p, "SnapshotRetentionLimit"))+ if _p(p, "SnapshotWindow"):+ rg["SnapshotWindow"] = _p(p, "SnapshotWindow")+ if _p(p, "AutomaticFailoverEnabled"):+ rg["AutomaticFailover"] = _p(p, "AutomaticFailoverEnabled")+ if _p(p, "MultiAZEnabled"):+ rg["MultiAZ"] = _p(p, "MultiAZEnabled")+ if _p(p, "EngineVersion"):+ rg["EngineVersion"] = _p(p, "EngineVersion")+ if _p(p, "CacheParameterGroupName"):+ rg["CacheParameterGroupName"] = _p(p, "CacheParameterGroupName")++ _record_event(rg_id, "replication-group", "Replication group modified")return _xml(200, "ModifyReplicationGroupResponse",f"<ModifyReplicationGroupResult><ReplicationGroup>{_rg_xml(rg)}</ReplicationGroup></ModifyReplicationGroupResult>")+def _increase_replica_count(p):+ rg_id = _p(p, "ReplicationGroupId")+ rg = _replication_groups.get(rg_id)+ if not rg:+ return _error("ReplicationGroupNotFoundFault", f"Replication group {rg_id} not found", 404)++ new_count = int(_p(p, "NewReplicaCount") or "0")+ if new_count <= 0:+ return _error("InvalidParameterValue", "NewReplicaCount must be positive", 400)++ endpoint_host = REDIS_DEFAULT_HOST+ endpoint_port = REDIS_DEFAULT_PORT+ for ng in rg["NodeGroups"]:+ current = len(ng.get("NodeGroupMembers", []))+ target = new_count + 1 # +1 for primary+ while current < target:+ current += 1+ ng["NodeGroupMembers"].append({+ "CacheClusterId": f"{rg_id}-{ng['NodeGroupId']}-{current:03d}",+ "CacheNodeId": "0001",+ "CurrentRole": "replica",+ "PreferredAvailabilityZone": f"{REGION}a",+ "ReadEndpoint": {"Address": endpoint_host, "Port": endpoint_port},+ })+ rg["_replicas_per_node_group"] = new_count++ _record_event(rg_id, "replication-group", "Replica count increased")+ return _xml(200, "IncreaseReplicaCountResponse",+ f"<IncreaseReplicaCountResult><ReplicationGroup>{_rg_xml(rg)}</ReplicationGroup></IncreaseReplicaCountResult>")+++def _decrease_replica_count(p):+ rg_id = _p(p, "ReplicationGroupId")+ rg = _replication_groups.get(rg_id)+ if not rg:+ return _error("ReplicationGroupNotFoundFault", f"Replication group {rg_id} not found", 404)++ new_count = int(_p(p, "NewReplicaCount") or "0")+ if new_count < 0:+ return _error("InvalidParameterValue", "NewReplicaCount must be non-negative", 400)++ for ng in rg["NodeGroups"]:+ target = new_count + 1+ members = ng.get("NodeGroupMembers", [])+ if len(members) > target:+ ng["NodeGroupMembers"] = members[:target]+ rg["_replicas_per_node_group"] = new_count++ _record_event(rg_id, "replication-group", "Replica count decreased")+ return _xml(200, "DecreaseReplicaCountResponse",+ f"<DecreaseReplicaCountResult><ReplicationGroup>{_rg_xml(rg)}</ReplicationGroup></DecreaseReplicaCountResult>")+++# ---- Subnet Groups ----+def _create_subnet_group(p):name = _p(p, "CacheSubnetGroupName")- _subnet_groups[name] = {"CacheSubnetGroupName": name, "CacheSubnetGroupDescription": _p(p, "CacheSubnetGroupDescription")}+ desc = _p(p, "CacheSubnetGroupDescription") or ""+ arn = _arn_subnet_group(name)++ subnets = []+ idx = 1+ while _p(p, f"SubnetIds.member.{idx}"):+ subnets.append({+ "SubnetIdentifier": _p(p, f"SubnetIds.member.{idx}"),+ "SubnetAvailabilityZone": {"Name": f"{REGION}{'abcdef'[(idx - 1) % 6]}"},+ })+ idx += 1++ _subnet_groups[name] = {+ "CacheSubnetGroupName": name,+ "CacheSubnetGroupDescription": desc,+ "VpcId": "vpc-00000000",+ "Subnets": subnets,+ "ARN": arn,+ }return _xml(200, "CreateCacheSubnetGroupResponse",- f"<CreateCacheSubnetGroupResult><CacheSubnetGroup><CacheSubnetGroupName>{name}</CacheSubnetGroupName></CacheSubnetGroup></CreateCacheSubnetGroupResult>")+ f"<CreateCacheSubnetGroupResult><CacheSubnetGroup>"+ f"<CacheSubnetGroupName>{name}</CacheSubnetGroupName>"+ f"<CacheSubnetGroupDescription>{desc}</CacheSubnetGroupDescription>"+ f"<ARN>{arn}</ARN>"+ f"</CacheSubnetGroup></CreateCacheSubnetGroupResult>")def _describe_subnet_groups(p):name = _p(p, "CacheSubnetGroupName")groups = [_subnet_groups[name]] if name and name in _subnet_groups else list(_subnet_groups.values())- members = "".join(f"<member><CacheSubnetGroupName>{g['CacheSubnetGroupName']}</CacheSubnetGroupName></member>" for g in groups)+ members = "".join(+ f"<member><CacheSubnetGroupName>{g['CacheSubnetGroupName']}</CacheSubnetGroupName>"+ f"<CacheSubnetGroupDescription>{g.get('CacheSubnetGroupDescription', '')}</CacheSubnetGroupDescription>"+ f"<ARN>{g.get('ARN', '')}</ARN></member>"+ for g in groups+ )return _xml(200, "DescribeCacheSubnetGroupsResponse",f"<DescribeCacheSubnetGroupsResult><CacheSubnetGroups>{members}</CacheSubnetGroups></DescribeCacheSubnetGroupsResult>")def _delete_subnet_group(p):- _subnet_groups.pop(_p(p, "CacheSubnetGroupName"), None)+ name = _p(p, "CacheSubnetGroupName")+ sg = _subnet_groups.pop(name, None)+ if sg:+ _tags.pop(sg.get("ARN", ""), None)return _xml(200, "DeleteCacheSubnetGroupResponse", "")+def _modify_subnet_group(p):+ name = _p(p, "CacheSubnetGroupName")+ sg = _subnet_groups.get(name)+ if not sg:+ return _error("CacheSubnetGroupNotFoundFault", f"Subnet group {name} not found", 404)++ if _p(p, "CacheSubnetGroupDescription"):+ sg["CacheSubnetGroupDescription"] = _p(p, "CacheSubnetGroupDescription")++ subnets = []+ idx = 1+ while _p(p, f"SubnetIds.member.{idx}"):+ subnets.append({+ "SubnetIdentifier": _p(p, f"SubnetIds.member.{idx}"),+ "SubnetAvailabilityZone": {"Name": f"{REGION}{'abcdef'[(idx - 1) % 6]}"},+ })+ idx += 1+ if subnets:+ sg["Subnets"] = subnets++ arn = sg.get("ARN", _arn_subnet_group(name))+ return _xml(200, "ModifyCacheSubnetGroupResponse",+ f"<ModifyCacheSubnetGroupResult><CacheSubnetGroup>"+ f"<CacheSubnetGroupName>{name}</CacheSubnetGroupName>"+ f"<CacheSubnetGroupDescription>{sg.get('CacheSubnetGroupDescription', '')}</CacheSubnetGroupDescription>"+ f"<ARN>{arn}</ARN>"+ f"</CacheSubnetGroup></ModifyCacheSubnetGroupResult>")+++# ---- Parameter Groups ----+def _create_param_group(p):name = _p(p, "CacheParameterGroupName")- _param_groups[name] = {"CacheParameterGroupName": name, "CacheParameterGroupFamily": _p(p, "CacheParameterGroupFamily")}+ family = _p(p, "CacheParameterGroupFamily") or "redis7.0"+ desc = _p(p, "Description") or ""+ arn = _arn_param_group(name)+ _param_groups[name] = {+ "CacheParameterGroupName": name,+ "CacheParameterGroupFamily": family,+ "Description": desc,+ "IsGlobal": False,+ "ARN": arn,+ }+ _param_group_params[name] = _default_params_for_family(family)return _xml(200, "CreateCacheParameterGroupResponse",- f"<CreateCacheParameterGroupResult><CacheParameterGroup><CacheParameterGroupName>{name}</CacheParameterGroupName></CacheParameterGroup></CreateCacheParameterGroupResult>")+ f"<CreateCacheParameterGroupResult><CacheParameterGroup>"+ f"<CacheParameterGroupName>{name}</CacheParameterGroupName>"+ f"<CacheParameterGroupFamily>{family}</CacheParameterGroupFamily>"+ f"<Description>{desc}</Description>"+ f"<ARN>{arn}</ARN>"+ f"</CacheParameterGroup></CreateCacheParameterGroupResult>")def _describe_param_groups(p):name = _p(p, "CacheParameterGroupName")groups = [_param_groups[name]] if name and name in _param_groups else list(_param_groups.values())- members = "".join(f"<member><CacheParameterGroupName>{g['CacheParameterGroupName']}</CacheParameterGroupName></member>" for g in groups)+ members = "".join(+ f"<member><CacheParameterGroupName>{g['CacheParameterGroupName']}</CacheParameterGroupName>"+ f"<CacheParameterGroupFamily>{g.get('CacheParameterGroupFamily', '')}</CacheParameterGroupFamily>"+ f"<Description>{g.get('Description', '')}</Description>"+ f"<ARN>{g.get('ARN', '')}</ARN></member>"+ for g in groups+ )return _xml(200, "DescribeCacheParameterGroupsResponse",f"<DescribeCacheParameterGroupsResult><CacheParameterGroups>{members}</CacheParameterGroups></DescribeCacheParameterGroupsResult>")def _delete_param_group(p):- _param_groups.pop(_p(p, "CacheParameterGroupName"), None)+ name = _p(p, "CacheParameterGroupName")+ pg = _param_groups.pop(name, None)+ _param_group_params.pop(name, None)+ if pg:+ _tags.pop(pg.get("ARN", ""), None)return _xml(200, "DeleteCacheParameterGroupResponse", "")+def _describe_cache_parameters(p):+ name = _p(p, "CacheParameterGroupName")+ if name not in _param_groups:+ return _error("CacheParameterGroupNotFound",+ f"Parameter group {name} not found", 404)+ params = _param_group_params.get(name, {})+ members = ""+ for pname, pval in params.items():+ members += (+ f"<member>"+ f"<ParameterName>{pname}</ParameterName>"+ f"<ParameterValue>{pval.get('Value', '')}</ParameterValue>"+ f"<Description>{pval.get('Description', '')}</Description>"+ f"<Source>{pval.get('Source', 'system')}</Source>"+ f"<DataType>{pval.get('DataType', 'string')}</DataType>"+ f"<AllowedValues>{pval.get('AllowedValues', '')}</AllowedValues>"+ f"<IsModifiable>{str(pval.get('IsModifiable', True)).lower()}</IsModifiable>"+ f"<MinimumEngineVersion>{pval.get('MinimumEngineVersion', '5.0.0')}</MinimumEngineVersion>"+ f"</member>"+ )+ return _xml(200, "DescribeCacheParametersResponse",+ f"<DescribeCacheParametersResult><Parameters>{members}</Parameters></DescribeCacheParametersResult>")+++def _modify_cache_parameter_group(p):+ name = _p(p, "CacheParameterGroupName")+ if name not in _param_groups:+ return _error("CacheParameterGroupNotFound",+ f"Parameter group {name} not found", 404)+ params = _param_group_params.setdefault(name, {})++ idx = 1+ while _p(p, f"ParameterNameValues.member.{idx}.ParameterName"):+ pname = _p(p, f"ParameterNameValues.member.{idx}.ParameterName")+ pvalue = _p(p, f"ParameterNameValues.member.{idx}.ParameterValue")+ if pname in params:+ params[pname]["Value"] = pvalue+ params[pname]["Source"] = "user"+ else:+ params[pname] = {"Value": pvalue, "Source": "user", "DataType": "string",+ "Description": "", "IsModifiable": True}+ idx += 1++ return _xml(200, "ModifyCacheParameterGroupResponse",+ f"<ModifyCacheParameterGroupResult>"+ f"<CacheParameterGroupName>{name}</CacheParameterGroupName>"+ f"</ModifyCacheParameterGroupResult>")+++def _reset_cache_parameter_group(p):+ name = _p(p, "CacheParameterGroupName")+ if name not in _param_groups:+ return _error("CacheParameterGroupNotFound",+ f"Parameter group {name} not found", 404)++ reset_all = _p(p, "ResetAllParameters", "false").lower() == "true"+ family = _param_groups[name].get("CacheParameterGroupFamily", "redis7.0")++ if reset_all:+ _param_group_params[name] = _default_params_for_family(family)+ else:+ defaults = _default_params_for_family(family)+ params = _param_group_params.get(name, {})+ idx = 1+ while _p(p, f"ParameterNameValues.member.{idx}.ParameterName"):+ pname = _p(p, f"ParameterNameValues.member.{idx}.ParameterName")+ if pname in defaults:+ params[pname] = dict(defaults[pname])+ idx += 1++ return _xml(200, "ResetCacheParameterGroupResponse",+ f"<ResetCacheParameterGroupResult>"+ f"<CacheParameterGroupName>{name}</CacheParameterGroupName>"+ f"</ResetCacheParameterGroupResult>")+++def _default_params_for_family(family):+ """Seed with commonly queried Redis/Memcached default parameters."""+ if family.startswith("redis"):+ return {+ "maxmemory-policy": {"Value": "volatile-lru", "Description": "Eviction policy",+ "Source": "system", "DataType": "string",+ "AllowedValues": "volatile-lru,allkeys-lru,volatile-random,allkeys-random,volatile-ttl,noeviction",+ "IsModifiable": True, "MinimumEngineVersion": "2.8.6"},+ "maxmemory-samples": {"Value": "5", "Description": "Number of keys to sample",+ "Source": "system", "DataType": "integer",+ "AllowedValues": "1-", "IsModifiable": True, "MinimumEngineVersion": "2.8.6"},+ "timeout": {"Value": "0", "Description": "Close connection after N seconds idle",+ "Source": "system", "DataType": "integer",+ "AllowedValues": "0-", "IsModifiable": True, "MinimumEngineVersion": "2.6.13"},+ "tcp-keepalive": {"Value": "300", "Description": "TCP keepalive",+ "Source": "system", "DataType": "integer",+ "AllowedValues": "0-", "IsModifiable": True, "MinimumEngineVersion": "2.6.13"},+ "databases": {"Value": "16", "Description": "Number of databases",+ "Source": "system", "DataType": "integer",+ "AllowedValues": "1-1200000", "IsModifiable": True, "MinimumEngineVersion": "2.6.13"},+ }+ return {+ "max_simultaneous_connections_per_server": {"Value": "8", "Source": "system",+ "DataType": "integer", "Description": "Max connections", "IsModifiable": True},+ }+++# ---- Engine Versions ----+def _describe_engine_versions(p):engine = _p(p, "Engine") or "redis"- versions = {"redis": ["7.0.12", "6.2.14", "5.0.6"], "memcached": ["1.6.17", "1.6.12"]}+ versions = {"redis": ["7.1.0", "7.0.12", "6.2.14", "5.0.6"], "memcached": ["1.6.22", "1.6.17", "1.6.12"]}members = "".join(- f"<member><Engine>{engine}</Engine><EngineVersion>{v}</EngineVersion><CacheParameterGroupFamily>{engine}{v[:3]}</CacheParameterGroupFamily></member>"+ f"<member><Engine>{engine}</Engine><EngineVersion>{v}</EngineVersion>"+ f"<CacheParameterGroupFamily>{engine}{v[:3]}</CacheParameterGroupFamily></member>"for v in versions.get(engine, ["7.0.12"]))return _xml(200, "DescribeCacheEngineVersionsResponse",f"<DescribeCacheEngineVersionsResult><CacheEngineVersions>{members}</CacheEngineVersions></DescribeCacheEngineVersionsResult>")+# ---- Tags ----++def _extract_tags(p):+ """Extract Tags.member.N or Tags.Tag.N format from query params."""+ tags = []+ for prefix in ("Tags.member", "Tags.Tag"):+ idx = 1+ while _p(p, f"{prefix}.{idx}.Key"):+ tags.append({+ "Key": _p(p, f"{prefix}.{idx}.Key"),+ "Value": _p(p, f"{prefix}.{idx}.Value") or "",+ })+ idx += 1+ if tags:+ break+ return tags++def _list_tags(p):- return _xml(200, "ListTagsForResourceResponse", "<ListTagsForResourceResult><TagList/></ListTagsForResourceResult>")+ arn = _p(p, "ResourceName")+ tags = _tags.get(arn, [])+ tag_xml = "".join(f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>" for t in tags)+ return _xml(200, "ListTagsForResourceResponse",+ f"<ListTagsForResourceResult><TagList>{tag_xml}</TagList></ListTagsForResourceResult>")def _add_tags(p):- return _xml(200, "AddTagsToResourceResponse", "<AddTagsToResourceResult><TagList/></AddTagsToResourceResult>")+ arn = _p(p, "ResourceName")+ new_tags = _extract_tags(p)+ existing = _tags.setdefault(arn, [])+ existing_keys = {t["Key"] for t in existing}+ for t in new_tags:+ if t["Key"] in existing_keys:+ for e in existing:+ if e["Key"] == t["Key"]:+ e["Value"] = t["Value"]+ break+ else:+ existing.append(t)+ existing_keys.add(t["Key"])++ tag_xml = "".join(f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>" for t in existing)+ return _xml(200, "AddTagsToResourceResponse",+ f"<AddTagsToResourceResult><TagList>{tag_xml}</TagList></AddTagsToResourceResult>")def _remove_tags(p):- return _xml(200, "RemoveTagsFromResourceResponse", "")+ arn = _p(p, "ResourceName")+ keys_to_remove = set()+ idx = 1+ while _p(p, f"TagKeys.member.{idx}"):+ keys_to_remove.add(_p(p, f"TagKeys.member.{idx}"))+ idx += 1+ if arn in _tags:+ _tags[arn] = [t for t in _tags[arn] if t["Key"] not in keys_to_remove]++ tags = _tags.get(arn, [])+ tag_xml = "".join(f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>" for t in tags)+ return _xml(200, "RemoveTagsFromResourceResponse",+ f"<RemoveTagsFromResourceResult><TagList>{tag_xml}</TagList></RemoveTagsFromResourceResult>")+++# ---- Snapshots ----++def _create_snapshot(p):+ snapshot_name = _p(p, "SnapshotName")+ cluster_id = _p(p, "CacheClusterId")+ rg_id = _p(p, "ReplicationGroupId")++ if snapshot_name in _snapshots:+ return _error("SnapshotAlreadyExistsFault", f"Snapshot {snapshot_name} already exists", 400)++ source_id = cluster_id or rg_id+ arn = _arn_snapshot(snapshot_name)+ _snapshots[snapshot_name] = {+ "SnapshotName": snapshot_name,+ "SnapshotStatus": "available",+ "SnapshotSource": "manual",+ "CacheClusterId": cluster_id,+ "ReplicationGroupId": rg_id,+ "CacheNodeType": "cache.t3.micro",+ "Engine": "redis",+ "EngineVersion": "7.0.12",+ "SnapshotRetentionLimit": 0,+ "SnapshotWindow": "05:00-06:00",+ "NodeSnapshots": [{"CacheNodeId": "0001", "SnapshotCreateTime": time.time(),+ "CacheSize": "0 MB"}],+ "ARN": arn,+ "CreateTime": time.time(),+ }++ if source_id:+ cluster = _clusters.get(source_id) or {}+ rg = _replication_groups.get(source_id) or {}+ src = cluster or rg+ if src:+ _snapshots[snapshot_name]["CacheNodeType"] = src.get("CacheNodeType", "cache.t3.micro")+ _snapshots[snapshot_name]["Engine"] = src.get("Engine", "redis")+ _snapshots[snapshot_name]["EngineVersion"] = src.get("EngineVersion", "7.0.12")++ _record_event(snapshot_name, "snapshot", "Snapshot created")+ return _xml(200, "CreateSnapshotResponse",+ f"<CreateSnapshotResult><Snapshot>{_snapshot_xml(_snapshots[snapshot_name])}</Snapshot></CreateSnapshotResult>")+++def _delete_snapshot(p):+ snapshot_name = _p(p, "SnapshotName")+ snap = _snapshots.pop(snapshot_name, None)+ if not snap:+ return _error("SnapshotNotFoundFault", f"Snapshot {snapshot_name} not found", 404)+ _tags.pop(snap.get("ARN", ""), None)+ snap["SnapshotStatus"] = "deleting"+ _record_event(snapshot_name, "snapshot", "Snapshot deleted")+ return _xml(200, "DeleteSnapshotResponse",+ f"<DeleteSnapshotResult><Snapshot>{_snapshot_xml(snap)}</Snapshot></DeleteSnapshotResult>")+++def _describe_snapshots(p):+ snapshot_name = _p(p, "SnapshotName")+ cluster_id = _p(p, "CacheClusterId")+ rg_id = _p(p, "ReplicationGroupId")++ snaps = list(_snapshots.values())+ if snapshot_name:+ snaps = [s for s in snaps if s["SnapshotName"] == snapshot_name]+ if cluster_id:+ snaps = [s for s in snaps if s.get("CacheClusterId") == cluster_id]+ if rg_id:+ snaps = [s for s in snaps if s.get("ReplicationGroupId") == rg_id]++ members = "".join(f"<member>{_snapshot_xml(s)}</member>" for s in snaps)+ return _xml(200, "DescribeSnapshotsResponse",+ f"<DescribeSnapshotsResult><Snapshots>{members}</Snapshots></DescribeSnapshotsResult>")+++# ---- Events ----++def _describe_events(p):+ source_id = _p(p, "SourceIdentifier")+ source_type = _p(p, "SourceType")+ max_records = int(_p(p, "MaxRecords") or "100")++ filtered = _events+ if source_id:+ filtered = [e for e in filtered if e["SourceIdentifier"] == source_id]+ if source_type:+ filtered = [e for e in filtered if e["SourceType"] == source_type]++ filtered = filtered[-max_records:]+ members = "".join(+ f"<member>"+ f"<SourceIdentifier>{e['SourceIdentifier']}</SourceIdentifier>"+ f"<SourceType>{e['SourceType']}</SourceType>"+ f"<Message>{e['Message']}</Message>"+ f"<Date>{e['Date']}</Date>"+ f"</member>"+ for e in filtered+ )+ return _xml(200, "DescribeEventsResponse",+ f"<DescribeEventsResult><Events>{members}</Events></DescribeEventsResult>")+++# ---- Users (Redis ACL) ----++def _arn_user(user_id):+ return f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:user:{user_id}"+++def _arn_user_group(group_id):+ return f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:usergroup:{group_id}"+++def _create_user(p):+ user_id = _p(p, "UserId")+ if not user_id:+ return _error("InvalidParameterValue", "UserId is required", 400)+ if user_id in _users:+ return _error("UserAlreadyExistsFault", f"User {user_id} already exists", 400)++ arn = _arn_user(user_id)+ user = {+ "UserId": user_id,+ "UserName": _p(p, "UserName") or user_id,+ "Engine": _p(p, "Engine") or "redis",+ "Status": "active",+ "AccessString": _p(p, "AccessString") or "on ~* +@all",+ "UserGroupIds": [],+ "Authentication": {"Type": "password", "PasswordCount": 1} if _p(p, "Passwords.member.1") else {"Type": "no-password", "PasswordCount": 0},+ "ARN": arn,+ }+ _users[user_id] = user++ tags = _extract_tags(p)+ if tags:+ _tags[arn] = tags++ return _xml(200, "CreateUserResponse", f"<CreateUserResult>{_user_xml(user)}</CreateUserResult>")+++def _describe_users(p):+ user_id = _p(p, "UserId")+ engine = _p(p, "Engine")++ if user_id:+ user = _users.get(user_id)+ if not user:+ return _error("UserNotFoundFault", f"User {user_id} not found", 404)+ users = [user]+ else:+ users = list(_users.values())+ if engine:+ users = [u for u in users if u.get("Engine") == engine]++ members = "".join(f"<member>{_user_xml(u)}</member>" for u in users)+ return _xml(200, "DescribeUsersResponse",+ f"<DescribeUsersResult><Users>{members}</Users></DescribeUsersResult>")+++def _delete_user(p):+ user_id = _p(p, "UserId")+ user = _users.pop(user_id, None)+ if not user:+ return _error("UserNotFoundFault", f"User {user_id} not found", 404)+ _tags.pop(user.get("ARN", ""), None)+ user["Status"] = "deleting"+ return _xml(200, "DeleteUserResponse", f"<DeleteUserResult>{_user_xml(user)}</DeleteUserResult>")+++def _modify_user(p):+ user_id = _p(p, "UserId")+ user = _users.get(user_id)+ if not user:+ return _error("UserNotFoundFault", f"User {user_id} not found", 404)++ if _p(p, "AccessString"):+ user["AccessString"] = _p(p, "AccessString")+ if _p(p, "Passwords.member.1"):+ user["Authentication"] = {"Type": "password", "PasswordCount": 1}++ return _xml(200, "ModifyUserResponse", f"<ModifyUserResult>{_user_xml(user)}</ModifyUserResult>")+++def _create_user_group(p):+ group_id = _p(p, "UserGroupId")+ if not group_id:+ return _error("InvalidParameterValue", "UserGroupId is required", 400)+ if group_id in _user_groups:+ return _error("UserGroupAlreadyExistsFault", f"User group {group_id} already exists", 400)++ arn = _arn_user_group(group_id)+ user_ids = []+ idx = 1+ while _p(p, f"UserIds.member.{idx}"):+ user_ids.append(_p(p, f"UserIds.member.{idx}"))+ idx += 1++ group = {+ "UserGroupId": group_id,+ "Status": "active",+ "Engine": _p(p, "Engine") or "redis",+ "UserIds": user_ids,+ "PendingChanges": {},+ "ReplicationGroups": [],+ "ARN": arn,+ }+ _user_groups[group_id] = group++ for uid in user_ids:+ if uid in _users:+ _users[uid].setdefault("UserGroupIds", []).append(group_id)++ tags = _extract_tags(p)+ if tags:+ _tags[arn] = tags++ return _xml(200, "CreateUserGroupResponse", f"<CreateUserGroupResult>{_user_group_xml(group)}</CreateUserGroupResult>")+++def _describe_user_groups(p):+ group_id = _p(p, "UserGroupId")++ if group_id:+ group = _user_groups.get(group_id)+ if not group:+ return _error("UserGroupNotFoundFault", f"User group {group_id} not found", 404)+ groups = [group]+ else:+ groups = list(_user_groups.values())++ members = "".join(f"<member>{_user_group_xml(g)}</member>" for g in groups)+ return _xml(200, "DescribeUserGroupsResponse",+ f"<DescribeUserGroupsResult><UserGroups>{members}</UserGroups></DescribeUserGroupsResult>")+++def _delete_user_group(p):+ group_id = _p(p, "UserGroupId")+ group = _user_groups.pop(group_id, None)+ if not group:+ return _error("UserGroupNotFoundFault", f"User group {group_id} not found", 404)+ _tags.pop(group.get("ARN", ""), None)++ for uid in group.get("UserIds", []):+ if uid in _users:+ gids = _users[uid].get("UserGroupIds", [])+ if group_id in gids:+ gids.remove(group_id)++ group["Status"] = "deleting"+ return _xml(200, "DeleteUserGroupResponse", f"<DeleteUserGroupResult>{_user_group_xml(group)}</DeleteUserGroupResult>")+++def _modify_user_group(p):+ group_id = _p(p, "UserGroupId")+ group = _user_groups.get(group_id)+ if not group:+ return _error("UserGroupNotFoundFault", f"User group {group_id} not found", 404)++ to_add = []+ idx = 1+ while _p(p, f"UserIdsToAdd.member.{idx}"):+ to_add.append(_p(p, f"UserIdsToAdd.member.{idx}"))+ idx += 1++ to_remove = []+ idx = 1+ while _p(p, f"UserIdsToRemove.member.{idx}"):+ to_remove.append(_p(p, f"UserIdsToRemove.member.{idx}"))+ idx += 1++ for uid in to_add:+ if uid not in group["UserIds"]:+ group["UserIds"].append(uid)+ if uid in _users:+ _users[uid].setdefault("UserGroupIds", []).append(group_id)++ for uid in to_remove:+ if uid in group["UserIds"]:+ group["UserIds"].remove(uid)+ if uid in _users:+ gids = _users[uid].get("UserGroupIds", [])+ if group_id in gids:+ gids.remove(group_id)++ return _xml(200, "ModifyUserGroupResponse", f"<ModifyUserGroupResult>{_user_group_xml(group)}</ModifyUserGroupResult>")+++def _user_xml(u):+ group_ids_xml = "".join(f"<member>{gid}</member>" for gid in u.get("UserGroupIds", []))+ auth = u.get("Authentication", {})+ return (+ f"<UserId>{u['UserId']}</UserId>"+ f"<UserName>{u.get('UserName', '')}</UserName>"+ f"<Engine>{u.get('Engine', 'redis')}</Engine>"+ f"<Status>{u.get('Status', 'active')}</Status>"+ f"<AccessString>{u.get('AccessString', '')}</AccessString>"+ f"<UserGroupIds>{group_ids_xml}</UserGroupIds>"+ f"<Authentication><Type>{auth.get('Type', 'no-password')}</Type>"+ f"<PasswordCount>{auth.get('PasswordCount', 0)}</PasswordCount></Authentication>"+ f"<ARN>{u.get('ARN', '')}</ARN>"+ )+++def _user_group_xml(g):+ user_ids_xml = "".join(f"<member>{uid}</member>" for uid in g.get("UserIds", []))+ rg_xml = "".join(f"<member>{rg}</member>" for rg in g.get("ReplicationGroups", []))+ return (+ f"<UserGroupId>{g['UserGroupId']}</UserGroupId>"+ f"<Status>{g.get('Status', 'active')}</Status>"+ f"<Engine>{g.get('Engine', 'redis')}</Engine>"+ f"<UserIds>{user_ids_xml}</UserIds>"+ f"<ReplicationGroups>{rg_xml}</ReplicationGroups>"+ f"<ARN>{g.get('ARN', '')}</ARN>"+ )# ---- XML helpers -----def _cluster_xml(c):+def _cluster_xml_inner(c):+ """Render cluster fields — no wrapping element."""ep = c.get("_endpoint", {})nodes_xml = ""for node in c.get("CacheNodes", []):nep = node.get("Endpoint", {})- nodes_xml += f"""<member>- <CacheNodeId>{node['CacheNodeId']}</CacheNodeId>- <CacheNodeStatus>{node['CacheNodeStatus']}</CacheNodeStatus>- <Endpoint><Address>{nep.get('Address','localhost')}</Address><Port>{nep.get('Port',6379)}</Port></Endpoint>- </member>"""- return f"""<member>- <CacheClusterId>{c['CacheClusterId']}</CacheClusterId>- <CacheClusterStatus>{c['CacheClusterStatus']}</CacheClusterStatus>- <Engine>{c['Engine']}</Engine>- <EngineVersion>{c['EngineVersion']}</EngineVersion>- <CacheNodeType>{c['CacheNodeType']}</CacheNodeType>- <NumCacheNodes>{c['NumCacheNodes']}</NumCacheNodes>- <CacheClusterArn>{c['CacheClusterArn']}</CacheClusterArn>- <CacheNodes>{nodes_xml}</CacheNodes>- </member>"""+ nodes_xml += (+ f"<member>"+ f"<CacheNodeId>{node['CacheNodeId']}</CacheNodeId>"+ f"<CacheNodeStatus>{node['CacheNodeStatus']}</CacheNodeStatus>"+ f"<Endpoint><Address>{nep.get('Address', 'localhost')}</Address>"+ f"<Port>{nep.get('Port', 6379)}</Port></Endpoint>"+ f"</member>"+ )+ return (+ f"<CacheClusterId>{c['CacheClusterId']}</CacheClusterId>"+ f"<CacheClusterStatus>{c['CacheClusterStatus']}</CacheClusterStatus>"+ f"<Engine>{c['Engine']}</Engine>"+ f"<EngineVersion>{c['EngineVersion']}</EngineVersion>"+ f"<CacheNodeType>{c['CacheNodeType']}</CacheNodeType>"+ f"<NumCacheNodes>{c['NumCacheNodes']}</NumCacheNodes>"+ f"<CacheClusterArn>{c['CacheClusterArn']}</CacheClusterArn>"+ f"<ARN>{c.get('CacheClusterArn', '')}</ARN>"+ f"<PreferredAvailabilityZone>{c.get('PreferredAvailabilityZone', '')}</PreferredAvailabilityZone>"+ f"<CacheSubnetGroupName>{c.get('CacheSubnetGroupName', '')}</CacheSubnetGroupName>"+ f"<ReplicationGroupId>{c.get('ReplicationGroupId', '')}</ReplicationGroupId>"+ f"<SnapshotRetentionLimit>{c.get('SnapshotRetentionLimit', 0)}</SnapshotRetentionLimit>"+ f"<SnapshotWindow>{c.get('SnapshotWindow', '')}</SnapshotWindow>"+ f"<CacheNodes>{nodes_xml}</CacheNodes>"+ )+++def _cluster_xml(c):+ """For list contexts (DescribeCacheClusters), wrap in <member>."""+ return f"<member>{_cluster_xml_inner(c)}</member>"def _rg_xml(rg):- return f"""<ReplicationGroupId>{rg['ReplicationGroupId']}</ReplicationGroupId>- <Description>{rg['Description']}</Description>- <Status>{rg['Status']}</Status>- <ARN>{rg['ARN']}</ARN>"""+ node_groups_xml = ""+ for ng in rg.get("NodeGroups", []):+ members_xml = ""+ for m in ng.get("NodeGroupMembers", []):+ rep = m.get("ReadEndpoint", {})+ members_xml += (+ f"<member>"+ f"<CacheClusterId>{m.get('CacheClusterId', '')}</CacheClusterId>"+ f"<CacheNodeId>{m.get('CacheNodeId', '0001')}</CacheNodeId>"+ f"<CurrentRole>{m.get('CurrentRole', 'primary')}</CurrentRole>"+ f"<PreferredAvailabilityZone>{m.get('PreferredAvailabilityZone', '')}</PreferredAvailabilityZone>"+ f"<ReadEndpoint><Address>{rep.get('Address', 'localhost')}</Address>"+ f"<Port>{rep.get('Port', 6379)}</Port></ReadEndpoint>"+ f"</member>"+ )+ pep = ng.get("PrimaryEndpoint", {})+ rdr = ng.get("ReaderEndpoint", {})+ node_groups_xml += (+ f"<member>"+ f"<NodeGroupId>{ng['NodeGroupId']}</NodeGroupId>"+ f"<Status>{ng['Status']}</Status>"+ f"<PrimaryEndpoint><Address>{pep.get('Address', 'localhost')}</Address>"+ f"<Port>{pep.get('Port', 6379)}</Port></PrimaryEndpoint>"+ f"<ReaderEndpoint><Address>{rdr.get('Address', 'localhost')}</Address>"+ f"<Port>{rdr.get('Port', 6379)}</Port></ReaderEndpoint>"+ f"<NodeGroupMembers>{members_xml}</NodeGroupMembers>"+ f"</member>"+ )++ config_ep_xml = ""+ cep = rg.get("ConfigurationEndpoint")+ if cep:+ config_ep_xml = (+ f"<ConfigurationEndpoint><Address>{cep['Address']}</Address>"+ f"<Port>{cep['Port']}</Port></ConfigurationEndpoint>"+ )++ return (+ f"<ReplicationGroupId>{rg['ReplicationGroupId']}</ReplicationGroupId>"+ f"<Description>{rg.get('Description', '')}</Description>"+ f"<Status>{rg['Status']}</Status>"+ f"<CacheNodeType>{rg.get('CacheNodeType', 'cache.t3.micro')}</CacheNodeType>"+ f"<AutomaticFailover>{rg.get('AutomaticFailover', 'disabled')}</AutomaticFailover>"+ f"<MultiAZ>{rg.get('MultiAZ', 'disabled')}</MultiAZ>"+ f"<ClusterEnabled>{str(rg.get('ClusterEnabled', False)).lower()}</ClusterEnabled>"+ f"<AuthTokenEnabled>{str(rg.get('AuthTokenEnabled', False)).lower()}</AuthTokenEnabled>"+ f"<TransitEncryptionEnabled>{str(rg.get('TransitEncryptionEnabled', False)).lower()}</TransitEncryptionEnabled>"+ f"<AtRestEncryptionEnabled>{str(rg.get('AtRestEncryptionEnabled', False)).lower()}</AtRestEncryptionEnabled>"+ f"<SnapshotRetentionLimit>{rg.get('SnapshotRetentionLimit', 0)}</SnapshotRetentionLimit>"+ f"<SnapshotWindow>{rg.get('SnapshotWindow', '')}</SnapshotWindow>"+ f"{config_ep_xml}"+ f"<NodeGroups>{node_groups_xml}</NodeGroups>"+ f"<ARN>{rg['ARN']}</ARN>"+ )+++def _snapshot_xml(snap):+ nodes_xml = ""+ for ns in snap.get("NodeSnapshots", []):+ nodes_xml += (+ f"<member>"+ f"<CacheNodeId>{ns.get('CacheNodeId', '0001')}</CacheNodeId>"+ f"<SnapshotCreateTime>{ns.get('SnapshotCreateTime', 0)}</SnapshotCreateTime>"+ f"<CacheSize>{ns.get('CacheSize', '0 MB')}</CacheSize>"+ f"</member>"+ )+ return (+ f"<SnapshotName>{snap['SnapshotName']}</SnapshotName>"+ f"<SnapshotStatus>{snap['SnapshotStatus']}</SnapshotStatus>"+ f"<SnapshotSource>{snap.get('SnapshotSource', 'manual')}</SnapshotSource>"+ f"<CacheClusterId>{snap.get('CacheClusterId', '')}</CacheClusterId>"+ f"<ReplicationGroupId>{snap.get('ReplicationGroupId', '')}</ReplicationGroupId>"+ f"<CacheNodeType>{snap.get('CacheNodeType', 'cache.t3.micro')}</CacheNodeType>"+ f"<Engine>{snap.get('Engine', 'redis')}</Engine>"+ f"<EngineVersion>{snap.get('EngineVersion', '7.0.12')}</EngineVersion>"+ f"<NodeSnapshots>{nodes_xml}</NodeSnapshots>"+ f"<ARN>{snap.get('ARN', '')}</ARN>"+ )def _xml_cluster_response(root_tag, result_tag, cluster):- return _xml(200, root_tag, f"<{result_tag}><CacheCluster>{_cluster_xml(cluster)}</CacheCluster></{result_tag}>")+ return _xml(200, root_tag, f"<{result_tag}><CacheCluster>{_cluster_xml_inner(cluster)}</CacheCluster></{result_tag}>")def _p(params, key, default=""):@@ -392,3 +1263,14 @@ def _error(code, message, status):<RequestId>{new_uuid()}</RequestId></ErrorResponse>""".encode("utf-8")return status, {"Content-Type": "application/xml"}, body+++def reset():+ _clusters.clear()+ _replication_groups.clear()+ _subnet_groups.clear()+ _param_groups.clear()+ _snapshots.clear()+ _users.clear()+ _user_groups.clear()+ _events.clear()diff --git a/services/eventbridge.py b/services/eventbridge.pyindex 1097a30e..5cd45c5f 100644--- a/services/eventbridge.py+++ b/services/eventbridge.py@@ -1,16 +1,24 @@"""EventBridge Service Emulator.JSON-based API via X-Amz-Target (AmazonEventBridge).-Supports: CreateEventBus, DeleteEventBus, ListEventBuses,+Supports: CreateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus,PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule,PutTargets, RemoveTargets, ListTargetsByRule,- PutEvents.+ PutEvents,+ TagResource, UntagResource, ListTagsForResource,+ CreateArchive, DeleteArchive, DescribeArchive, ListArchives,+ PutPermission, RemovePermission,+ CreateConnection, DescribeConnection, DeleteConnection, ListConnections, UpdateConnection,+ CreateApiDestination, DescribeApiDestination, DeleteApiDestination,+ ListApiDestinations, UpdateApiDestination."""import jsonimport time+import hashlibimport loggingimport re+from datetime import datetime, timezonefrom core.responses import json_response, error_response_json, new_uuid@@ -19,16 +27,26 @@ logger = logging.getLogger("events")ACCOUNT_ID = "000000000000"REGION = "us-east-1"++def _now_iso() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"++_event_buses: dict = {"default": {"Name": "default","Arn": f"arn:aws:events:{REGION}:{ACCOUNT_ID}:event-bus/default",- "CreationTime": time.time(),+ "CreationTime": _now_iso(),}}-_rules: dict = {} # rule_name -> rule dict-_targets: dict = {} # rule_name -> [target, ...]-_events_log: list = [] # stored PutEvents entries+_rules: dict = {}+_targets: dict = {}+_events_log: list = []+_tags: dict = {}+_archives: dict = {}+_event_bus_policies: dict = {} # bus_name -> {Statement: [...]}+_connections: dict = {} # connection_name -> {...}+_api_destinations: dict = {} # destination_name -> {...}async def handle_request(method, path, headers, body, query_params):@@ -55,6 +73,25 @@ async def handle_request(method, path, headers, body, query_params):"RemoveTargets": _remove_targets,"ListTargetsByRule": _list_targets_by_rule,"PutEvents": _put_events,+ "TagResource": _tag_resource,+ "UntagResource": _untag_resource,+ "ListTagsForResource": _list_tags_for_resource,+ "CreateArchive": _create_archive,+ "DeleteArchive": _delete_archive,+ "DescribeArchive": _describe_archive,+ "ListArchives": _list_archives,+ "PutPermission": _put_permission,+ "RemovePermission": _remove_permission,+ "CreateConnection": _create_connection,+ "DescribeConnection": _describe_connection,+ "DeleteConnection": _delete_connection,+ "ListConnections": _list_connections,+ "UpdateConnection": _update_connection,+ "CreateApiDestination": _create_api_destination,+ "DescribeApiDestination": _describe_api_destination,+ "DeleteApiDestination": _delete_api_destination,+ "ListApiDestinations": _list_api_destinations,+ "UpdateApiDestination": _update_api_destination,}handler = handlers.get(action)@@ -63,6 +100,10 @@ async def handle_request(method, path, headers, body, query_params):return handler(data)+# ---------------------------------------------------------------------------+# Event Buses+# ---------------------------------------------------------------------------+def _create_event_bus(data):name = data.get("Name")if not name:@@ -70,7 +111,14 @@ def _create_event_bus(data):if name in _event_buses:return error_response_json("ResourceAlreadyExistsException", f"Event bus {name} already exists", 400)arn = f"arn:aws:events:{REGION}:{ACCOUNT_ID}:event-bus/{name}"- _event_buses[name] = {"Name": name, "Arn": arn, "CreationTime": time.time()}+ _event_buses[name] = {+ "Name": name,+ "Arn": arn,+ "CreationTime": _now_iso(),+ }+ tags = data.get("Tags", [])+ if tags:+ _tags[arn] = {t["Key"]: t["Value"] for t in tags}return json_response({"EventBusArn": arn})@@ -78,13 +126,25 @@ def _delete_event_bus(data):name = data.get("Name")if name == "default":return error_response_json("ValidationException", "Cannot delete the default event bus", 400)- _event_buses.pop(name, None)+ bus = _event_buses.pop(name, None)+ if bus:+ _tags.pop(bus["Arn"], None)+ rules_to_delete = [n for n, r in _rules.items() if r.get("EventBusName") == name]+ for rn in rules_to_delete:+ _rules.pop(rn, None)+ _targets.pop(rn, None)return json_response({})def _list_event_buses(data):prefix = data.get("NamePrefix", "")- buses = [b for n, b in _event_buses.items() if n.startswith(prefix)]+ buses = []+ for n, b in _event_buses.items():+ if n.startswith(prefix):+ buses.append({+ "Name": b["Name"],+ "Arn": b["Arn"],+ })return json_response({"EventBuses": buses})@@ -93,7 +153,33 @@ def _describe_event_bus(data):bus = _event_buses.get(name)if not bus:return error_response_json("ResourceNotFoundException", f"Event bus {name} not found", 400)- return json_response(bus)+ return json_response({+ "Name": bus["Name"],+ "Arn": bus["Arn"],+ "CreationTime": bus["CreationTime"],+ })+++# ---------------------------------------------------------------------------+# Rules+# ---------------------------------------------------------------------------++def _rule_arn(rule_name: str, bus_name: str) -> str:+ if bus_name == "default":+ return f"arn:aws:events:{REGION}:{ACCOUNT_ID}:rule/{rule_name}"+ return f"arn:aws:events:{REGION}:{ACCOUNT_ID}:rule/{bus_name}/{rule_name}"+++def _rule_key(rule_name: str, bus_name: str) -> str:+ return f"{bus_name}|{rule_name}"+++def _validate_schedule_expression(expr: str) -> bool:+ if not expr:+ return True+ rate_pattern = re.compile(r"^rate\(\d+\s+(minute|minutes|hour|hours|day|days)\)$")+ cron_pattern = re.compile(r"^cron\(.+\)$")+ return bool(rate_pattern.match(expr) or cron_pattern.match(expr))def _put_rule(data):@@ -101,96 +187,817 @@ def _put_rule(data):if not name:return error_response_json("ValidationException", "Name is required", 400)bus = data.get("EventBusName", "default")- arn = f"arn:aws:events:{REGION}:{ACCOUNT_ID}:rule/{name}"- _rules[name] = {++ if bus not in _event_buses:+ return error_response_json("ResourceNotFoundException", f"Event bus {bus} does not exist.", 400)++ schedule = data.get("ScheduleExpression", "")+ if schedule and not _validate_schedule_expression(schedule):+ return error_response_json(+ "ValidationException",+ f"Parameter ScheduleExpression is not valid.",+ 400,+ )++ event_pattern = data.get("EventPattern", "")+ if event_pattern and isinstance(event_pattern, str):+ try:+ json.loads(event_pattern)+ except json.JSONDecodeError:+ return error_response_json(+ "InvalidEventPatternException",+ "Event pattern is not valid JSON",+ 400,+ )++ arn = _rule_arn(name, bus)+ key = _rule_key(name, bus)++ existing = _rules.get(key, {})+ _rules[key] = {"Name": name,"Arn": arn,"EventBusName": bus,- "ScheduleExpression": data.get("ScheduleExpression", ""),- "EventPattern": data.get("EventPattern", ""),- "State": data.get("State", "ENABLED"),- "Description": data.get("Description", ""),+ "ScheduleExpression": schedule,+ "EventPattern": event_pattern,+ "State": data.get("State", existing.get("State", "ENABLED")),+ "Description": data.get("Description", existing.get("Description", "")),+ "RoleArn": data.get("RoleArn", existing.get("RoleArn", "")),+ "ManagedBy": existing.get("ManagedBy", ""),"CreatedBy": ACCOUNT_ID,+ "CreationTime": existing.get("CreationTime", _now_iso()),}++ tags = data.get("Tags", [])+ if tags:+ _tags[arn] = {t["Key"]: t["Value"] for t in tags}+return json_response({"RuleArn": arn})def _delete_rule(data):name = data.get("Name")- _rules.pop(name, None)- _targets.pop(name, None)+ bus = data.get("EventBusName", "default")+ key = _rule_key(name, bus)+ rule = _rules.pop(key, None)+ _targets.pop(key, None)+ if rule:+ _tags.pop(rule["Arn"], None)return json_response({})def _list_rules(data):prefix = data.get("NamePrefix", "")bus = data.get("EventBusName", "default")- rules = [r for n, r in _rules.items() if n.startswith(prefix) and r.get("EventBusName", "default") == bus]+ rules = []+ for key, r in _rules.items():+ if r.get("EventBusName", "default") != bus:+ continue+ if prefix and not r["Name"].startswith(prefix):+ continue+ rules.append(_rule_out(r))return json_response({"Rules": rules})def _describe_rule(data):name = data.get("Name")- rule = _rules.get(name)+ bus = data.get("EventBusName", "default")+ key = _rule_key(name, bus)+ rule = _rules.get(key)if not rule:- return error_response_json("ResourceNotFoundException", f"Rule {name} not found", 400)- return json_response(rule)+ return error_response_json("ResourceNotFoundException", f"Rule {name} does not exist.", 400)+ return json_response(_rule_out(rule))def _enable_rule(data):name = data.get("Name")- if name in _rules:- _rules[name]["State"] = "ENABLED"+ bus = data.get("EventBusName", "default")+ key = _rule_key(name, bus)+ if key in _rules:+ _rules[key]["State"] = "ENABLED"return json_response({})def _disable_rule(data):name = data.get("Name")- if name in _rules:- _rules[name]["State"] = "DISABLED"+ bus = data.get("EventBusName", "default")+ key = _rule_key(name, bus)+ if key in _rules:+ _rules[key]["State"] = "DISABLED"return json_response({})+def _rule_out(rule):+ out = {+ "Name": rule["Name"],+ "Arn": rule["Arn"],+ "EventBusName": rule["EventBusName"],+ "State": rule["State"],+ }+ if rule.get("ScheduleExpression"):+ out["ScheduleExpression"] = rule["ScheduleExpression"]+ if rule.get("EventPattern"):+ out["EventPattern"] = rule["EventPattern"]+ if rule.get("Description"):+ out["Description"] = rule["Description"]+ if rule.get("RoleArn"):+ out["RoleArn"] = rule["RoleArn"]+ return out+++# ---------------------------------------------------------------------------+# Targets+# ---------------------------------------------------------------------------+def _put_targets(data):- rule = data.get("Rule")+ rule_name = data.get("Rule")+ bus = data.get("EventBusName", "default")targets = data.get("Targets", [])- if rule not in _targets:- _targets[rule] = []- existing_ids = {t["Id"] for t in _targets[rule]}+ key = _rule_key(rule_name, bus)++ if key not in _rules:+ return error_response_json("ResourceNotFoundException", f"Rule {rule_name} does not exist.", 400)++ if key not in _targets:+ _targets[key] = []+ existing_ids = {t["Id"] for t in _targets[key]}for t in targets:if t["Id"] in existing_ids:- _targets[rule] = [x for x in _targets[rule] if x["Id"] != t["Id"]]- _targets[rule].append(t)+ _targets[key] = [x for x in _targets[key] if x["Id"] != t["Id"]]+ _targets[key].append(t)return json_response({"FailedEntryCount": 0, "FailedEntries": []})def _remove_targets(data):- rule = data.get("Rule")+ rule_name = data.get("Rule")+ bus = data.get("EventBusName", "default")ids = set(data.get("Ids", []))- if rule in _targets:- _targets[rule] = [t for t in _targets[rule] if t["Id"] not in ids]+ key = _rule_key(rule_name, bus)+ if key in _targets:+ _targets[key] = [t for t in _targets[key] if t["Id"] not in ids]return json_response({"FailedEntryCount": 0, "FailedEntries": []})def _list_targets_by_rule(data):- rule = data.get("Rule")- targets = _targets.get(rule, [])+ rule_name = data.get("Rule")+ bus = data.get("EventBusName", "default")+ key = _rule_key(rule_name, bus)+ targets = _targets.get(key, [])return json_response({"Targets": targets})+# ---------------------------------------------------------------------------+# PutEvents + event pattern matching + target dispatch+# ---------------------------------------------------------------------------+def _put_events(data):entries = data.get("Entries", [])results = []for entry in entries:event_id = new_uuid()- _events_log.append({+ bus_name = entry.get("EventBusName", "default")+ event_time = _now_iso()++ event_record = {"EventId": event_id,"Source": entry.get("Source", ""),"DetailType": entry.get("DetailType", ""),"Detail": entry.get("Detail", "{}"),- "EventBusName": entry.get("EventBusName", "default"),- "Time": time.time(),- })+ "EventBusName": bus_name,+ "Time": event_time,+ "Resources": entry.get("Resources", []),+ "Account": ACCOUNT_ID,+ "Region": REGION,+ }+ _events_log.append(event_record)results.append({"EventId": event_id})logger.debug(f"EventBridge event: {entry.get('Source')} / {entry.get('DetailType')}")++ _dispatch_event(event_record)+return json_response({"FailedEntryCount": 0, "Entries": results})+++def _dispatch_event(event):+ bus_name = event.get("EventBusName", "default")++ for key, rule in _rules.items():+ if rule.get("EventBusName", "default") != bus_name:+ continue+ if rule.get("State") != "ENABLED":+ continue+ if not rule.get("EventPattern"):+ continue++ if _matches_pattern(rule["EventPattern"], event):+ rule_targets = _targets.get(key, [])+ for target in rule_targets:+ _invoke_target(target, event, rule)+++def _matches_pattern(pattern_str, event):+ try:+ if isinstance(pattern_str, str):+ pattern = json.loads(pattern_str)+ else:+ pattern = pattern_str+ except (json.JSONDecodeError, TypeError):+ return False++ if "source" in pattern:+ if not _matches_field(event.get("Source", ""), pattern["source"]):+ return False++ if "detail-type" in pattern:+ if not _matches_field(event.get("DetailType", ""), pattern["detail-type"]):+ return False++ if "detail" in pattern:+ try:+ detail = json.loads(event.get("Detail", "{}")) if isinstance(event.get("Detail"), str) else event.get("Detail", {})+ except (json.JSONDecodeError, TypeError):+ detail = {}+ if not _matches_detail(detail, pattern["detail"]):+ return False++ if "account" in pattern:+ if not _matches_field(event.get("Account", ACCOUNT_ID), pattern["account"]):+ return False++ if "region" in pattern:+ if not _matches_field(event.get("Region", REGION), pattern["region"]):+ return False++ if "resources" in pattern:+ event_resources = event.get("Resources", [])+ for required in pattern["resources"]:+ if required not in event_resources:+ return False++ return True+++def _matches_field(value, pattern_values):+ if isinstance(pattern_values, list):+ return value in pattern_values+ return value == pattern_values+++def _matches_detail(detail, pattern):+ if not isinstance(pattern, dict):+ return True+ for key, expected in pattern.items():+ actual = detail.get(key)+ if isinstance(expected, list):+ if actual is None:+ return False+ if isinstance(actual, (str, int, float, bool)):+ matched = False+ for item in expected:+ if isinstance(item, dict):+ matched = matched or _matches_content_filter(actual, item)+ elif actual == item or str(actual) == str(item):+ matched = True+ if not matched:+ return False+ elif isinstance(actual, list):+ if not any(a in expected for a in actual):+ return False+ elif isinstance(expected, dict):+ if not isinstance(actual, dict):+ return False+ if not _matches_detail(actual, expected):+ return False+ return True+++def _matches_content_filter(value, filter_rule):+ if "prefix" in filter_rule:+ return isinstance(value, str) and value.startswith(filter_rule["prefix"])+ if "suffix" in filter_rule:+ return isinstance(value, str) and value.endswith(filter_rule["suffix"])+ if "anything-but" in filter_rule:+ excluded = filter_rule["anything-but"]+ if isinstance(excluded, list):+ return value not in excluded+ return value != excluded+ if "numeric" in filter_rule:+ ops = filter_rule["numeric"]+ try:+ num = float(value)+ except (ValueError, TypeError):+ return False+ i = 0+ while i < len(ops) - 1:+ op, threshold = ops[i], float(ops[i + 1])+ if op == ">" and not (num > threshold):+ return False+ if op == ">=" and not (num >= threshold):+ return False+ if op == "<" and not (num < threshold):+ return False+ if op == "<=" and not (num <= threshold):+ return False+ if op == "=" and not (num == threshold):+ return False+ i += 2+ return True+ if "exists" in filter_rule:+ return filter_rule["exists"] == (value is not None)+ return False+++def _invoke_target(target, event, rule):+ arn = target.get("Arn", "")++ event_payload = json.dumps({+ "version": "0",+ "id": event["EventId"],+ "source": event["Source"],+ "account": ACCOUNT_ID,+ "time": event["Time"],+ "region": REGION,+ "resources": event.get("Resources", []),+ "detail-type": event["DetailType"],+ "detail": json.loads(event["Detail"]) if isinstance(event["Detail"], str) else event["Detail"],+ })++ input_transformer = target.get("InputTransformer")+ if input_transformer:+ event_payload = _apply_input_transformer(input_transformer, event)+ elif target.get("Input"):+ event_payload = target["Input"]+ elif target.get("InputPath"):+ try:+ full = json.loads(event_payload)+ parts = target["InputPath"].strip("$.").split(".")+ val = full+ for p in parts:+ if p:+ val = val[p]+ event_payload = json.dumps(val)+ except Exception:+ pass++ try:+ if ":lambda:" in arn or ":function:" in arn:+ _dispatch_to_lambda(arn, event_payload)+ elif ":sqs:" in arn:+ _dispatch_to_sqs(arn, event_payload)+ elif ":sns:" in arn:+ _dispatch_to_sns(arn, event_payload)+ else:+ logger.warning(f"EventBridge: unsupported target type for ARN {arn}")+ except Exception as e:+ logger.error(f"EventBridge target dispatch error for {arn}: {e}")+++def _apply_input_transformer(transformer, event):+ input_paths = transformer.get("InputPathsMap", {})+ template = transformer.get("InputTemplate", "")++ try:+ full = json.loads(event.get("Detail", "{}")) if isinstance(event.get("Detail"), str) else event.get("Detail", {})+ except Exception:+ full = {}++ event_envelope = {+ "source": event.get("Source", ""),+ "detail-type": event.get("DetailType", ""),+ "detail": full,+ "account": ACCOUNT_ID,+ "region": REGION,+ "time": event.get("Time", ""),+ "id": event.get("EventId", ""),+ "resources": event.get("Resources", []),+ }++ replacements = {}+ for var_name, jpath in input_paths.items():+ parts = jpath.strip("$.").split(".")+ val = event_envelope+ try:+ for p in parts:+ if p:+ val = val[p]+ replacements[var_name] = val if isinstance(val, str) else json.dumps(val)+ except (KeyError, TypeError, IndexError):+ replacements[var_name] = ""++ result = template+ for var_name, val in replacements.items():+ result = result.replace(f"<{var_name}>", str(val))++ return result+++def _dispatch_to_lambda(arn, payload):+ from services import lambda_svc++ parts = arn.split(":")+ func_name = parts[-1].split("/")[-1] if "/" in parts[-1] else parts[-1]+ if func_name.startswith("function:"):+ func_name = func_name[len("function:"):]++ try:+ event = json.loads(payload)+ except (json.JSONDecodeError, TypeError):+ event = {"body": payload}++ headers = {"x-amz-invocation-type": "Event"}+ result = lambda_svc._invoke(func_name, event, headers)+ logger.info(f"EventBridge → Lambda {func_name}: status={result[0] if result else 'unknown'}")+++def _dispatch_to_sqs(arn, payload):+ from services import sqs as _sqs++ queue_name = arn.split(":")[-1]+ queue_url = _sqs._queue_url(queue_name)+ queue = _sqs._queues.get(queue_url)+ if not queue:+ logger.warning(f"EventBridge → SQS: queue {queue_name} not found")+ return++ msg_id = new_uuid()+ md5 = hashlib.md5(payload.encode()).hexdigest()+ queue["messages"].append({+ "id": msg_id,+ "body": payload,+ "md5": md5,+ "receipt_handle": None,+ "sent_at": time.time(),+ "visible_at": time.time(),+ "receive_count": 0,+ "attributes": {},+ })+ logger.info(f"EventBridge → SQS {queue_name}")+++def _dispatch_to_sns(arn, payload):+ from services import sns as _sns++ topic = _sns._topics.get(arn)+ if not topic:+ logger.warning(f"EventBridge → SNS: topic {arn} not found")+ return++ msg_id = new_uuid()+ topic["messages"].append({+ "id": msg_id,+ "message": payload,+ "subject": "EventBridge Notification",+ "timestamp": time.time(),+ })+ _sns._fanout(arn, msg_id, payload, "EventBridge Notification")+ logger.info(f"EventBridge → SNS {arn}")+++# ---------------------------------------------------------------------------+# Tags+# ---------------------------------------------------------------------------++def _tag_resource(data):+ arn = data.get("ResourceARN", "")+ tags = data.get("Tags", [])+ if arn not in _tags:+ _tags[arn] = {}+ for t in tags:+ _tags[arn][t["Key"]] = t["Value"]+ return json_response({})+++def _untag_resource(data):+ arn = data.get("ResourceARN", "")+ keys = data.get("TagKeys", [])+ if arn in _tags:+ for k in keys:+ _tags[arn].pop(k, None)+ return json_response({})+++def _list_tags_for_resource(data):+ arn = data.get("ResourceARN", "")+ tag_dict = _tags.get(arn, {})+ tag_list = [{"Key": k, "Value": v} for k, v in tag_dict.items()]+ return json_response({"Tags": tag_list})+++# ---------------------------------------------------------------------------+# Archives (stubs)+# ---------------------------------------------------------------------------++def _create_archive(data):+ name = data.get("ArchiveName")+ if not name:+ return error_response_json("ValidationException", "ArchiveName is required", 400)+ if name in _archives:+ return error_response_json("ResourceAlreadyExistsException", f"Archive {name} already exists", 400)++ source_arn = data.get("EventSourceArn", "")+ arn = f"arn:aws:events:{REGION}:{ACCOUNT_ID}:archive/{name}"+ _archives[name] = {+ "ArchiveName": name,+ "ArchiveArn": arn,+ "EventSourceArn": source_arn,+ "Description": data.get("Description", ""),+ "EventPattern": data.get("EventPattern", ""),+ "RetentionDays": data.get("RetentionDays", 0),+ "State": "ENABLED",+ "CreationTime": _now_iso(),+ "EventCount": 0,+ "SizeBytes": 0,+ }+ return json_response({"ArchiveArn": arn, "State": "ENABLED", "CreationTime": _archives[name]["CreationTime"]})+++def _delete_archive(data):+ name = data.get("ArchiveName")+ if name not in _archives:+ return error_response_json("ResourceNotFoundException", f"Archive {name} does not exist.", 400)+ del _archives[name]+ return json_response({})+++def _describe_archive(data):+ name = data.get("ArchiveName")+ archive = _archives.get(name)+ if not archive:+ return error_response_json("ResourceNotFoundException", f"Archive {name} does not exist.", 400)+ return json_response(archive)+++def _list_archives(data):+ prefix = data.get("NamePrefix", "")+ source_arn = data.get("EventSourceArn", "")+ state = data.get("State", "")+ results = []+ for name, archive in _archives.items():+ if prefix and not name.startswith(prefix):+ continue+ if source_arn and archive.get("EventSourceArn") != source_arn:+ continue+ if state and archive.get("State") != state:+ continue+ results.append(archive)+ return json_response({"Archives": results})+++# ---------------------------------------------------------------------------+# Permissions (resource policies)+# ---------------------------------------------------------------------------++def _put_permission(data):+ bus_name = data.get("EventBusName", "default")+ statement_id = data.get("StatementId")+ if not statement_id:+ return error_response_json("ValidationException", "StatementId is required", 400)++ if bus_name not in _event_bus_policies:+ _event_bus_policies[bus_name] = {"Version": "2012-10-17", "Statement": []}++ policy = _event_bus_policies[bus_name]+ policy["Statement"] = [s for s in policy["Statement"] if s.get("Sid") != statement_id]++ statement = {+ "Sid": statement_id,+ "Effect": "Allow",+ "Principal": data.get("Principal", "*"),+ "Action": data.get("Action", "events:PutEvents"),+ "Resource": f"arn:aws:events:{REGION}:{ACCOUNT_ID}:event-bus/{bus_name}",+ }+ condition = data.get("Condition")+ if condition:+ statement["Condition"] = condition+ policy["Statement"].append(statement)++ return json_response({})+++def _remove_permission(data):+ bus_name = data.get("EventBusName", "default")+ statement_id = data.get("StatementId")+ remove_all = data.get("RemoveAllPermissions", False)++ if remove_all:+ _event_bus_policies.pop(bus_name, None)+ return json_response({})++ if bus_name in _event_bus_policies:+ policy = _event_bus_policies[bus_name]+ policy["Statement"] = [s for s in policy["Statement"] if s.get("Sid") != statement_id]+ if not policy["Statement"]:+ del _event_bus_policies[bus_name]++ return json_response({})+++# ---------------------------------------------------------------------------+# Connections+# ---------------------------------------------------------------------------++def _create_connection(data):+ name = data.get("Name")+ if not name:+ return error_response_json("ValidationException", "Name is required", 400)+ if name in _connections:+ return error_response_json("ResourceAlreadyExistsException",+ f"Connection {name} already exists", 400)++ arn = f"arn:aws:events:{REGION}:{ACCOUNT_ID}:connection/{name}"+ now = _now_iso()+ _connections[name] = {+ "Name": name,+ "ConnectionArn": arn,+ "ConnectionState": "AUTHORIZED",+ "AuthorizationType": data.get("AuthorizationType", ""),+ "AuthParameters": data.get("AuthParameters", {}),+ "Description": data.get("Description", ""),+ "CreationTime": now,+ "LastModifiedTime": now,+ "LastAuthorizedTime": now,+ }+ return json_response({+ "ConnectionArn": arn,+ "ConnectionState": "AUTHORIZED",+ "CreationTime": now,+ })+++def _describe_connection(data):+ name = data.get("Name")+ conn = _connections.get(name)+ if not conn:+ return error_response_json("ResourceNotFoundException",+ f"Connection {name} does not exist.", 400)+ return json_response(conn)+++def _delete_connection(data):+ name = data.get("Name")+ conn = _connections.pop(name, None)+ if not conn:+ return error_response_json("ResourceNotFoundException",+ f"Connection {name} does not exist.", 400)+ return json_response({+ "ConnectionArn": conn["ConnectionArn"],+ "ConnectionState": "DELETING",+ "LastModifiedTime": _now_iso(),+ })+++def _list_connections(data):+ prefix = data.get("NamePrefix", "")+ state = data.get("ConnectionState", "")+ results = []+ for name in sorted(_connections):+ conn = _connections[name]+ if prefix and not name.startswith(prefix):+ continue+ if state and conn.get("ConnectionState") != state:+ continue+ results.append({+ "Name": conn["Name"],+ "ConnectionArn": conn["ConnectionArn"],+ "ConnectionState": conn["ConnectionState"],+ "AuthorizationType": conn["AuthorizationType"],+ "CreationTime": conn["CreationTime"],+ "LastModifiedTime": conn["LastModifiedTime"],+ "LastAuthorizedTime": conn.get("LastAuthorizedTime", ""),+ })+ return json_response({"Connections": results})+++def _update_connection(data):+ name = data.get("Name")+ if name not in _connections:+ return error_response_json("ResourceNotFoundException",+ f"Connection {name} does not exist.", 400)+ conn = _connections[name]+ now = _now_iso()+ for key in ("AuthorizationType", "AuthParameters", "Description"):+ if key in data:+ conn[key] = data[key]+ conn["LastModifiedTime"] = now+ conn["ConnectionState"] = "AUTHORIZED"+ conn["LastAuthorizedTime"] = now++ return json_response({+ "ConnectionArn": conn["ConnectionArn"],+ "ConnectionState": conn["ConnectionState"],+ "LastModifiedTime": now,+ })+++# ---------------------------------------------------------------------------+# API Destinations+# ---------------------------------------------------------------------------++def _create_api_destination(data):+ name = data.get("Name")+ if not name:+ return error_response_json("ValidationException", "Name is required", 400)+ if name in _api_destinations:+ return error_response_json("ResourceAlreadyExistsException",+ f"ApiDestination {name} already exists", 400)++ arn = f"arn:aws:events:{REGION}:{ACCOUNT_ID}:api-destination/{name}"+ now = _now_iso()+ _api_destinations[name] = {+ "Name": name,+ "ApiDestinationArn": arn,+ "ApiDestinationState": "ACTIVE",+ "ConnectionArn": data.get("ConnectionArn", ""),+ "InvocationEndpoint": data.get("InvocationEndpoint", ""),+ "HttpMethod": data.get("HttpMethod", ""),+ "InvocationRateLimitPerSecond": data.get("InvocationRateLimitPerSecond", 300),+ "Description": data.get("Description", ""),+ "CreationTime": now,+ "LastModifiedTime": now,+ }+ return json_response({+ "ApiDestinationArn": arn,+ "ApiDestinationState": "ACTIVE",+ "CreationTime": now,+ "LastModifiedTime": now,+ })+++def _describe_api_destination(data):+ name = data.get("Name")+ dest = _api_destinations.get(name)+ if not dest:+ return error_response_json("ResourceNotFoundException",+ f"ApiDestination {name} does not exist.", 400)+ return json_response(dest)+++def _delete_api_destination(data):+ name = data.get("Name")+ if name not in _api_destinations:+ return error_response_json("ResourceNotFoundException",+ f"ApiDestination {name} does not exist.", 400)+ del _api_destinations[name]+ return json_response({})+++def _list_api_destinations(data):+ prefix = data.get("NamePrefix", "")+ conn_arn = data.get("ConnectionArn", "")+ results = []+ for name in sorted(_api_destinations):+ dest = _api_destinations[name]+ if prefix and not name.startswith(prefix):+ continue+ if conn_arn and dest.get("ConnectionArn") != conn_arn:+ continue+ results.append({+ "Name": dest["Name"],+ "ApiDestinationArn": dest["ApiDestinationArn"],+ "ApiDestinationState": dest["ApiDestinationState"],+ "ConnectionArn": dest["ConnectionArn"],+ "InvocationEndpoint": dest["InvocationEndpoint"],+ "HttpMethod": dest["HttpMethod"],+ "CreationTime": dest["CreationTime"],+ "LastModifiedTime": dest["LastModifiedTime"],+ })+ return json_response({"ApiDestinations": results})+++def _update_api_destination(data):+ name = data.get("Name")+ if name not in _api_destinations:+ return error_response_json("ResourceNotFoundException",+ f"ApiDestination {name} does not exist.", 400)+ dest = _api_destinations[name]+ now = _now_iso()+ for key in ("ConnectionArn", "InvocationEndpoint", "HttpMethod",+ "InvocationRateLimitPerSecond", "Description"):+ if key in data:+ dest[key] = data[key]+ dest["LastModifiedTime"] = now++ return json_response({+ "ApiDestinationArn": dest["ApiDestinationArn"],+ "ApiDestinationState": dest["ApiDestinationState"],+ "LastModifiedTime": now,+ })+++def reset():+ global _event_buses+ _rules.clear()+ _targets.clear()+ _events_log.clear()+ _tags.clear()+ _archives.clear()+ _event_bus_policies.clear()+ _connections.clear()+ _api_destinations.clear()+ _event_buses = {+ "default": {+ "Name": "default",+ "Arn": f"arn:aws:events:{REGION}:{ACCOUNT_ID}:event-bus/default",+ "CreationTime": _now_iso(),+ }+ }diff --git a/services/glue.py b/services/glue.pyindex aec81abb..963025a3 100644--- a/services/glue.py+++ b/services/glue.py@@ -2,7 +2,10 @@Glue Service Emulator.JSON-based API via X-Amz-Target (AWSGlue).Supports full Data Catalog: Databases, Tables, Partitions, Connections, Crawlers, Jobs, JobRuns.-Job execution runs Python scripts via subprocess (same approach as Lambda).+Also: SecurityConfigurations, Classifiers, PartitionIndexes, CrawlerMetrics, Tags,+ Triggers, Workflows.+Job execution runs Python scripts via subprocess in background threads.+Crawlers transition through RUNNING state with a configurable timer."""import os@@ -10,6 +13,7 @@ import jsonimport timeimport subprocessimport tempfile+import threadingimport loggingfrom core.responses import json_response, error_response_json, new_uuid@@ -18,14 +22,27 @@ logger = logging.getLogger("glue")ACCOUNT_ID = "000000000000"REGION = "us-east-1"+CRAWLER_RUN_SECONDS = int(os.environ.get("GLUE_CRAWLER_RUN_SECONDS", "5"))+S3_DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/localstack-data/s3")-_databases: dict = {} # db_name -> {Name, Description, LocationUri, Parameters, CreateTime}-_tables: dict = {} # db_name/table_name -> table dict-_partitions: dict = {} # db_name/table_name -> [partition, ...]+_databases: dict = {}+_tables: dict = {} # "db_name/table_name" -> table dict+_partitions: dict = {} # "db_name/table_name" -> [partition, ...]+_partition_indexes: dict = {} # "db_name/table_name" -> [index, ...]_connections: dict = {}_crawlers: dict = {}_jobs: dict = {}-_job_runs: dict = {} # job_name -> [run, ...]+_job_runs: dict = {} # job_name -> [run, ...]+_tags: dict = {} # arn -> {key: value, ...}+_security_configs: dict = {}+_classifiers: dict = {}+_triggers: dict = {} # trigger_name -> trigger dict+_workflows: dict = {} # workflow_name -> workflow dict+_workflow_runs: dict = {} # workflow_name -> [run, ...]+++def _arn(resource_type, name):+ return f"arn:aws:glue:{REGION}:{ACCOUNT_ID}:{resource_type}/{name}"async def handle_request(method, path, headers, body, query_params):@@ -57,6 +74,10 @@ async def handle_request(method, path, headers, body, query_params):"GetPartition": _get_partition,"GetPartitions": _get_partitions,"BatchCreatePartition": _batch_create_partition,+ "BatchGetPartition": _batch_get_partition,+ # Partition Indexes+ "CreatePartitionIndex": _create_partition_index,+ "GetPartitionIndexes": _get_partition_indexes,# Connections"CreateConnection": _create_connection,"DeleteConnection": _delete_connection,@@ -67,8 +88,10 @@ async def handle_request(method, path, headers, body, query_params):"DeleteCrawler": _delete_crawler,"GetCrawler": _get_crawler,"GetCrawlers": _get_crawlers,+ "UpdateCrawler": _update_crawler,"StartCrawler": _start_crawler,"StopCrawler": _stop_crawler,+ "GetCrawlerMetrics": _get_crawler_metrics,# Jobs"CreateJob": _create_job,"DeleteJob": _delete_job,@@ -79,6 +102,32 @@ async def handle_request(method, path, headers, body, query_params):"GetJobRun": _get_job_run,"GetJobRuns": _get_job_runs,"BatchStopJobRun": _batch_stop_job_run,+ # Security Configurations+ "CreateSecurityConfiguration": _create_security_configuration,+ "DeleteSecurityConfiguration": _delete_security_configuration,+ "GetSecurityConfiguration": _get_security_configuration,+ "GetSecurityConfigurations": _get_security_configurations,+ # Classifiers+ "CreateClassifier": _create_classifier,+ "GetClassifier": _get_classifier,+ "GetClassifiers": _get_classifiers,+ "DeleteClassifier": _delete_classifier,+ # Triggers+ "CreateTrigger": _create_trigger,+ "GetTrigger": _get_trigger,+ "DeleteTrigger": _delete_trigger,+ "UpdateTrigger": _update_trigger,+ "StartTrigger": _start_trigger,+ "StopTrigger": _stop_trigger,+ "ListTriggers": _list_triggers,+ "BatchGetTriggers": _batch_get_triggers,+ "GetTriggers": _get_triggers,+ # Workflows+ "CreateWorkflow": _create_workflow,+ "GetWorkflow": _get_workflow,+ "DeleteWorkflow": _delete_workflow,+ "UpdateWorkflow": _update_workflow,+ "StartWorkflowRun": _start_workflow_run,# Tags"TagResource": _tag_resource,"UntagResource": _untag_resource,@@ -116,10 +165,11 @@ def _delete_database(data):if name not in _databases:return error_response_json("EntityNotFoundException", f"Database {name} not found", 400)del _databases[name]- # Remove all tables in this databasekeys_to_del = [k for k in _tables if k.startswith(f"{name}/")]for k in keys_to_del:del _tables[k]+ _partitions.pop(k, None)+ _partition_indexes.pop(k, None)return json_response({})@@ -140,7 +190,10 @@ def _update_database(data):db_input = data.get("DatabaseInput", {})if name not in _databases:return error_response_json("EntityNotFoundException", f"Database {name} not found", 400)- _databases[name].update({k: v for k, v in db_input.items() if k != "Name"})+ safe_keys = {"Description", "LocationUri", "Parameters"}+ for k in safe_keys:+ if k in db_input:+ _databases[name][k] = db_input[k]return json_response({})@@ -176,6 +229,8 @@ def _delete_table(data):name = data.get("Name")key = f"{db_name}/{name}"_tables.pop(key, None)+ _partitions.pop(key, None)+ _partition_indexes.pop(key, None)return json_response({})@@ -191,7 +246,10 @@ def _get_table(data):def _get_tables(data):db_name = data.get("DatabaseName")+ expression = data.get("Expression", "")tables = [t for k, t in _tables.items() if k.startswith(f"{db_name}/")]+ if expression:+ tables = [t for t in tables if _simple_glob_match(expression, t["Name"])]return json_response({"TableList": tables})@@ -202,7 +260,11 @@ def _update_table(data):key = f"{db_name}/{name}"if key not in _tables:return error_response_json("EntityNotFoundException", f"Table {name} not found", 400)- _tables[key].update({k: v for k, v in table_input.items() if k != "Name"})+ safe_keys = {"Description", "Owner", "StorageDescriptor", "PartitionKeys",+ "TableType", "Parameters", "ViewOriginalText", "ViewExpandedText"}+ for k in safe_keys:+ if k in table_input:+ _tables[key][k] = table_input[k]_tables[key]["UpdateTime"] = time.time()return json_response({})@@ -214,9 +276,12 @@ def _batch_delete_table(data):for name in names:key = f"{db_name}/{name}"if key not in _tables:- errors.append({"TableName": name, "ErrorDetail": {"ErrorCode": "EntityNotFoundException", "ErrorMessage": "Table not found"}})+ errors.append({"TableName": name, "ErrorDetail": {+ "ErrorCode": "EntityNotFoundException", "ErrorMessage": "Table not found"}})else:del _tables[key]+ _partitions.pop(key, None)+ _partition_indexes.pop(key, None)return json_response({"Errors": errors})@@ -229,7 +294,21 @@ def _create_partition(data):key = f"{db_name}/{table_name}"if key not in _partitions:_partitions[key] = []- _partitions[key].append({**partition_input, "CreationTime": time.time(), "LastAccessTime": time.time()})++ values = partition_input.get("Values", [])+ for existing in _partitions[key]:+ if existing.get("Values") == values:+ return error_response_json("AlreadyExistsException",+ f"Partition with values {values} already exists", 400)++ _partitions[key].append({+ **partition_input,+ "DatabaseName": db_name,+ "TableName": table_name,+ "CreationTime": time.time(),+ "LastAccessTime": time.time(),+ "CatalogId": ACCOUNT_ID,+ })return json_response({})@@ -267,9 +346,69 @@ def _batch_create_partition(data):key = f"{db_name}/{table_name}"if key not in _partitions:_partitions[key] = []+ errors = []for pi in data.get("PartitionInputList", []):- _partitions[key].append({**pi, "CreationTime": time.time()})- return json_response({"Errors": []})+ values = pi.get("Values", [])+ dupe = any(p.get("Values") == values for p in _partitions[key])+ if dupe:+ errors.append({"PartitionValues": values, "ErrorDetail": {+ "ErrorCode": "AlreadyExistsException",+ "ErrorMessage": f"Partition already exists"}})+ else:+ _partitions[key].append({+ **pi,+ "DatabaseName": db_name,+ "TableName": table_name,+ "CreationTime": time.time(),+ "CatalogId": ACCOUNT_ID,+ })+ return json_response({"Errors": errors})+++def _batch_get_partition(data):+ db_name = data.get("DatabaseName")+ table_name = data.get("TableName")+ key = f"{db_name}/{table_name}"+ entries = data.get("PartitionsToGet", [])+ partitions = []+ unprocessed = []+ all_parts = _partitions.get(key, [])+ for entry in entries:+ values = entry.get("Values", [])+ found = None+ for p in all_parts:+ if p.get("Values") == values:+ found = p+ break+ if found:+ partitions.append(found)+ else:+ unprocessed.append(entry)+ return json_response({"Partitions": partitions, "UnprocessedKeys": unprocessed})+++# ---- Partition Indexes ----++def _create_partition_index(data):+ db_name = data.get("DatabaseName")+ table_name = data.get("TableName")+ index_input = data.get("PartitionIndex", {})+ key = f"{db_name}/{table_name}"+ if key not in _partition_indexes:+ _partition_indexes[key] = []+ _partition_indexes[key].append({+ "IndexName": index_input.get("IndexName", ""),+ "Keys": index_input.get("Keys", []),+ "IndexStatus": "ACTIVE",+ })+ return json_response({})+++def _get_partition_indexes(data):+ db_name = data.get("DatabaseName")+ table_name = data.get("TableName")+ key = f"{db_name}/{table_name}"+ return json_response({"PartitionIndexDescriptorList": _partition_indexes.get(key, [])})# ---- Connections ----@@ -303,7 +442,6 @@ def _get_connections(data):def _create_crawler(data):name = data.get("Name")schedule = data.get("Schedule", "")- # Schedule can be passed as a string (cron expression) or omittedschedule_struct = {"ScheduleExpression": schedule} if schedule else {}_crawlers[name] = {"Name": name,@@ -312,6 +450,11 @@ def _create_crawler(data):"Description": data.get("Description", ""),"Targets": data.get("Targets", {}),"Schedule": schedule_struct,+ "Classifiers": data.get("Classifiers", []),+ "TablePrefix": data.get("TablePrefix", ""),+ "SchemaChangePolicy": data.get("SchemaChangePolicy", {}),+ "RecrawlPolicy": data.get("RecrawlPolicy", {}),+ "LineageConfiguration": data.get("LineageConfiguration", {}),"State": "READY","CrawlElapsedTime": 0,"CreationTime": time.time(),@@ -325,7 +468,10 @@ def _create_crawler(data):def _delete_crawler(data):- _crawlers.pop(data.get("Name"), None)+ name = data.get("Name")+ if name not in _crawlers:+ return error_response_json("EntityNotFoundException", f"Crawler {name} not found", 400)+ del _crawlers[name]return json_response({})@@ -341,42 +487,116 @@ def _get_crawlers(data):return json_response({"Crawlers": list(_crawlers.values())})+def _update_crawler(data):+ name = data.get("Name")+ if name not in _crawlers:+ return error_response_json("EntityNotFoundException", f"Crawler {name} not found", 400)+ crawler = _crawlers[name]+ updatable = {"Role", "DatabaseName", "Description", "Targets", "Schedule",+ "Classifiers", "TablePrefix", "SchemaChangePolicy", "RecrawlPolicy",+ "LineageConfiguration", "Configuration", "CrawlerSecurityConfiguration"}+ for k in updatable:+ if k in data:+ if k == "Schedule":+ sched = data[k]+ crawler["Schedule"] = {"ScheduleExpression": sched} if isinstance(sched, str) else sched+ else:+ crawler[k] = data[k]+ crawler["LastUpdated"] = time.time()+ crawler["Version"] = crawler.get("Version", 1) + 1+ return json_response({})++def _start_crawler(data):name = data.get("Name")if name not in _crawlers:return error_response_json("EntityNotFoundException", f"Crawler {name} not found", 400)- _crawlers[name]["State"] = "RUNNING"- # Immediately mark as ready (no actual crawling)- _crawlers[name]["State"] = "READY"- _crawlers[name]["LastCrawl"] = {"Status": "SUCCEEDED", "StartTime": time.time(), "EndTime": time.time()}+ crawler = _crawlers[name]+ if crawler["State"] == "RUNNING":+ return error_response_json("CrawlerRunningException",+ f"Crawler {name} is already running", 400)++ crawler["State"] = "RUNNING"+ crawler["CrawlElapsedTime"] = 0+ start_time = time.time()++ def _finish_crawl():+ if name in _crawlers and _crawlers[name]["State"] == "RUNNING":+ _crawlers[name]["State"] = "READY"+ _crawlers[name]["CrawlElapsedTime"] = int((time.time() - start_time) * 1000)+ _crawlers[name]["LastCrawl"] = {+ "Status": "SUCCEEDED",+ "LogGroup": f"/aws-glue/crawlers/{name}",+ "LogStream": new_uuid(),+ "MessagePrefix": "",+ "StartTime": start_time,+ "EndTime": time.time(),+ }+ logger.info(f"Glue: Crawler {name} finished after {CRAWLER_RUN_SECONDS}s")++ timer = threading.Timer(CRAWLER_RUN_SECONDS, _finish_crawl)+ timer.daemon = True+ timer.start()++ logger.info(f"Glue: Crawler {name} started (will run for {CRAWLER_RUN_SECONDS}s)")return json_response({})def _stop_crawler(data):name = data.get("Name")- if name in _crawlers:- _crawlers[name]["State"] = "READY"+ if name not in _crawlers:+ return error_response_json("EntityNotFoundException", f"Crawler {name} not found", 400)+ if _crawlers[name]["State"] != "RUNNING":+ return error_response_json("CrawlerNotRunningException",+ f"Crawler {name} is not running", 400)+ _crawlers[name]["State"] = "STOPPING"+ _crawlers[name]["State"] = "READY"return json_response({})+def _get_crawler_metrics(data):+ crawler_names = data.get("CrawlerNameList", list(_crawlers.keys()))+ metrics = []+ for name in crawler_names:+ crawler = _crawlers.get(name)+ if crawler:+ metrics.append({+ "CrawlerName": name,+ "TimeLeftSeconds": 0.0,+ "StillEstimating": False,+ "LastRuntimeSeconds": crawler.get("CrawlElapsedTime", 0) / 1000.0,+ "MedianRuntimeSeconds": crawler.get("CrawlElapsedTime", 0) / 1000.0,+ "TablesCreated": 0,+ "TablesUpdated": 0,+ "TablesDeleted": 0,+ })+ return json_response({"CrawlerMetricsList": metrics})++# ---- Jobs ----def _create_job(data):name = data.get("Name")if not name:return error_response_json("InvalidInputException", "Name is required", 400)+ if name in _jobs:+ return error_response_json("AlreadyExistsException", f"Job {name} already exists", 400)_jobs[name] = {"Name": name,"Description": data.get("Description", ""),"Role": data.get("Role", ""),"Command": data.get("Command", {}),"DefaultArguments": data.get("DefaultArguments", {}),+ "NonOverridableArguments": data.get("NonOverridableArguments", {}),"Connections": data.get("Connections", {}),"MaxRetries": data.get("MaxRetries", 0),"Timeout": data.get("Timeout", 2880),"GlueVersion": data.get("GlueVersion", "3.0"),"NumberOfWorkers": data.get("NumberOfWorkers", 2),"WorkerType": data.get("WorkerType", "G.1X"),+ "MaxCapacity": data.get("MaxCapacity"),+ "SecurityConfiguration": data.get("SecurityConfiguration", ""),+ "Tags": data.get("Tags", {}),"CreatedOn": time.time(),"LastModifiedOn": time.time(),}@@ -408,11 +628,34 @@ def _update_job(data):job_update = data.get("JobUpdate", {})if name not in _jobs:return error_response_json("EntityNotFoundException", f"Job {name} not found", 400)- _jobs[name].update(job_update)+ updatable = {"Description", "Role", "Command", "DefaultArguments",+ "NonOverridableArguments", "Connections", "MaxRetries", "Timeout",+ "GlueVersion", "NumberOfWorkers", "WorkerType", "MaxCapacity",+ "SecurityConfiguration"}+ for k in updatable:+ if k in job_update:+ _jobs[name][k] = job_update[k]_jobs[name]["LastModifiedOn"] = time.time()return json_response({"JobName": name})+def _resolve_script(script_location):+ """Resolve a script location to a local path. Supports local paths and s3:// URIs."""+ if not script_location:+ return None+ if os.path.exists(script_location):+ return script_location+ if script_location.startswith("s3://"):+ stripped = script_location[5:]+ parts = stripped.split("/", 1)+ bucket = parts[0]+ key = parts[1] if len(parts) > 1 else ""+ local_path = os.path.join(S3_DATA_DIR, bucket, key)+ if os.path.exists(local_path):+ return local_path+ return None++def _start_job_run(data):job_name = data.get("JobName")if job_name not in _jobs:@@ -428,40 +671,65 @@ def _start_job_run(data):"StartedOn": time.time(),"LastModifiedOn": time.time(),"CompletedOn": None,- "JobRunState": "RUNNING",+ "JobRunState": "STARTING","Arguments": args,"ErrorMessage": "",+ "PredecessorRuns": [],+ "AllocatedCapacity": job.get("MaxCapacity") or job.get("NumberOfWorkers", 2),"ExecutionTime": 0,- "Attempt": 0,+ "Timeout": job.get("Timeout", 2880),+ "MaxCapacity": job.get("MaxCapacity"),+ "WorkerType": job.get("WorkerType", "G.1X"),+ "NumberOfWorkers": job.get("NumberOfWorkers", 2),+ "SecurityConfiguration": job.get("SecurityConfiguration", ""),"GlueVersion": job.get("GlueVersion", "3.0"),+ "Attempt": 0,}- # Try to actually run the script if it's a Python shell job- script_location = job.get("Command", {}).get("ScriptLocation", "")- if script_location and script_location.endswith(".py") and os.path.exists(script_location):- try:- env = dict(os.environ)- env.update({k.lstrip("--"): v for k, v in args.items() if k.startswith("--")})- proc = subprocess.run(- ["python3", script_location],- capture_output=True, text=True, timeout=job.get("Timeout", 300),- env=env,- )- if proc.returncode == 0:- run["JobRunState"] = "SUCCEEDED"- else:- run["JobRunState"] = "FAILED"- run["ErrorMessage"] = proc.stderr[:500]- except Exception as e:- run["JobRunState"] = "FAILED"- run["ErrorMessage"] = str(e)- else:- # Mock success- run["JobRunState"] = "SUCCEEDED"-- run["CompletedOn"] = time.time()- run["ExecutionTime"] = int(run["CompletedOn"] - run["StartedOn"])+ if job_name not in _job_runs:+ _job_runs[job_name] = []_job_runs[job_name].append(run)++ def _execute():+ run["JobRunState"] = "RUNNING"+ run["LastModifiedOn"] = time.time()++ script_location = job.get("Command", {}).get("ScriptLocation", "")+ resolved = _resolve_script(script_location)+ if resolved and resolved.endswith(".py"):+ try:+ env = dict(os.environ)+ for k, v in args.items():+ env_key = k.lstrip("-")+ if env_key:+ env[env_key] = str(v)+ proc = subprocess.run(+ ["python3", resolved],+ capture_output=True, text=True,+ timeout=min(job.get("Timeout", 300), 600),+ env=env,+ )+ if proc.returncode == 0:+ run["JobRunState"] = "SUCCEEDED"+ else:+ run["JobRunState"] = "FAILED"+ run["ErrorMessage"] = proc.stderr[:2000] if proc.stderr else f"Exit code {proc.returncode}"+ except subprocess.TimeoutExpired:+ run["JobRunState"] = "TIMEOUT"+ run["ErrorMessage"] = "Job execution timed out"+ except Exception as e:+ run["JobRunState"] = "FAILED"+ run["ErrorMessage"] = str(e)[:2000]+ else:+ run["JobRunState"] = "SUCCEEDED"++ run["CompletedOn"] = time.time()+ run["ExecutionTime"] = int(run["CompletedOn"] - run["StartedOn"])+ run["LastModifiedOn"] = time.time()++ thread = threading.Thread(target=_execute, daemon=True)+ thread.start()+return json_response({"JobRunId": run_id})@@ -483,20 +751,302 @@ def _batch_stop_job_run(data):job_name = data.get("JobName")run_ids = data.get("JobRunIds", [])errors = []+ successful = []for run_id in run_ids:found = Falsefor run in _job_runs.get(job_name, []):if run["Id"] == run_id:- run["JobRunState"] = "STOPPED"+ if run["JobRunState"] in ("STARTING", "RUNNING"):+ run["JobRunState"] = "STOPPED"+ run["CompletedOn"] = time.time()+ run["LastModifiedOn"] = time.time()+ successful.append({"JobName": job_name, "JobRunId": run_id})+ else:+ errors.append({"JobName": job_name, "JobRunId": run_id,+ "ErrorDetail": {"ErrorCode": "InvalidInputException",+ "ErrorMessage": f"Run {run_id} is in state {run['JobRunState']}"}})found = Truebreakif not found:- errors.append({"JobName": job_name, "JobRunId": run_id, "ErrorDetail": {"ErrorCode": "EntityNotFoundException", "ErrorMessage": "Run not found"}})- return json_response({"SuccessfulSubmissions": [{"JobName": job_name, "JobRunId": r} for r in run_ids if r not in [e["JobRunId"] for e in errors]], "Errors": errors})+ errors.append({"JobName": job_name, "JobRunId": run_id,+ "ErrorDetail": {"ErrorCode": "EntityNotFoundException",+ "ErrorMessage": "Run not found"}})+ return json_response({"SuccessfulSubmissions": successful, "Errors": errors})+++# ---- Security Configurations ----++def _create_security_configuration(data):+ name = data.get("Name")+ if not name:+ return error_response_json("InvalidInputException", "Name is required", 400)+ if name in _security_configs:+ return error_response_json("AlreadyExistsException",+ f"Security configuration {name} already exists", 400)+ _security_configs[name] = {+ "Name": name,+ "CreatedTimeStamp": time.time(),+ "EncryptionConfiguration": data.get("EncryptionConfiguration", {}),+ }+ return json_response({"Name": name, "CreatedTimestamp": _security_configs[name]["CreatedTimeStamp"]})+++def _delete_security_configuration(data):+ name = data.get("Name")+ if name not in _security_configs:+ return error_response_json("EntityNotFoundException",+ f"Security configuration {name} not found", 400)+ del _security_configs[name]+ return json_response({})+++def _get_security_configuration(data):+ name = data.get("Name")+ config = _security_configs.get(name)+ if not config:+ return error_response_json("EntityNotFoundException",+ f"Security configuration {name} not found", 400)+ return json_response({"SecurityConfiguration": config})+++def _get_security_configurations(data):+ return json_response({"SecurityConfigurations": list(_security_configs.values())})+++# ---- Classifiers ----++def _create_classifier(data):+ grok = data.get("GrokClassifier")+ xml_cls = data.get("XMLClassifier")+ json_cls = data.get("JsonClassifier")+ csv_cls = data.get("CsvClassifier")++ classifier = grok or xml_cls or json_cls or csv_cls+ if not classifier:+ return error_response_json("InvalidInputException",+ "Must provide one of GrokClassifier, XMLClassifier, JsonClassifier, CsvClassifier", 400)++ name = classifier.get("Name")+ if not name:+ return error_response_json("InvalidInputException", "Classifier name is required", 400)+ if name in _classifiers:+ return error_response_json("AlreadyExistsException",+ f"Classifier {name} already exists", 400)++ cls_type = "GrokClassifier" if grok else "XMLClassifier" if xml_cls else "JsonClassifier" if json_cls else "CsvClassifier"+ _classifiers[name] = {+ cls_type: {**classifier, "CreationTime": time.time(), "LastUpdated": time.time(), "Version": 1},+ }+ return json_response({})+++def _get_classifier(data):+ name = data.get("Name")+ cls = _classifiers.get(name)+ if not cls:+ return error_response_json("EntityNotFoundException", f"Classifier {name} not found", 400)+ return json_response({"Classifier": cls})+++def _get_classifiers(data):+ return json_response({"Classifiers": list(_classifiers.values())})+++def _delete_classifier(data):+ name = data.get("Name")+ if name not in _classifiers:+ return error_response_json("EntityNotFoundException", f"Classifier {name} not found", 400)+ del _classifiers[name]+ return json_response({})+++# ---- Triggers ----++def _create_trigger(data):+ name = data.get("Name")+ if not name:+ return error_response_json("InvalidInputException", "Name is required", 400)+ if name in _triggers:+ return error_response_json("AlreadyExistsException", f"Trigger {name} already exists", 400)++ trigger_type = data.get("Type", "ON_DEMAND")+ _triggers[name] = {+ "Name": name,+ "Type": trigger_type,+ "State": "CREATED",+ "Schedule": data.get("Schedule", ""),+ "Predicate": data.get("Predicate", {}),+ "Actions": data.get("Actions", []),+ "Description": data.get("Description", ""),+ "WorkflowName": data.get("WorkflowName", ""),+ "Tags": data.get("Tags", {}),+ "CreatedOn": time.time(),+ "LastModifiedOn": time.time(),+ }+ if data.get("StartOnCreation", False):+ _triggers[name]["State"] = "ACTIVATED"+ if data.get("Tags"):+ arn = _arn("trigger", name)+ _tags[arn] = dict(data["Tags"])+ return json_response({"Name": name})+++def _get_trigger(data):+ name = data.get("Name")+ trigger = _triggers.get(name)+ if not trigger:+ return error_response_json("EntityNotFoundException", f"Trigger {name} not found", 400)+ return json_response({"Trigger": trigger})+++def _delete_trigger(data):+ name = data.get("Name")+ if name not in _triggers:+ return error_response_json("EntityNotFoundException", f"Trigger {name} not found", 400)+ del _triggers[name]+ _tags.pop(_arn("trigger", name), None)+ return json_response({"Name": name})+++def _update_trigger(data):+ name = data.get("Name")+ if name not in _triggers:+ return error_response_json("EntityNotFoundException", f"Trigger {name} not found", 400)+ trigger_update = data.get("TriggerUpdate", {})+ updatable = {"Schedule", "Predicate", "Actions", "Description"}+ for k in updatable:+ if k in trigger_update:+ _triggers[name][k] = trigger_update[k]+ _triggers[name]["LastModifiedOn"] = time.time()+ return json_response({"Trigger": _triggers[name]})+++def _start_trigger(data):+ name = data.get("Name")+ if name not in _triggers:+ return error_response_json("EntityNotFoundException", f"Trigger {name} not found", 400)+ _triggers[name]["State"] = "ACTIVATED"+ _triggers[name]["LastModifiedOn"] = time.time()+ return json_response({"Name": name})+++def _stop_trigger(data):+ name = data.get("Name")+ if name not in _triggers:+ return error_response_json("EntityNotFoundException", f"Trigger {name} not found", 400)+ _triggers[name]["State"] = "DEACTIVATED"+ _triggers[name]["LastModifiedOn"] = time.time()+ return json_response({"Name": name})+++def _list_triggers(data):+ dependent_job = data.get("DependentJobName", "")+ names = []+ for name, trigger in _triggers.items():+ if dependent_job:+ actions = trigger.get("Actions", [])+ if not any(a.get("JobName") == dependent_job for a in actions):+ continue+ names.append(name)+ return json_response({"TriggerNames": sorted(names)})+++def _batch_get_triggers(data):+ requested = data.get("TriggerNames", [])+ found = [_triggers[n] for n in requested if n in _triggers]+ not_found = [n for n in requested if n not in _triggers]+ return json_response({"Triggers": found, "TriggersNotFound": not_found})+++def _get_triggers(data):+ dependent_job = data.get("DependentJobName", "")+ triggers = []+ for trigger in _triggers.values():+ if dependent_job:+ actions = trigger.get("Actions", [])+ if not any(a.get("JobName") == dependent_job for a in actions):+ continue+ triggers.append(trigger)+ return json_response({"Triggers": triggers})+++# ---- Workflows ----++def _create_workflow(data):+ name = data.get("Name")+ if not name:+ return error_response_json("InvalidInputException", "Name is required", 400)+ if name in _workflows:+ return error_response_json("AlreadyExistsException", f"Workflow {name} already exists", 400)+ _workflows[name] = {+ "Name": name,+ "Description": data.get("Description", ""),+ "DefaultRunProperties": data.get("DefaultRunProperties", {}),+ "CreatedOn": time.time(),+ "LastModifiedOn": time.time(),+ "MaxConcurrentRuns": data.get("MaxConcurrentRuns", 0),+ }+ if data.get("Tags"):+ _tags[_arn("workflow", name)] = dict(data["Tags"])+ _workflow_runs[name] = []+ return json_response({"Name": name})+++def _get_workflow(data):+ name = data.get("Name")+ wf = _workflows.get(name)+ if not wf:+ return error_response_json("EntityNotFoundException", f"Workflow {name} not found", 400)+ result = dict(wf)+ runs = _workflow_runs.get(name, [])+ if runs:+ result["LastRun"] = runs[-1]+ return json_response({"Workflow": result})+++def _delete_workflow(data):+ name = data.get("Name")+ if name not in _workflows:+ return error_response_json("EntityNotFoundException", f"Workflow {name} not found", 400)+ del _workflows[name]+ _workflow_runs.pop(name, None)+ _tags.pop(_arn("workflow", name), None)+ return json_response({"Name": name})+++def _update_workflow(data):+ name = data.get("Name")+ if name not in _workflows:+ return error_response_json("EntityNotFoundException", f"Workflow {name} not found", 400)+ for k in ("Description", "DefaultRunProperties", "MaxConcurrentRuns"):+ if k in data:+ _workflows[name][k] = data[k]+ _workflows[name]["LastModifiedOn"] = time.time()+ return json_response({"Name": name})+++def _start_workflow_run(data):+ name = data.get("Name")+ if name not in _workflows:+ return error_response_json("EntityNotFoundException", f"Workflow {name} not found", 400)+ run_id = new_uuid()+ run = {+ "WorkflowRunId": run_id,+ "Name": name,+ "Status": "RUNNING",+ "StartedOn": time.time(),+ "CompletedOn": None,+ "Statistics": {+ "TotalActions": 0, "RunningActions": 0, "StoppedActions": 0,+ "SucceededActions": 0, "FailedActions": 0, "TimeoutActions": 0,+ },+ "WorkflowRunProperties": dict(_workflows[name].get("DefaultRunProperties", {})),+ }+ _workflow_runs.setdefault(name, []).append(run)+ return json_response({"RunId": run_id})# ---- Tags -----_tags: dict = {}def _tag_resource(data):arn = data.get("ResourceArn", "")@@ -514,3 +1064,28 @@ def _untag_resource(data):def _get_tags(data):arn = data.get("ResourceArn", "")return json_response({"Tags": _tags.get(arn, {})})+++# ---- Helpers ----++def _simple_glob_match(pattern, name):+ """Very simple glob matching: * matches anything."""+ import fnmatch+ return fnmatch.fnmatch(name, pattern)+++def reset():+ _databases.clear()+ _tables.clear()+ _partitions.clear()+ _partition_indexes.clear()+ _connections.clear()+ _crawlers.clear()+ _jobs.clear()+ _job_runs.clear()+ _tags.clear()+ _security_configs.clear()+ _classifiers.clear()+ _triggers.clear()+ _workflows.clear()+ _workflow_runs.clear()diff --git a/services/iam_sts.py b/services/iam_sts.pyindex 5590cc39..91240a2d 100644--- a/services/iam_sts.py+++ b/services/iam_sts.py@@ -1,14 +1,37 @@"""-IAM & STS Service Emulators.-IAM: CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles,- DeleteRole, CreatePolicy, AttachRolePolicy, PutRolePolicy, CreateAccessKey.-STS: GetCallerIdentity, AssumeRole, GetSessionToken.+IAM & STS Service Emulators (AWS-compatible).++IAM actions:+ CreateUser, GetUser, ListUsers, DeleteUser,+ CreateRole, GetRole, ListRoles, DeleteRole,+ CreatePolicy, GetPolicy, GetPolicyVersion, ListPolicyVersions, ListPolicies, DeletePolicy,+ CreatePolicyVersion, DeletePolicyVersion,+ AttachRolePolicy, DetachRolePolicy, ListAttachedRolePolicies,+ PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies,+ AttachUserPolicy, DetachUserPolicy, ListAttachedUserPolicies,+ PutUserPolicy, GetUserPolicy, DeleteUserPolicy, ListUserPolicies,+ CreateAccessKey, ListAccessKeys, DeleteAccessKey,+ CreateInstanceProfile, DeleteInstanceProfile, GetInstanceProfile,+ AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile,+ ListInstanceProfiles, ListInstanceProfilesForRole,+ UpdateAssumeRolePolicy,+ CreateGroup, GetGroup, DeleteGroup, ListGroups,+ AddUserToGroup, RemoveUserFromGroup, ListGroupsForUser,+ CreateServiceLinkedRole,+ CreateOpenIDConnectProvider, GetOpenIDConnectProvider, DeleteOpenIDConnectProvider,+ TagRole, UntagRole, ListRoleTags,+ TagUser, UntagUser, ListUserTags,+ TagPolicy, UntagPolicy, ListPolicyTags,+ SimulatePrincipalPolicy, SimulateCustomPolicy.++STS actions:+ GetCallerIdentity, AssumeRole, GetSessionToken."""-import timeimport jsonimport logging-from urllib.parse import parse_qs+import time+from urllib.parse import parse_qs, quote as _url_quotefrom core.responses import new_uuid@@ -17,192 +40,1228 @@ logger = logging.getLogger("iam")ACCOUNT_ID = "000000000000"REGION = "us-east-1"+# ---------------------------------------------------------------------------+# Module-level state+# ---------------------------------------------------------------------------_users: dict = {}_roles: dict = {}_policies: dict = {}_access_keys: dict = {}+_instance_profiles: dict = {}+_groups: dict = {}+_user_inline_policies: dict = {}+_oidc_providers: dict = {}-# ========== IAM ==========+# ===================================================================== IAM+# =====================================================================async def handle_iam_request(method, path, headers, body, query_params):params = dict(query_params)if method == "POST" and body:- form_params = parse_qs(body.decode("utf-8", errors="replace"))- for k, v in form_params.items():+ for k, v in parse_qs(body.decode("utf-8", errors="replace")).items():params[k] = vaction = _p(params, "Action")-- handlers = {- "CreateUser": _create_user,- "GetUser": _get_user,- "ListUsers": _list_users,- "DeleteUser": _delete_user,- "CreateRole": _create_role,- "GetRole": _get_role,- "ListRoles": _list_roles,- "DeleteRole": _delete_role,- "CreatePolicy": _create_policy,- "AttachRolePolicy": _attach_role_policy,- "PutRolePolicy": _put_role_policy,- "CreateAccessKey": _create_access_key,- "ListAccessKeys": _list_access_keys,- }-- handler = handlers.get(action)+ handler = _IAM_HANDLERS.get(action)if not handler:- return _xml(200, "ErrorResponse", f"<Error><Code>InvalidAction</Code><Message>Unknown: {action}</Message></Error>", ns="iam")+ return _error(400, "InvalidAction", f"Unknown IAM action: {action}", ns="iam")return handler(params)+# -------------------- User management --------------------+def _create_user(p):name = _p(p, "UserName")- arn = f"arn:aws:iam::{ACCOUNT_ID}:user/{name}"- _users[name] = {"UserName": name, "Arn": arn, "UserId": new_uuid()[:20].upper(), "CreateDate": _now(), "Path": _p(p, "Path") or "/"}- return _xml(200, "CreateUserResponse", f"<CreateUserResult><User>{_user_xml(name)}</User></CreateUserResult>", ns="iam")+ if name in _users:+ return _error(409, "EntityAlreadyExists",+ f"User with name {name} already exists.", ns="iam")+ path = _p(p, "Path") or "/"+ _users[name] = {+ "UserName": name,+ "Arn": f"arn:aws:iam::{ACCOUNT_ID}:user{path}{name}" if path != "/" else f"arn:aws:iam::{ACCOUNT_ID}:user/{name}",+ "UserId": _gen_id("AIDA"),+ "CreateDate": _now(),+ "Path": path,+ "AttachedPolicies": [],+ "Tags": [],+ }+ return _xml(200, "CreateUserResponse",+ f"<CreateUserResult><User>{_user_xml(name)}</User></CreateUserResult>",+ ns="iam")def _get_user(p):- name = _p(p, "UserName") or "default"+ name = _p(p, "UserName")+ if not name:+ return _xml(200, "GetUserResponse",+ "<GetUserResult><User>"+ f"<UserName>root</UserName>"+ f"<UserId>{ACCOUNT_ID}</UserId>"+ f"<Arn>arn:aws:iam::{ACCOUNT_ID}:root</Arn>"+ "<Path>/</Path>"+ f"<CreateDate>{_now()}</CreateDate>"+ "</User></GetUserResult>",+ ns="iam")if name not in _users:- _users[name] = {"UserName": name, "Arn": f"arn:aws:iam::{ACCOUNT_ID}:user/{name}", "UserId": new_uuid()[:20].upper(), "CreateDate": _now(), "Path": "/"}- return _xml(200, "GetUserResponse", f"<GetUserResult><User>{_user_xml(name)}</User></GetUserResult>", ns="iam")+ return _error(404, "NoSuchEntity",+ f"The user with name {name} cannot be found.", ns="iam")+ return _xml(200, "GetUserResponse",+ f"<GetUserResult><User>{_user_xml(name)}</User></GetUserResult>",+ ns="iam")def _list_users(p):- members = "".join(f"<member>{_user_xml(n)}</member>" for n in _users)- return _xml(200, "ListUsersResponse", f"<ListUsersResult><Users>{members}</Users><IsTruncated>false</IsTruncated></ListUsersResult>", ns="iam")+ prefix = _p(p, "PathPrefix") or "/"+ members = "".join(+ f"<member>{_user_xml(n)}</member>"+ for n, u in _users.items()+ if u.get("Path", "/").startswith(prefix)+ )+ return _xml(200, "ListUsersResponse",+ f"<ListUsersResult><Users>{members}</Users>"+ "<IsTruncated>false</IsTruncated></ListUsersResult>",+ ns="iam")def _delete_user(p):- _users.pop(_p(p, "UserName"), None)+ name = _p(p, "UserName")+ user = _users.get(name)+ if not user:+ return _error(404, "NoSuchEntity",+ f"The user with name {name} cannot be found.", ns="iam")+ if user.get("AttachedPolicies"):+ return _error(409, "DeleteConflict",+ "Cannot delete entity, must detach all policies first.", ns="iam")+ user_keys = [k for k, v in _access_keys.items() if v["UserName"] == name]+ if user_keys:+ return _error(409, "DeleteConflict",+ "Cannot delete entity, must delete access keys first.", ns="iam")+ _users.pop(name, None)return _xml(200, "DeleteUserResponse", "", ns="iam")+# -------------------- Role management --------------------+def _create_role(p):name = _p(p, "RoleName")- arn = f"arn:aws:iam::{ACCOUNT_ID}:role/{name}"- _roles[name] = {"RoleName": name, "Arn": arn, "RoleId": new_uuid()[:20].upper(), "CreateDate": _now(), "Path": _p(p, "Path") or "/", "AssumeRolePolicyDocument": _p(p, "AssumeRolePolicyDocument"), "Policies": []}- return _xml(200, "CreateRoleResponse", f"<CreateRoleResult><Role>{_role_xml(name)}</Role></CreateRoleResult>", ns="iam")+ if name in _roles:+ return _error(409, "EntityAlreadyExists",+ f"Role with name {name} already exists.", ns="iam")+ path = _p(p, "Path") or "/"+ _roles[name] = {+ "RoleName": name,+ "Arn": f"arn:aws:iam::{ACCOUNT_ID}:role{path}{name}" if path != "/" else f"arn:aws:iam::{ACCOUNT_ID}:role/{name}",+ "RoleId": _gen_id("AROA"),+ "CreateDate": _now(),+ "Path": path,+ "AssumeRolePolicyDocument": _p(p, "AssumeRolePolicyDocument"),+ "Description": _p(p, "Description"),+ "MaxSessionDuration": int(_p(p, "MaxSessionDuration") or 3600),+ "AttachedPolicies": [],+ "InlinePolicies": {},+ "Tags": [],+ }+ return _xml(200, "CreateRoleResponse",+ f"<CreateRoleResult><Role>{_role_xml(name)}</Role></CreateRoleResult>",+ ns="iam")def _get_role(p):name = _p(p, "RoleName")if name not in _roles:- return _xml(404, "ErrorResponse", f"<Error><Code>NoSuchEntity</Code><Message>Role {name} not found</Message></Error>", ns="iam")- return _xml(200, "GetRoleResponse", f"<GetRoleResult><Role>{_role_xml(name)}</Role></GetRoleResult>", ns="iam")+ return _error(404, "NoSuchEntity",+ f"Role {name} not found.", ns="iam")+ return _xml(200, "GetRoleResponse",+ f"<GetRoleResult><Role>{_role_xml(name)}</Role></GetRoleResult>",+ ns="iam")def _list_roles(p):- members = "".join(f"<member>{_role_xml(n)}</member>" for n in _roles)- return _xml(200, "ListRolesResponse", f"<ListRolesResult><Roles>{members}</Roles><IsTruncated>false</IsTruncated></ListRolesResult>", ns="iam")+ prefix = _p(p, "PathPrefix") or "/"+ members = "".join(+ f"<member>{_role_xml(n)}</member>"+ for n, r in _roles.items()+ if r.get("Path", "/").startswith(prefix)+ )+ return _xml(200, "ListRolesResponse",+ f"<ListRolesResult><Roles>{members}</Roles>"+ "<IsTruncated>false</IsTruncated></ListRolesResult>",+ ns="iam")def _delete_role(p):- _roles.pop(_p(p, "RoleName"), None)+ name = _p(p, "RoleName")+ role = _roles.get(name)+ if not role:+ return _error(404, "NoSuchEntity",+ f"Role {name} not found.", ns="iam")+ if role.get("AttachedPolicies"):+ return _error(409, "DeleteConflict",+ "Cannot delete entity, must detach all policies first.", ns="iam")+ if role.get("InlinePolicies"):+ return _error(409, "DeleteConflict",+ "Cannot delete entity, must delete all inline policies first.", ns="iam")+ for ip in _instance_profiles.values():+ if name in ip.get("Roles", []):+ return _error(409, "DeleteConflict",+ "Cannot delete entity, must remove role from all instance profiles first.", ns="iam")+ _roles.pop(name, None)return _xml(200, "DeleteRoleResponse", "", ns="iam")+def _update_assume_role_policy(p):+ name = _p(p, "RoleName")+ if name not in _roles:+ return _error(404, "NoSuchEntity",+ f"Role {name} not found.", ns="iam")+ _roles[name]["AssumeRolePolicyDocument"] = _p(p, "PolicyDocument")+ return _xml(200, "UpdateAssumeRolePolicyResponse", "", ns="iam")+++# -------------------- Managed policy management --------------------+def _create_policy(p):name = _p(p, "PolicyName")- arn = f"arn:aws:iam::{ACCOUNT_ID}:policy/{name}"- _policies[arn] = {"PolicyName": name, "Arn": arn, "PolicyId": new_uuid()[:20].upper(), "CreateDate": _now()}- return _xml(200, "CreatePolicyResponse", f"""<CreatePolicyResult><Policy>- <PolicyName>{name}</PolicyName><Arn>{arn}</Arn>- </Policy></CreatePolicyResult>""", ns="iam")+ path = _p(p, "Path") or "/"+ arn = f"arn:aws:iam::{ACCOUNT_ID}:policy{path}{name}" if path != "/" else f"arn:aws:iam::{ACCOUNT_ID}:policy/{name}"+ if arn in _policies:+ return _error(409, "EntityAlreadyExists",+ f"A policy called {name} already exists.", ns="iam")+ doc = _p(p, "PolicyDocument")+ policy_id = _gen_id("ANPA")+ version_id = "v1"+ _policies[arn] = {+ "PolicyName": name,+ "Arn": arn,+ "PolicyId": policy_id,+ "CreateDate": _now(),+ "UpdateDate": _now(),+ "DefaultVersionId": version_id,+ "AttachmentCount": 0,+ "IsAttachable": True,+ "Path": path,+ "Tags": [],+ "Versions": {+ version_id: {+ "Document": doc,+ "VersionId": version_id,+ "IsDefaultVersion": True,+ "CreateDate": _now(),+ }+ },+ }+ return _xml(200, "CreatePolicyResponse",+ f"<CreatePolicyResult><Policy>{_managed_policy_xml(arn)}</Policy></CreatePolicyResult>",+ ns="iam")+++def _get_policy(p):+ arn = _p(p, "PolicyArn")+ if arn not in _policies:+ return _error(404, "NoSuchEntity",+ f"Policy {arn} not found.", ns="iam")+ return _xml(200, "GetPolicyResponse",+ f"<GetPolicyResult><Policy>{_managed_policy_xml(arn)}</Policy></GetPolicyResult>",+ ns="iam")+++def _get_policy_version(p):+ arn = _p(p, "PolicyArn")+ vid = _p(p, "VersionId")+ pol = _policies.get(arn)+ if not pol:+ return _error(404, "NoSuchEntity", "Policy not found.", ns="iam")+ ver = pol["Versions"].get(vid)+ if not ver:+ return _error(404, "NoSuchEntity",+ f"Policy version {vid} not found.", ns="iam")+ doc = _url_quote(ver.get("Document") or "{}", safe="")+ is_default = "true" if ver.get("IsDefaultVersion") else "false"+ return _xml(200, "GetPolicyVersionResponse",+ f"<GetPolicyVersionResult><PolicyVersion>"+ f"<Document>{doc}</Document>"+ f"<VersionId>{vid}</VersionId>"+ f"<IsDefaultVersion>{is_default}</IsDefaultVersion>"+ f"<CreateDate>{ver['CreateDate']}</CreateDate>"+ f"</PolicyVersion></GetPolicyVersionResult>",+ ns="iam")+++def _list_policy_versions(p):+ arn = _p(p, "PolicyArn")+ pol = _policies.get(arn)+ if not pol:+ return _error(404, "NoSuchEntity", "Policy not found.", ns="iam")+ members = ""+ for vid, ver in pol["Versions"].items():+ is_default = "true" if ver.get("IsDefaultVersion") else "false"+ members += (f"<member><VersionId>{vid}</VersionId>"+ f"<IsDefaultVersion>{is_default}</IsDefaultVersion>"+ f"<CreateDate>{ver['CreateDate']}</CreateDate></member>")+ return _xml(200, "ListPolicyVersionsResponse",+ f"<ListPolicyVersionsResult><Versions>{members}</Versions>"+ "<IsTruncated>false</IsTruncated></ListPolicyVersionsResult>",+ ns="iam")+def _create_policy_version(p):+ arn = _p(p, "PolicyArn")+ pol = _policies.get(arn)+ if not pol:+ return _error(404, "NoSuchEntity", "Policy not found.", ns="iam")+ if len(pol["Versions"]) >= 5:+ return _error(409, "LimitExceeded",+ "A managed policy can have at most 5 versions.", ns="iam")+ doc = _p(p, "PolicyDocument")+ set_default = _p(p, "SetAsDefault").lower() in ("true", "1") if _p(p, "SetAsDefault") else False+ next_v = max((int(v.lstrip("v")) for v in pol["Versions"]), default=0) + 1+ vid = f"v{next_v}"+ pol["Versions"][vid] = {+ "Document": doc,+ "VersionId": vid,+ "IsDefaultVersion": set_default,+ "CreateDate": _now(),+ }+ if set_default:+ for v in pol["Versions"].values():+ v["IsDefaultVersion"] = (v["VersionId"] == vid)+ pol["DefaultVersionId"] = vid+ pol["UpdateDate"] = _now()+ is_default = "true" if set_default else "false"+ return _xml(200, "CreatePolicyVersionResponse",+ f"<CreatePolicyVersionResult><PolicyVersion>"+ f"<VersionId>{vid}</VersionId>"+ f"<IsDefaultVersion>{is_default}</IsDefaultVersion>"+ f"<CreateDate>{pol['Versions'][vid]['CreateDate']}</CreateDate>"+ f"</PolicyVersion></CreatePolicyVersionResult>",+ ns="iam")+++def _delete_policy_version(p):+ arn = _p(p, "PolicyArn")+ vid = _p(p, "VersionId")+ pol = _policies.get(arn)+ if not pol:+ return _error(404, "NoSuchEntity", "Policy not found.", ns="iam")+ ver = pol["Versions"].get(vid)+ if not ver:+ return _error(404, "NoSuchEntity",+ f"Policy version {vid} not found.", ns="iam")+ if ver.get("IsDefaultVersion"):+ return _error(409, "DeleteConflict",+ "Cannot delete the default version of a policy.", ns="iam")+ del pol["Versions"][vid]+ return _xml(200, "DeletePolicyVersionResponse", "", ns="iam")+++def _list_policies(p):+ scope = _p(p, "Scope") or "All"+ prefix = _p(p, "PathPrefix") or "/"+ members = ""+ for arn, pol in _policies.items():+ if not pol.get("Path", "/").startswith(prefix):+ continue+ if scope == "Local" and arn.startswith("arn:aws:iam::aws:"):+ continue+ members += f"<member>{_managed_policy_xml(arn)}</member>"+ return _xml(200, "ListPoliciesResponse",+ f"<ListPoliciesResult><Policies>{members}</Policies>"+ "<IsTruncated>false</IsTruncated></ListPoliciesResult>",+ ns="iam")+++def _delete_policy(p):+ arn = _p(p, "PolicyArn")+ if arn not in _policies:+ return _error(404, "NoSuchEntity", f"Policy {arn} not found.", ns="iam")+ pol = _policies[arn]+ if pol.get("AttachmentCount", 0) > 0:+ return _error(409, "DeleteConflict",+ "Cannot delete a policy attached to entities.", ns="iam")+ del _policies[arn]+ return _xml(200, "DeletePolicyResponse", "", ns="iam")+++# -------------------- Attached role policies --------------------+def _attach_role_policy(p):role_name = _p(p, "RoleName")policy_arn = _p(p, "PolicyArn")- if role_name in _roles:- _roles[role_name]["Policies"].append(policy_arn)+ role = _roles.get(role_name)+ if not role:+ return _error(404, "NoSuchEntity",+ f"Role {role_name} not found.", ns="iam")+ if policy_arn not in role["AttachedPolicies"]:+ role["AttachedPolicies"].append(policy_arn)+ pol = _policies.get(policy_arn)+ if pol:+ pol["AttachmentCount"] = pol.get("AttachmentCount", 0) + 1return _xml(200, "AttachRolePolicyResponse", "", ns="iam")+def _detach_role_policy(p):+ role_name = _p(p, "RoleName")+ policy_arn = _p(p, "PolicyArn")+ role = _roles.get(role_name)+ if not role:+ return _error(404, "NoSuchEntity",+ f"Role {role_name} not found.", ns="iam")+ if policy_arn not in role["AttachedPolicies"]:+ return _error(404, "NoSuchEntity",+ f"Policy {policy_arn} is not attached to role {role_name}.", ns="iam")+ role["AttachedPolicies"].remove(policy_arn)+ pol = _policies.get(policy_arn)+ if pol:+ pol["AttachmentCount"] = max(pol.get("AttachmentCount", 1) - 1, 0)+ return _xml(200, "DetachRolePolicyResponse", "", ns="iam")+++def _list_attached_role_policies(p):+ role_name = _p(p, "RoleName")+ role = _roles.get(role_name)+ if not role:+ return _error(404, "NoSuchEntity",+ f"Role {role_name} not found.", ns="iam")+ members = ""+ for arn in role["AttachedPolicies"]:+ pol = _policies.get(arn)+ pname = pol["PolicyName"] if pol else arn.rsplit("/", 1)[-1]+ members += (f"<member><PolicyName>{pname}</PolicyName>"+ f"<PolicyArn>{arn}</PolicyArn></member>")+ return _xml(200, "ListAttachedRolePoliciesResponse",+ f"<ListAttachedRolePoliciesResult><AttachedPolicies>{members}</AttachedPolicies>"+ "<IsTruncated>false</IsTruncated></ListAttachedRolePoliciesResult>",+ ns="iam")+++# -------------------- Inline role policies --------------------+def _put_role_policy(p):+ role_name = _p(p, "RoleName")+ policy_name = _p(p, "PolicyName")+ policy_doc = _p(p, "PolicyDocument")+ role = _roles.get(role_name)+ if not role:+ return _error(404, "NoSuchEntity",+ f"Role {role_name} not found.", ns="iam")+ role["InlinePolicies"][policy_name] = policy_docreturn _xml(200, "PutRolePolicyResponse", "", ns="iam")+def _get_role_policy(p):+ role_name = _p(p, "RoleName")+ policy_name = _p(p, "PolicyName")+ role = _roles.get(role_name)+ if not role:+ return _error(404, "NoSuchEntity",+ f"Role {role_name} not found.", ns="iam")+ doc = role["InlinePolicies"].get(policy_name)+ if doc is None:+ return _error(404, "NoSuchEntity",+ f"The role policy with name {policy_name} cannot be found.", ns="iam")+ if isinstance(doc, (dict, list)):+ doc_str = json.dumps(doc)+ elif isinstance(doc, (bytes, bytearray)):+ doc_str = doc.decode("utf-8")+ else:+ doc_str = doc+ encoded_doc = _url_quote(doc_str, safe="")+ return _xml(200, "GetRolePolicyResponse",+ f"<GetRolePolicyResult>"+ f"<RoleName>{role_name}</RoleName>"+ f"<PolicyName>{policy_name}</PolicyName>"+ f"<PolicyDocument>{encoded_doc}</PolicyDocument>"+ f"</GetRolePolicyResult>",+ ns="iam")+++def _delete_role_policy(p):+ role_name = _p(p, "RoleName")+ policy_name = _p(p, "PolicyName")+ role = _roles.get(role_name)+ if not role:+ return _error(404, "NoSuchEntity",+ f"Role {role_name} not found.", ns="iam")+ if policy_name not in role["InlinePolicies"]:+ return _error(404, "NoSuchEntity",+ f"The role policy with name {policy_name} cannot be found.", ns="iam")+ del role["InlinePolicies"][policy_name]+ return _xml(200, "DeleteRolePolicyResponse", "", ns="iam")+++def _list_role_policies(p):+ role_name = _p(p, "RoleName")+ role = _roles.get(role_name)+ if not role:+ return _error(404, "NoSuchEntity",+ f"Role {role_name} not found.", ns="iam")+ members = "".join(+ f"<member>{name}</member>"+ for name in role["InlinePolicies"]+ )+ return _xml(200, "ListRolePoliciesResponse",+ f"<ListRolePoliciesResult><PolicyNames>{members}</PolicyNames>"+ "<IsTruncated>false</IsTruncated></ListRolePoliciesResult>",+ ns="iam")+++# -------------------- Attached user policies --------------------++def _attach_user_policy(p):+ user_name = _p(p, "UserName")+ policy_arn = _p(p, "PolicyArn")+ user = _users.get(user_name)+ if not user:+ return _error(404, "NoSuchEntity",+ f"The user with name {user_name} cannot be found.", ns="iam")+ if policy_arn not in user["AttachedPolicies"]:+ user["AttachedPolicies"].append(policy_arn)+ pol = _policies.get(policy_arn)+ if pol:+ pol["AttachmentCount"] = pol.get("AttachmentCount", 0) + 1+ return _xml(200, "AttachUserPolicyResponse", "", ns="iam")+++def _detach_user_policy(p):+ user_name = _p(p, "UserName")+ policy_arn = _p(p, "PolicyArn")+ user = _users.get(user_name)+ if not user:+ return _error(404, "NoSuchEntity",+ f"The user with name {user_name} cannot be found.", ns="iam")+ if policy_arn not in user["AttachedPolicies"]:+ return _error(404, "NoSuchEntity",+ f"Policy {policy_arn} is not attached to user {user_name}.", ns="iam")+ user["AttachedPolicies"].remove(policy_arn)+ pol = _policies.get(policy_arn)+ if pol:+ pol["AttachmentCount"] = max(pol.get("AttachmentCount", 1) - 1, 0)+ return _xml(200, "DetachUserPolicyResponse", "", ns="iam")+++def _list_attached_user_policies(p):+ user_name = _p(p, "UserName")+ user = _users.get(user_name)+ if not user:+ return _error(404, "NoSuchEntity",+ f"The user with name {user_name} cannot be found.", ns="iam")+ members = ""+ for arn in user["AttachedPolicies"]:+ pol = _policies.get(arn)+ pname = pol["PolicyName"] if pol else arn.rsplit("/", 1)[-1]+ members += (f"<member><PolicyName>{pname}</PolicyName>"+ f"<PolicyArn>{arn}</PolicyArn></member>")+ return _xml(200, "ListAttachedUserPoliciesResponse",+ f"<ListAttachedUserPoliciesResult><AttachedPolicies>{members}</AttachedPolicies>"+ "<IsTruncated>false</IsTruncated></ListAttachedUserPoliciesResult>",+ ns="iam")+++# -------------------- Access keys --------------------+def _create_access_key(p):- user = _p(p, "UserName") or "default"- key_id = f"AKIA{''.join(new_uuid().replace('-','')[:16].upper())}"+ user_name = _p(p, "UserName")+ if not user_name:+ user_name = "default"+ if user_name != "default" and user_name not in _users:+ return _error(404, "NoSuchEntity",+ f"The user with name {user_name} cannot be found.", ns="iam")+ key_id = _gen_access_key_id()secret = new_uuid().replace("-", "") + new_uuid().replace("-", "")[:8]- _access_keys[key_id] = {"UserName": user, "AccessKeyId": key_id, "SecretAccessKey": secret, "Status": "Active", "CreateDate": _now()}- return _xml(200, "CreateAccessKeyResponse", f"""<CreateAccessKeyResult><AccessKey>- <UserName>{user}</UserName><AccessKeyId>{key_id}</AccessKeyId>- <SecretAccessKey>{secret}</SecretAccessKey><Status>Active</Status>- </AccessKey></CreateAccessKeyResult>""", ns="iam")+ _access_keys[key_id] = {+ "UserName": user_name,+ "AccessKeyId": key_id,+ "SecretAccessKey": secret,+ "Status": "Active",+ "CreateDate": _now(),+ }+ return _xml(200, "CreateAccessKeyResponse",+ f"<CreateAccessKeyResult><AccessKey>"+ f"<UserName>{user_name}</UserName>"+ f"<AccessKeyId>{key_id}</AccessKeyId>"+ f"<SecretAccessKey>{secret}</SecretAccessKey>"+ f"<Status>Active</Status>"+ f"<CreateDate>{_access_keys[key_id]['CreateDate']}</CreateDate>"+ f"</AccessKey></CreateAccessKeyResult>",+ ns="iam")def _list_access_keys(p):- user = _p(p, "UserName") or "default"+ user_name = _p(p, "UserName") or "default"members = ""- for k, v in _access_keys.items():- if v["UserName"] == user:- members += f"<member><AccessKeyId>{k}</AccessKeyId><Status>{v['Status']}</Status><UserName>{user}</UserName></member>"- return _xml(200, "ListAccessKeysResponse", f"<ListAccessKeysResult><AccessKeyMetadata>{members}</AccessKeyMetadata></ListAccessKeysResult>", ns="iam")+ for kid, v in _access_keys.items():+ if v["UserName"] == user_name:+ members += (f"<member><AccessKeyId>{kid}</AccessKeyId>"+ f"<Status>{v['Status']}</Status>"+ f"<UserName>{user_name}</UserName>"+ f"<CreateDate>{v['CreateDate']}</CreateDate>"+ f"</member>")+ return _xml(200, "ListAccessKeysResponse",+ f"<ListAccessKeysResult><AccessKeyMetadata>{members}</AccessKeyMetadata>"+ "<IsTruncated>false</IsTruncated></ListAccessKeysResult>",+ ns="iam")-def _user_xml(name):- u = _users[name]- return f"<UserName>{u['UserName']}</UserName><UserId>{u['UserId']}</UserId><Arn>{u['Arn']}</Arn><Path>{u['Path']}</Path><CreateDate>{u['CreateDate']}</CreateDate>"+def _delete_access_key(p):+ key_id = _p(p, "AccessKeyId")+ if key_id not in _access_keys:+ return _error(404, "NoSuchEntity",+ f"The Access Key with id {key_id} cannot be found.", ns="iam")+ del _access_keys[key_id]+ return _xml(200, "DeleteAccessKeyResponse", "", ns="iam")-def _role_xml(name):- r = _roles[name]- return f"<RoleName>{r['RoleName']}</RoleName><RoleId>{r['RoleId']}</RoleId><Arn>{r['Arn']}</Arn><Path>{r['Path']}</Path><CreateDate>{r['CreateDate']}</CreateDate>"+# -------------------- Instance profiles --------------------++def _create_instance_profile(p):+ name = _p(p, "InstanceProfileName")+ if name in _instance_profiles:+ return _error(409, "EntityAlreadyExists",+ f"Instance profile {name} already exists.", ns="iam")+ path = _p(p, "Path") or "/"+ ip_id = _gen_id("AIPA")+ arn = (f"arn:aws:iam::{ACCOUNT_ID}:instance-profile{path}{name}"+ if path != "/" else+ f"arn:aws:iam::{ACCOUNT_ID}:instance-profile/{name}")+ _instance_profiles[name] = {+ "InstanceProfileName": name,+ "InstanceProfileId": ip_id,+ "Arn": arn,+ "Path": path,+ "CreateDate": _now(),+ "Roles": [],+ }+ return _xml(200, "CreateInstanceProfileResponse",+ f"<CreateInstanceProfileResult>"+ f"<InstanceProfile>{_instance_profile_xml(name)}</InstanceProfile>"+ f"</CreateInstanceProfileResult>",+ ns="iam")+++def _delete_instance_profile(p):+ name = _p(p, "InstanceProfileName")+ if name not in _instance_profiles:+ return _error(404, "NoSuchEntity",+ f"Instance profile {name} not found.", ns="iam")+ ip = _instance_profiles[name]+ if ip["Roles"]:+ return _error(409, "DeleteConflict",+ "Cannot delete entity, must remove all roles first.", ns="iam")+ del _instance_profiles[name]+ return _xml(200, "DeleteInstanceProfileResponse", "", ns="iam")+++def _get_instance_profile(p):+ name = _p(p, "InstanceProfileName")+ if name not in _instance_profiles:+ return _error(404, "NoSuchEntity",+ f"Instance profile {name} not found.", ns="iam")+ return _xml(200, "GetInstanceProfileResponse",+ f"<GetInstanceProfileResult>"+ f"<InstanceProfile>{_instance_profile_xml(name)}</InstanceProfile>"+ f"</GetInstanceProfileResult>",+ ns="iam")+++def _add_role_to_instance_profile(p):+ ip_name = _p(p, "InstanceProfileName")+ role_name = _p(p, "RoleName")+ ip = _instance_profiles.get(ip_name)+ if not ip:+ return _error(404, "NoSuchEntity",+ f"Instance profile {ip_name} not found.", ns="iam")+ if role_name not in _roles:+ return _error(404, "NoSuchEntity",+ f"Role {role_name} not found.", ns="iam")+ if role_name in ip["Roles"]:+ return _error(409, "LimitExceeded",+ f"Role {role_name} is already associated with instance profile {ip_name}.", ns="iam")+ if len(ip["Roles"]) >= 1:+ return _error(409, "LimitExceeded",+ "An instance profile can have only one role.", ns="iam")+ ip["Roles"].append(role_name)+ return _xml(200, "AddRoleToInstanceProfileResponse", "", ns="iam")+++def _remove_role_from_instance_profile(p):+ ip_name = _p(p, "InstanceProfileName")+ role_name = _p(p, "RoleName")+ ip = _instance_profiles.get(ip_name)+ if not ip:+ return _error(404, "NoSuchEntity",+ f"Instance profile {ip_name} not found.", ns="iam")+ if role_name not in ip["Roles"]:+ return _error(404, "NoSuchEntity",+ f"Role {role_name} is not associated with instance profile {ip_name}.", ns="iam")+ ip["Roles"].remove(role_name)+ return _xml(200, "RemoveRoleFromInstanceProfileResponse", "", ns="iam")+++def _list_instance_profiles(p):+ prefix = _p(p, "PathPrefix") or "/"+ members = "".join(+ f"<member>{_instance_profile_xml(name)}</member>"+ for name, ip in _instance_profiles.items()+ if ip["Path"].startswith(prefix)+ )+ return _xml(200, "ListInstanceProfilesResponse",+ f"<ListInstanceProfilesResult><InstanceProfiles>{members}</InstanceProfiles>"+ "<IsTruncated>false</IsTruncated></ListInstanceProfilesResult>",+ ns="iam")+++def _list_instance_profiles_for_role(p):+ role_name = _p(p, "RoleName")+ if role_name not in _roles:+ return _error(404, "NoSuchEntity",+ f"Role {role_name} not found.", ns="iam")+ members = "".join(+ f"<member>{_instance_profile_xml(name)}</member>"+ for name, ip in _instance_profiles.items()+ if role_name in ip["Roles"]+ )+ return _xml(200, "ListInstanceProfilesForRoleResponse",+ f"<ListInstanceProfilesForRoleResult><InstanceProfiles>{members}</InstanceProfiles>"+ "<IsTruncated>false</IsTruncated></ListInstanceProfilesForRoleResult>",+ ns="iam")+++# -------------------- Tags: roles --------------------++def _tag_role(p):+ role_name = _p(p, "RoleName")+ role = _roles.get(role_name)+ if not role:+ return _error(404, "NoSuchEntity",+ f"Role {role_name} not found.", ns="iam")+ new_tags = _extract_tags(p)+ existing = {t["Key"]: t for t in role["Tags"]}+ for t in new_tags:+ existing[t["Key"]] = t+ role["Tags"] = list(existing.values())+ return _xml(200, "TagRoleResponse", "", ns="iam")+++def _untag_role(p):+ role_name = _p(p, "RoleName")+ role = _roles.get(role_name)+ if not role:+ return _error(404, "NoSuchEntity",+ f"Role {role_name} not found.", ns="iam")+ keys_to_remove = _extract_tag_keys(p)+ role["Tags"] = [t for t in role["Tags"] if t["Key"] not in keys_to_remove]+ return _xml(200, "UntagRoleResponse", "", ns="iam")+++def _list_role_tags(p):+ role_name = _p(p, "RoleName")+ role = _roles.get(role_name)+ if not role:+ return _error(404, "NoSuchEntity",+ f"Role {role_name} not found.", ns="iam")+ members = "".join(+ f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>"+ for t in role["Tags"]+ )+ return _xml(200, "ListRoleTagsResponse",+ f"<ListRoleTagsResult><Tags>{members}</Tags>"+ "<IsTruncated>false</IsTruncated></ListRoleTagsResult>",+ ns="iam")+++# -------------------- Tags: users --------------------++def _tag_user(p):+ user_name = _p(p, "UserName")+ user = _users.get(user_name)+ if not user:+ return _error(404, "NoSuchEntity",+ f"The user with name {user_name} cannot be found.", ns="iam")+ new_tags = _extract_tags(p)+ existing = {t["Key"]: t for t in user["Tags"]}+ for t in new_tags:+ existing[t["Key"]] = t+ user["Tags"] = list(existing.values())+ return _xml(200, "TagUserResponse", "", ns="iam")++def _untag_user(p):+ user_name = _p(p, "UserName")+ user = _users.get(user_name)+ if not user:+ return _error(404, "NoSuchEntity",+ f"The user with name {user_name} cannot be found.", ns="iam")+ keys_to_remove = _extract_tag_keys(p)+ user["Tags"] = [t for t in user["Tags"] if t["Key"] not in keys_to_remove]+ return _xml(200, "UntagUserResponse", "", ns="iam")-# ========== STS ==========++def _list_user_tags(p):+ user_name = _p(p, "UserName")+ user = _users.get(user_name)+ if not user:+ return _error(404, "NoSuchEntity",+ f"The user with name {user_name} cannot be found.", ns="iam")+ members = "".join(+ f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>"+ for t in user["Tags"]+ )+ return _xml(200, "ListUserTagsResponse",+ f"<ListUserTagsResult><Tags>{members}</Tags>"+ "<IsTruncated>false</IsTruncated></ListUserTagsResult>",+ ns="iam")+++# -------------------- Simulate (stubs) --------------------++def _simulate_principal_policy(p):+ results = _build_simulate_results(p)+ return _xml(200, "SimulatePrincipalPolicyResponse",+ f"<SimulatePrincipalPolicyResult>"+ f"<EvaluationResults>{results}</EvaluationResults>"+ "<IsTruncated>false</IsTruncated>"+ f"</SimulatePrincipalPolicyResult>",+ ns="iam")+++def _simulate_custom_policy(p):+ results = _build_simulate_results(p)+ return _xml(200, "SimulateCustomPolicyResponse",+ f"<SimulateCustomPolicyResult>"+ f"<EvaluationResults>{results}</EvaluationResults>"+ "<IsTruncated>false</IsTruncated>"+ f"</SimulateCustomPolicyResult>",+ ns="iam")+++def _build_simulate_results(p):+ actions = []+ idx = 1+ while True:+ a = _p(p, f"ActionNames.member.{idx}")+ if not a:+ break+ actions.append(a)+ idx += 1+ if not actions:+ actions = ["sts:AssumeRole"]+ resource_arn = _p(p, "ResourceArns.member.1") or "*"+ members = ""+ for action in actions:+ members += (f"<member>"+ f"<EvalActionName>{action}</EvalActionName>"+ f"<EvalResourceName>{resource_arn}</EvalResourceName>"+ f"<EvalDecision>allowed</EvalDecision>"+ f"<MatchedStatements></MatchedStatements>"+ f"<MissingContextValues></MissingContextValues>"+ f"</member>")+ return members+++# -------------------- Group management --------------------++def _create_group(p):+ name = _p(p, "GroupName")+ if name in _groups:+ return _error(409, "EntityAlreadyExists",+ f"Group with name {name} already exists.", ns="iam")+ path = _p(p, "Path") or "/"+ _groups[name] = {+ "GroupName": name,+ "GroupId": _gen_id("AGPA"),+ "Arn": f"arn:aws:iam::{ACCOUNT_ID}:group{path}{name}" if path != "/" else f"arn:aws:iam::{ACCOUNT_ID}:group/{name}",+ "Path": path,+ "CreateDate": _now(),+ "Users": [],+ }+ return _xml(200, "CreateGroupResponse",+ f"<CreateGroupResult><Group>{_group_xml(name)}</Group></CreateGroupResult>",+ ns="iam")+++def _get_group(p):+ name = _p(p, "GroupName")+ if name not in _groups:+ return _error(404, "NoSuchEntity",+ f"The group with name {name} cannot be found.", ns="iam")+ g = _groups[name]+ user_members = ""+ for uname in g["Users"]:+ if uname in _users:+ user_members += f"<member>{_user_xml(uname)}</member>"+ return _xml(200, "GetGroupResponse",+ f"<GetGroupResult>"+ f"<Group>{_group_xml(name)}</Group>"+ f"<Users>{user_members}</Users>"+ f"<IsTruncated>false</IsTruncated>"+ f"</GetGroupResult>",+ ns="iam")+++def _delete_group(p):+ name = _p(p, "GroupName")+ if name not in _groups:+ return _error(404, "NoSuchEntity",+ f"The group with name {name} cannot be found.", ns="iam")+ _groups.pop(name, None)+ return _xml(200, "DeleteGroupResponse", "", ns="iam")+++def _list_groups(p):+ prefix = _p(p, "PathPrefix") or "/"+ members = "".join(+ f"<member>{_group_xml(n)}</member>"+ for n, g in _groups.items()+ if g.get("Path", "/").startswith(prefix)+ )+ return _xml(200, "ListGroupsResponse",+ f"<ListGroupsResult><Groups>{members}</Groups>"+ "<IsTruncated>false</IsTruncated></ListGroupsResult>",+ ns="iam")+++def _add_user_to_group(p):+ group_name = _p(p, "GroupName")+ user_name = _p(p, "UserName")+ g = _groups.get(group_name)+ if not g:+ return _error(404, "NoSuchEntity",+ f"The group with name {group_name} cannot be found.", ns="iam")+ if user_name not in _users:+ return _error(404, "NoSuchEntity",+ f"The user with name {user_name} cannot be found.", ns="iam")+ if user_name not in g["Users"]:+ g["Users"].append(user_name)+ return _xml(200, "AddUserToGroupResponse", "", ns="iam")+++def _remove_user_from_group(p):+ group_name = _p(p, "GroupName")+ user_name = _p(p, "UserName")+ g = _groups.get(group_name)+ if not g:+ return _error(404, "NoSuchEntity",+ f"The group with name {group_name} cannot be found.", ns="iam")+ if user_name not in g["Users"]:+ return _error(404, "NoSuchEntity",+ f"The user with name {user_name} is not in group {group_name}.", ns="iam")+ g["Users"].remove(user_name)+ return _xml(200, "RemoveUserFromGroupResponse", "", ns="iam")+++def _list_groups_for_user(p):+ user_name = _p(p, "UserName")+ if user_name not in _users:+ return _error(404, "NoSuchEntity",+ f"The user with name {user_name} cannot be found.", ns="iam")+ members = "".join(+ f"<member>{_group_xml(n)}</member>"+ for n, g in _groups.items()+ if user_name in g["Users"]+ )+ return _xml(200, "ListGroupsForUserResponse",+ f"<ListGroupsForUserResult><Groups>{members}</Groups>"+ "<IsTruncated>false</IsTruncated></ListGroupsForUserResult>",+ ns="iam")+++# -------------------- Inline user policies --------------------++def _put_user_policy(p):+ user_name = _p(p, "UserName")+ policy_name = _p(p, "PolicyName")+ policy_doc = _p(p, "PolicyDocument")+ if user_name not in _users:+ return _error(404, "NoSuchEntity",+ f"The user with name {user_name} cannot be found.", ns="iam")+ _user_inline_policies[(user_name, policy_name)] = policy_doc+ return _xml(200, "PutUserPolicyResponse", "", ns="iam")+++def _get_user_policy(p):+ user_name = _p(p, "UserName")+ policy_name = _p(p, "PolicyName")+ if user_name not in _users:+ return _error(404, "NoSuchEntity",+ f"The user with name {user_name} cannot be found.", ns="iam")+ doc = _user_inline_policies.get((user_name, policy_name))+ if doc is None:+ return _error(404, "NoSuchEntity",+ f"The user policy with name {policy_name} cannot be found.", ns="iam")+ if isinstance(doc, (dict, list)):+ doc_str = json.dumps(doc)+ elif isinstance(doc, (bytes, bytearray)):+ doc_str = doc.decode("utf-8")+ else:+ doc_str = doc+ encoded_doc = _url_quote(doc_str, safe="")+ return _xml(200, "GetUserPolicyResponse",+ f"<GetUserPolicyResult>"+ f"<UserName>{user_name}</UserName>"+ f"<PolicyName>{policy_name}</PolicyName>"+ f"<PolicyDocument>{encoded_doc}</PolicyDocument>"+ f"</GetUserPolicyResult>",+ ns="iam")+++def _delete_user_policy(p):+ user_name = _p(p, "UserName")+ policy_name = _p(p, "PolicyName")+ if user_name not in _users:+ return _error(404, "NoSuchEntity",+ f"The user with name {user_name} cannot be found.", ns="iam")+ if (user_name, policy_name) not in _user_inline_policies:+ return _error(404, "NoSuchEntity",+ f"The user policy with name {policy_name} cannot be found.", ns="iam")+ del _user_inline_policies[(user_name, policy_name)]+ return _xml(200, "DeleteUserPolicyResponse", "", ns="iam")+++def _list_user_policies(p):+ user_name = _p(p, "UserName")+ if user_name not in _users:+ return _error(404, "NoSuchEntity",+ f"The user with name {user_name} cannot be found.", ns="iam")+ members = "".join(+ f"<member>{pname}</member>"+ for (uname, pname) in _user_inline_policies+ if uname == user_name+ )+ return _xml(200, "ListUserPoliciesResponse",+ f"<ListUserPoliciesResult><PolicyNames>{members}</PolicyNames>"+ "<IsTruncated>false</IsTruncated></ListUserPoliciesResult>",+ ns="iam")+++# -------------------- Service-linked roles --------------------++def _create_service_linked_role(p):+ service_name = _p(p, "AWSServiceName")+ suffix = service_name.split(".")[0] if "." in service_name else service_name+ role_name = f"AWSServiceRoleFor{suffix.capitalize()}"+ path = f"/aws-service-role/{service_name}/"++ if role_name in _roles:+ return _error(409, "EntityAlreadyExists",+ f"Role with name {role_name} already exists.", ns="iam")++ trust_policy = json.dumps({+ "Version": "2012-10-17",+ "Statement": [{+ "Effect": "Allow",+ "Principal": {"Service": service_name},+ "Action": "sts:AssumeRole"+ }]+ })++ _roles[role_name] = {+ "RoleName": role_name,+ "Arn": f"arn:aws:iam::{ACCOUNT_ID}:role{path}{role_name}",+ "RoleId": _gen_id("AROA"),+ "CreateDate": _now(),+ "Path": path,+ "AssumeRolePolicyDocument": trust_policy,+ "Description": f"Service-linked role for {service_name}",+ "MaxSessionDuration": 3600,+ "AttachedPolicies": [],+ "InlinePolicies": {},+ "Tags": [],+ }+ return _xml(200, "CreateServiceLinkedRoleResponse",+ f"<CreateServiceLinkedRoleResult><Role>{_role_xml(role_name)}</Role></CreateServiceLinkedRoleResult>",+ ns="iam")+++# -------------------- OIDC providers --------------------++def _create_oidc_provider(p):+ url = _p(p, "Url")+ client_ids = []+ idx = 1+ while True:+ cid = _p(p, f"ClientIDList.member.{idx}")+ if not cid:+ break+ client_ids.append(cid)+ idx += 1+ thumbprints = []+ idx = 1+ while True:+ tp = _p(p, f"ThumbprintList.member.{idx}")+ if not tp:+ break+ thumbprints.append(tp)+ idx += 1++ host = url.replace("https://", "").replace("http://", "").rstrip("/")+ arn = f"arn:aws:iam::{ACCOUNT_ID}:oidc-provider/{host}"++ if arn in _oidc_providers:+ return _error(409, "EntityAlreadyExists",+ f"OIDC provider with url {url} already exists.", ns="iam")++ tags = _extract_tags(p)+ _oidc_providers[arn] = {+ "Url": url,+ "ClientIDList": client_ids,+ "ThumbprintList": thumbprints,+ "Arn": arn,+ "CreateDate": _now(),+ "Tags": tags,+ }+ return _xml(200, "CreateOpenIDConnectProviderResponse",+ f"<CreateOpenIDConnectProviderResult>"+ f"<OpenIDConnectProviderArn>{arn}</OpenIDConnectProviderArn>"+ f"</CreateOpenIDConnectProviderResult>",+ ns="iam")+++def _get_oidc_provider(p):+ arn = _p(p, "OpenIDConnectProviderArn")+ prov = _oidc_providers.get(arn)+ if not prov:+ return _error(404, "NoSuchEntity",+ f"OIDC provider {arn} not found.", ns="iam")+ client_members = "".join(f"<member>{c}</member>" for c in prov["ClientIDList"])+ thumb_members = "".join(f"<member>{t}</member>" for t in prov["ThumbprintList"])+ tag_members = "".join(+ f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>"+ for t in prov.get("Tags", [])+ )+ return _xml(200, "GetOpenIDConnectProviderResponse",+ f"<GetOpenIDConnectProviderResult>"+ f"<Url>{prov['Url']}</Url>"+ f"<ClientIDList>{client_members}</ClientIDList>"+ f"<ThumbprintList>{thumb_members}</ThumbprintList>"+ f"<CreateDate>{prov['CreateDate']}</CreateDate>"+ f"<Tags>{tag_members}</Tags>"+ f"</GetOpenIDConnectProviderResult>",+ ns="iam")+++def _delete_oidc_provider(p):+ arn = _p(p, "OpenIDConnectProviderArn")+ if arn not in _oidc_providers:+ return _error(404, "NoSuchEntity",+ f"OIDC provider {arn} not found.", ns="iam")+ del _oidc_providers[arn]+ return _xml(200, "DeleteOpenIDConnectProviderResponse", "", ns="iam")+++# -------------------- Tags: policies --------------------++def _tag_policy(p):+ arn = _p(p, "PolicyArn")+ pol = _policies.get(arn)+ if not pol:+ return _error(404, "NoSuchEntity",+ f"Policy {arn} not found.", ns="iam")+ new_tags = _extract_tags(p)+ existing = {t["Key"]: t for t in pol.get("Tags", [])}+ for t in new_tags:+ existing[t["Key"]] = t+ pol["Tags"] = list(existing.values())+ return _xml(200, "TagPolicyResponse", "", ns="iam")+++def _untag_policy(p):+ arn = _p(p, "PolicyArn")+ pol = _policies.get(arn)+ if not pol:+ return _error(404, "NoSuchEntity",+ f"Policy {arn} not found.", ns="iam")+ keys_to_remove = _extract_tag_keys(p)+ pol["Tags"] = [t for t in pol.get("Tags", []) if t["Key"] not in keys_to_remove]+ return _xml(200, "UntagPolicyResponse", "", ns="iam")+++def _list_policy_tags(p):+ arn = _p(p, "PolicyArn")+ pol = _policies.get(arn)+ if not pol:+ return _error(404, "NoSuchEntity",+ f"Policy {arn} not found.", ns="iam")+ members = "".join(+ f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>"+ for t in pol.get("Tags", [])+ )+ return _xml(200, "ListPolicyTagsResponse",+ f"<ListPolicyTagsResult><Tags>{members}</Tags>"+ "<IsTruncated>false</IsTruncated></ListPolicyTagsResult>",+ ns="iam")+++# ===================================================================== STS+# =====================================================================async def handle_sts_request(method, path, headers, body, query_params):params = dict(query_params)if method == "POST" and body:- form_params = parse_qs(body.decode("utf-8", errors="replace"))- for k, v in form_params.items():+ for k, v in parse_qs(body.decode("utf-8", errors="replace")).items():params[k] = vaction = _p(params, "Action")if action == "GetCallerIdentity":- return _xml(200, "GetCallerIdentityResponse", f"""<GetCallerIdentityResult>- <Arn>arn:aws:iam::{ACCOUNT_ID}:root</Arn>- <UserId>{ACCOUNT_ID}</UserId>- <Account>{ACCOUNT_ID}</Account>- </GetCallerIdentityResult>""", ns="sts")+ return _xml(200, "GetCallerIdentityResponse",+ f"<GetCallerIdentityResult>"+ f"<Arn>arn:aws:iam::{ACCOUNT_ID}:root</Arn>"+ f"<UserId>{ACCOUNT_ID}</UserId>"+ f"<Account>{ACCOUNT_ID}</Account>"+ f"</GetCallerIdentityResult>",+ ns="sts")if action == "AssumeRole":role_arn = _p(params, "RoleArn")- session = _p(params, "RoleSessionName")- return _xml(200, "AssumeRoleResponse", f"""<AssumeRoleResult>- <Credentials>- <AccessKeyId>ASIAEXAMPLE</AccessKeyId>- <SecretAccessKey>secretkey</SecretAccessKey>- <SessionToken>sessiontoken{new_uuid()}</SessionToken>- <Expiration>{_now()}</Expiration>- </Credentials>- <AssumedRoleUser>- <AssumedRoleId>AROA:{session}</AssumedRoleId>- <Arn>{role_arn}</Arn>- </AssumedRoleUser>- </AssumeRoleResult>""", ns="sts")+ session_name = _p(params, "RoleSessionName")+ duration = int(_p(params, "DurationSeconds") or 3600)+ expiration = _future(duration)+ access_key = _gen_session_access_key()+ secret_key = _gen_secret()+ session_token = _gen_session_token()+ role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()+ assumed_arn = role_arn.replace(":role/", ":assumed-role/", 1)+ if not assumed_arn.endswith(f"/{session_name}"):+ assumed_arn = f"{assumed_arn}/{session_name}"+ return _xml(200, "AssumeRoleResponse",+ f"<AssumeRoleResult>"+ f"<Credentials>"+ f"<AccessKeyId>{access_key}</AccessKeyId>"+ f"<SecretAccessKey>{secret_key}</SecretAccessKey>"+ f"<SessionToken>{session_token}</SessionToken>"+ f"<Expiration>{expiration}</Expiration>"+ f"</Credentials>"+ f"<AssumedRoleUser>"+ f"<AssumedRoleId>{role_id}:{session_name}</AssumedRoleId>"+ f"<Arn>{assumed_arn}</Arn>"+ f"</AssumedRoleUser>"+ f"<PackedPolicySize>0</PackedPolicySize>"+ f"</AssumeRoleResult>",+ ns="sts")if action == "GetSessionToken":- return _xml(200, "GetSessionTokenResponse", f"""<GetSessionTokenResult>- <Credentials>- <AccessKeyId>ASIAEXAMPLE</AccessKeyId>- <SecretAccessKey>secretkey</SecretAccessKey>- <SessionToken>sessiontoken{new_uuid()}</SessionToken>- <Expiration>{_now()}</Expiration>- </Credentials>- </GetSessionTokenResult>""", ns="sts")+ duration = int(_p(params, "DurationSeconds") or 43200)+ expiration = _future(duration)+ access_key = _gen_session_access_key()+ secret_key = _gen_secret()+ session_token = _gen_session_token()+ return _xml(200, "GetSessionTokenResponse",+ f"<GetSessionTokenResult>"+ f"<Credentials>"+ f"<AccessKeyId>{access_key}</AccessKeyId>"+ f"<SecretAccessKey>{secret_key}</SecretAccessKey>"+ f"<SessionToken>{session_token}</SessionToken>"+ f"<Expiration>{expiration}</Expiration>"+ f"</Credentials>"+ f"</GetSessionTokenResult>",+ ns="sts")- return _xml(400, "ErrorResponse", f"<Error><Code>InvalidAction</Code><Message>Unknown: {action}</Message></Error>", ns="sts")+ return _error(400, "InvalidAction", f"Unknown STS action: {action}", ns="sts")-# ========== Shared helpers ==========+# ===================================================================== Shared helpers+# =====================================================================def _p(params, key, default=""):val = params.get(key, [default])@@ -213,14 +1272,228 @@ def _now():return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())+def _future(seconds):+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + seconds))+++def _gen_id(prefix="AIDA"):+ return prefix + new_uuid().replace("-", "")[:17].upper()+++def _gen_access_key_id():+ return "AKIA" + new_uuid().replace("-", "")[:16].upper()+++def _gen_session_access_key():+ return "ASIA" + new_uuid().replace("-", "")[:16].upper()+++def _gen_secret():+ raw = new_uuid().replace("-", "") + new_uuid().replace("-", "")+ return raw[:40]+++def _gen_session_token():+ parts = [new_uuid().replace("-", "") for _ in range(4)]+ return "FwoGZX" + "".join(parts)+++def _extract_tags(p):+ tags = []+ idx = 1+ while True:+ key = _p(p, f"Tags.member.{idx}.Key")+ if not key:+ break+ value = _p(p, f"Tags.member.{idx}.Value")+ tags.append({"Key": key, "Value": value})+ idx += 1+ return tags+++def _extract_tag_keys(p):+ keys = set()+ idx = 1+ while True:+ key = _p(p, f"TagKeys.member.{idx}")+ if not key:+ break+ keys.add(key)+ idx += 1+ return keys+++# -------------------- XML builders --------------------++def _user_xml(name):+ u = _users[name]+ return (f"<UserName>{u['UserName']}</UserName>"+ f"<UserId>{u['UserId']}</UserId>"+ f"<Arn>{u['Arn']}</Arn>"+ f"<Path>{u['Path']}</Path>"+ f"<CreateDate>{u['CreateDate']}</CreateDate>")+++def _role_xml(name):+ r = _roles[name]+ assume_doc = _url_quote(r.get("AssumeRolePolicyDocument") or "{}", safe="")+ desc = r.get("Description") or ""+ max_dur = r.get("MaxSessionDuration", 3600)+ tags_xml = ""+ if r.get("Tags"):+ tag_members = "".join(+ f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>"+ for t in r["Tags"]+ )+ tags_xml = f"<Tags>{tag_members}</Tags>"+ return (f"<RoleName>{r['RoleName']}</RoleName>"+ f"<RoleId>{r['RoleId']}</RoleId>"+ f"<Arn>{r['Arn']}</Arn>"+ f"<Path>{r['Path']}</Path>"+ f"<CreateDate>{r['CreateDate']}</CreateDate>"+ f"<AssumeRolePolicyDocument>{assume_doc}</AssumeRolePolicyDocument>"+ f"<Description>{desc}</Description>"+ f"<MaxSessionDuration>{max_dur}</MaxSessionDuration>"+ f"{tags_xml}")+++def _managed_policy_xml(arn):+ pol = _policies[arn]+ return (f"<PolicyName>{pol['PolicyName']}</PolicyName>"+ f"<Arn>{arn}</Arn>"+ f"<PolicyId>{pol['PolicyId']}</PolicyId>"+ f"<DefaultVersionId>{pol['DefaultVersionId']}</DefaultVersionId>"+ f"<AttachmentCount>{pol.get('AttachmentCount', 0)}</AttachmentCount>"+ f"<IsAttachable>true</IsAttachable>"+ f"<CreateDate>{pol['CreateDate']}</CreateDate>"+ f"<UpdateDate>{pol.get('UpdateDate', pol['CreateDate'])}</UpdateDate>"+ f"<Path>{pol.get('Path', '/')}</Path>")+++def _group_xml(name):+ g = _groups[name]+ return (f"<GroupName>{g['GroupName']}</GroupName>"+ f"<GroupId>{g['GroupId']}</GroupId>"+ f"<Arn>{g['Arn']}</Arn>"+ f"<Path>{g['Path']}</Path>"+ f"<CreateDate>{g['CreateDate']}</CreateDate>")+++def _instance_profile_xml(name):+ ip = _instance_profiles[name]+ roles_xml = ""+ for rname in ip["Roles"]:+ if rname in _roles:+ roles_xml += f"<member>{_role_xml(rname)}</member>"+ return (f"<InstanceProfileName>{ip['InstanceProfileName']}</InstanceProfileName>"+ f"<InstanceProfileId>{ip['InstanceProfileId']}</InstanceProfileId>"+ f"<Arn>{ip['Arn']}</Arn>"+ f"<Path>{ip['Path']}</Path>"+ f"<CreateDate>{ip['CreateDate']}</CreateDate>"+ f"<Roles>{roles_xml}</Roles>")++def _xml(status, root_tag, inner, ns="iam"):ns_url = {"iam": "https://iam.amazonaws.com/doc/2010-05-08/","sts": "https://sts.amazonaws.com/doc/2011-06-15/",}.get(ns, "")- body = f"""<?xml version="1.0" encoding="UTF-8"?>-<{root_tag} xmlns="{ns_url}">- {inner}- <ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>-</{root_tag}>""".encode("utf-8")+ body = (f'<?xml version="1.0" encoding="UTF-8"?>'+ f'<{root_tag} xmlns="{ns_url}">'+ f'{inner}'+ f'<ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>'+ f'</{root_tag}>').encode("utf-8")return status, {"Content-Type": "application/xml"}, body+++def _error(status, code, message, ns="iam"):+ ns_url = {+ "iam": "https://iam.amazonaws.com/doc/2010-05-08/",+ "sts": "https://sts.amazonaws.com/doc/2011-06-15/",+ }.get(ns, "")+ body = (f'<?xml version="1.0" encoding="UTF-8"?>'+ f'<ErrorResponse xmlns="{ns_url}">'+ f'<Error><Code>{code}</Code><Message>{message}</Message></Error>'+ f'<RequestId>{new_uuid()}</RequestId>'+ f'</ErrorResponse>').encode("utf-8")+ return status, {"Content-Type": "application/xml"}, body+++# -------------------- Handler dispatch table --------------------++_IAM_HANDLERS = {+ "CreateUser": _create_user,+ "GetUser": _get_user,+ "ListUsers": _list_users,+ "DeleteUser": _delete_user,+ "CreateRole": _create_role,+ "GetRole": _get_role,+ "ListRoles": _list_roles,+ "DeleteRole": _delete_role,+ "CreatePolicy": _create_policy,+ "GetPolicy": _get_policy,+ "GetPolicyVersion": _get_policy_version,+ "ListPolicyVersions": _list_policy_versions,+ "CreatePolicyVersion": _create_policy_version,+ "DeletePolicyVersion": _delete_policy_version,+ "ListPolicies": _list_policies,+ "DeletePolicy": _delete_policy,+ "AttachRolePolicy": _attach_role_policy,+ "DetachRolePolicy": _detach_role_policy,+ "ListAttachedRolePolicies": _list_attached_role_policies,+ "PutRolePolicy": _put_role_policy,+ "GetRolePolicy": _get_role_policy,+ "DeleteRolePolicy": _delete_role_policy,+ "ListRolePolicies": _list_role_policies,+ "AttachUserPolicy": _attach_user_policy,+ "DetachUserPolicy": _detach_user_policy,+ "ListAttachedUserPolicies": _list_attached_user_policies,+ "CreateAccessKey": _create_access_key,+ "ListAccessKeys": _list_access_keys,+ "DeleteAccessKey": _delete_access_key,+ "CreateInstanceProfile": _create_instance_profile,+ "DeleteInstanceProfile": _delete_instance_profile,+ "GetInstanceProfile": _get_instance_profile,+ "AddRoleToInstanceProfile": _add_role_to_instance_profile,+ "RemoveRoleFromInstanceProfile": _remove_role_from_instance_profile,+ "ListInstanceProfiles": _list_instance_profiles,+ "ListInstanceProfilesForRole": _list_instance_profiles_for_role,+ "UpdateAssumeRolePolicy": _update_assume_role_policy,+ "TagRole": _tag_role,+ "UntagRole": _untag_role,+ "ListRoleTags": _list_role_tags,+ "TagUser": _tag_user,+ "UntagUser": _untag_user,+ "ListUserTags": _list_user_tags,+ "SimulatePrincipalPolicy": _simulate_principal_policy,+ "SimulateCustomPolicy": _simulate_custom_policy,+ "CreateGroup": _create_group,+ "GetGroup": _get_group,+ "DeleteGroup": _delete_group,+ "ListGroups": _list_groups,+ "AddUserToGroup": _add_user_to_group,+ "RemoveUserFromGroup": _remove_user_from_group,+ "ListGroupsForUser": _list_groups_for_user,+ "PutUserPolicy": _put_user_policy,+ "GetUserPolicy": _get_user_policy,+ "DeleteUserPolicy": _delete_user_policy,+ "ListUserPolicies": _list_user_policies,+ "CreateServiceLinkedRole": _create_service_linked_role,+ "CreateOpenIDConnectProvider": _create_oidc_provider,+ "GetOpenIDConnectProvider": _get_oidc_provider,+ "DeleteOpenIDConnectProvider": _delete_oidc_provider,+ "TagPolicy": _tag_policy,+ "UntagPolicy": _untag_policy,+ "ListPolicyTags": _list_policy_tags,+}+++def reset():+ _users.clear()+ _roles.clear()+ _policies.clear()+ _access_keys.clear()+ _instance_profiles.clear()+ _groups.clear()+ _user_inline_policies.clear()+ _oidc_providers.clear()diff --git a/services/kinesis.py b/services/kinesis.pyindex 5589a40e..5ee3cde9 100644--- a/services/kinesis.py+++ b/services/kinesis.py@@ -3,7 +3,13 @@ Kinesis Data Streams Emulator.JSON-based API via X-Amz-Target (Kinesis_20131202).Supports: CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary,ListStreams, PutRecord, PutRecords, GetShardIterator, GetRecords,- MergeShards, SplitShard, ListShards.+ MergeShards, SplitShard, UpdateShardCount, ListShards,+ IncreaseStreamRetentionPeriod, DecreaseStreamRetentionPeriod,+ AddTagsToStream, RemoveTagsFromStream, ListTagsForStream,+ RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers,+ DescribeStreamConsumer,+ StartStreamEncryption, StopStreamEncryption,+ EnableEnhancedMonitoring, DisableEnhancedMonitoring."""import json@@ -11,6 +17,7 @@ import timeimport base64import hashlibimport logging+import threadingfrom core.responses import json_response, error_response_json, new_uuid@@ -18,11 +25,100 @@ logger = logging.getLogger("kinesis")ACCOUNT_ID = "000000000000"REGION = "us-east-1"+MAX_HASH_KEY = (2**128) - 1+ITERATOR_EXPIRY_SECONDS = 300-_streams: dict = {} # stream_name -> {arn, shards: {shard_id: {records: [...]}}, status, retention}-_shard_iterators: dict = {} # iterator_token -> {stream, shard_id, position}+_streams: dict = {}+_shard_iterators: dict = {}+_consumers: dict = {}+_sequence_counter = 0+_sequence_lock = threading.Lock()+def _next_sequence_number():+ global _sequence_counter+ with _sequence_lock:+ _sequence_counter += 1+ ts_millis = int(time.time() * 1000)+ return f"{ts_millis:020d}{_sequence_counter:010d}"+++def _compute_hash_ranges(shard_count):+ range_size = (MAX_HASH_KEY + 1) // shard_count+ ranges = []+ for i in range(shard_count):+ start = i * range_size+ end = ((i + 1) * range_size - 1) if i < shard_count - 1 else MAX_HASH_KEY+ ranges.append((str(start), str(end)))+ return ranges+++def _build_shards(shard_count, start_index=0):+ ranges = _compute_hash_ranges(shard_count)+ shards = {}+ for i in range(shard_count):+ sid = f"shardId-{start_index + i:012d}"+ shards[sid] = {+ "records": [],+ "starting_hash_key": ranges[i][0],+ "ending_hash_key": ranges[i][1],+ "starting_sequence_number": _next_sequence_number(),+ "parent_shard_id": None,+ "adjacent_parent_shard_id": None,+ }+ return shards+++def _partition_key_to_hash(partition_key: str) -> int:+ return int(hashlib.md5(partition_key.encode("utf-8")).hexdigest(), 16)+++def _route_to_shard(hash_key_int: int, stream: dict) -> str:+ for sid, shard in stream["shards"].items():+ if int(shard["starting_hash_key"]) <= hash_key_int <= int(shard["ending_hash_key"]):+ return sid+ return next(iter(stream["shards"]))+++def _expire_records(stream):+ cutoff = time.time() - stream["RetentionPeriodHours"] * 3600+ for shard in stream["shards"].values():+ shard["records"] = [r for r in shard["records"] if r["ApproximateArrivalTimestamp"] >= cutoff]+++def _expire_iterators():+ now = time.time()+ expired = [tok for tok, st in _shard_iterators.items()+ if now - st["created_at"] > ITERATOR_EXPIRY_SECONDS]+ for tok in expired:+ del _shard_iterators[tok]+++def _ensure_active(stream):+ if stream["StreamStatus"] == "CREATING":+ stream["StreamStatus"] = "ACTIVE"+++def _resolve_stream(data):+ name = data.get("StreamName")+ arn = data.get("StreamARN")+ if name and name in _streams:+ return name, _streams[name]+ if arn:+ for n, s in _streams.items():+ if s["StreamARN"] == arn:+ return n, s+ return name or arn, None+++def _max_shard_index(stream):+ return max((int(sid.split("-")[1]) for sid in stream["shards"]), default=-1)+++# ---------------------------------------------------------------------------+# Request dispatcher+# ---------------------------------------------------------------------------+async def handle_request(method, path, headers, body, query_params):target = headers.get("x-amz-target", "")action = target.split(".")[-1] if "." in target else ""@@ -32,6 +128,8 @@ async def handle_request(method, path, headers, body, query_params):except json.JSONDecodeError:return error_response_json("SerializationException", "Invalid JSON", 400)+ _expire_iterators()+handlers = {"CreateStream": _create_stream,"DeleteStream": _delete_stream,@@ -46,7 +144,19 @@ async def handle_request(method, path, headers, body, query_params):"IncreaseStreamRetentionPeriod": _increase_retention,"DecreaseStreamRetentionPeriod": _decrease_retention,"AddTagsToStream": _add_tags,+ "RemoveTagsFromStream": _remove_tags,"ListTagsForStream": _list_tags,+ "MergeShards": _merge_shards,+ "SplitShard": _split_shard,+ "UpdateShardCount": _update_shard_count,+ "RegisterStreamConsumer": _register_consumer,+ "DeregisterStreamConsumer": _deregister_consumer,+ "ListStreamConsumers": _list_consumers,+ "DescribeStreamConsumer": _describe_stream_consumer,+ "StartStreamEncryption": _start_stream_encryption,+ "StopStreamEncryption": _stop_stream_encryption,+ "EnableEnhancedMonitoring": _enable_enhanced_monitoring,+ "DisableEnhancedMonitoring": _disable_enhanced_monitoring,}handler = handlers.get(action)@@ -55,6 +165,10 @@ async def handle_request(method, path, headers, body, query_params):return handler(data)+# ---------------------------------------------------------------------------+# Stream lifecycle+# ---------------------------------------------------------------------------+def _create_stream(data):name = data.get("StreamName")shard_count = data.get("ShardCount", 1)@@ -62,240 +176,689 @@ def _create_stream(data):return error_response_json("ValidationException", "StreamName is required", 400)if name in _streams:return error_response_json("ResourceInUseException", f"Stream {name} already exists", 400)+ if shard_count < 1:+ return error_response_json("ValidationException", "ShardCount must be at least 1", 400)arn = f"arn:aws:kinesis:{REGION}:{ACCOUNT_ID}:stream/{name}"- shards = {}- for i in range(shard_count):- shard_id = f"shardId-{i:012d}"- shards[shard_id] = {- "records": [],- "sequence_counter": 0,- "tags": {},- }-+ mode = data.get("StreamModeDetails", {}).get("StreamMode", "PROVISIONED")_streams[name] = {"StreamName": name,"StreamARN": arn,"StreamStatus": "ACTIVE",+ "StreamModeDetails": {"StreamMode": mode},"RetentionPeriodHours": 24,- "shards": shards,+ "shards": _build_shards(shard_count),"tags": {},"CreationTimestamp": time.time(),+ "EncryptionType": "NONE",}return json_response({})def _delete_stream(data):- name = data.get("StreamName")- if name not in _streams:+ name, stream = _resolve_stream(data)+ if not stream:return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ stream["StreamStatus"] = "DELETING"+ for tok in [t for t, s in _shard_iterators.items() if s["stream"] == name]:+ del _shard_iterators[tok]+ for carn in [a for a, c in _consumers.items() if c["StreamARN"] == stream["StreamARN"]]:+ del _consumers[carn]del _streams[name]return json_response({})+# ---------------------------------------------------------------------------+# Describe / List+# ---------------------------------------------------------------------------+def _describe_stream(data):- name = data.get("StreamName")- stream = _streams.get(name)+ name, stream = _resolve_stream(data)if not stream:return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)- return json_response({"StreamDescription": _stream_desc(stream)})+ _ensure_active(stream)+ _expire_records(stream)++ limit = data.get("Limit", 100)+ exclusive_start = data.get("ExclusiveStartShardId")+ shard_ids = sorted(stream["shards"].keys())+ if exclusive_start:+ shard_ids = [s for s in shard_ids if s > exclusive_start]+ page = shard_ids[:limit]+ has_more = len(shard_ids) > limit++ desc = _stream_desc(stream, page)+ desc["HasMoreShards"] = has_more+ return json_response({"StreamDescription": desc})def _describe_stream_summary(data):- name = data.get("StreamName")- stream = _streams.get(name)+ name, stream = _resolve_stream(data)if not stream:return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)- desc = _stream_desc(stream)- desc.pop("Shards", None)- return json_response({"StreamDescriptionSummary": {**desc, "OpenShardCount": len(stream["shards"])}})+ _ensure_active(stream)+ consumer_count = sum(1 for c in _consumers.values() if c["StreamARN"] == stream["StreamARN"])+ return json_response({"StreamDescriptionSummary": {+ "StreamName": stream["StreamName"],+ "StreamARN": stream["StreamARN"],+ "StreamStatus": stream["StreamStatus"],+ "StreamModeDetails": stream.get("StreamModeDetails", {"StreamMode": "PROVISIONED"}),+ "RetentionPeriodHours": stream["RetentionPeriodHours"],+ "StreamCreationTimestamp": stream["CreationTimestamp"],+ "EnhancedMonitoring": [{"ShardLevelMetrics": []}],+ "EncryptionType": stream.get("EncryptionType", "NONE"),+ "OpenShardCount": len(stream["shards"]),+ "ConsumerCount": consumer_count,+ }})def _list_streams(data):- names = list(_streams.keys())- return json_response({"StreamNames": names, "HasMoreStreams": False})+ limit = data.get("Limit", 100)+ exclusive_start = data.get("ExclusiveStartStreamName")+ names = sorted(_streams.keys())+ if exclusive_start:+ names = [n for n in names if n > exclusive_start]+ page = names[:limit]+ has_more = len(names) > limit+ summaries = []+ for n in page:+ s = _streams[n]+ summaries.append({+ "StreamName": n,+ "StreamARN": s["StreamARN"],+ "StreamStatus": s["StreamStatus"],+ "StreamModeDetails": s.get("StreamModeDetails", {"StreamMode": "PROVISIONED"}),+ "StreamCreationTimestamp": s["CreationTimestamp"],+ })+ return json_response({"StreamNames": page, "StreamSummaries": summaries, "HasMoreStreams": has_more})def _list_shards(data):- name = data.get("StreamName")- stream = _streams.get(name)+ name, stream = _resolve_stream(data)if not stream:return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)- shards = [_shard_out(sid, s) for sid, s in stream["shards"].items()]- return json_response({"Shards": shards})+ _ensure_active(stream)++ max_results = data.get("MaxResults", 10000)+ next_token = data.get("NextToken")+ exclusive_start = data.get("ExclusiveStartShardId")++ shard_ids = sorted(stream["shards"].keys())+ if exclusive_start:+ shard_ids = [s for s in shard_ids if s > exclusive_start]+ if next_token:+ shard_ids = [s for s in shard_ids if s > next_token]++ page = shard_ids[:max_results]+ result = {"Shards": [_shard_out(sid, stream["shards"][sid]) for sid in page]}+ if len(shard_ids) > max_results:+ result["NextToken"] = page[-1]+ return json_response(result)+# ---------------------------------------------------------------------------+# Put records+# ---------------------------------------------------------------------------+def _put_record(data):- name = data.get("StreamName")- stream = _streams.get(name)+ name, stream = _resolve_stream(data)if not stream:return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ if stream["StreamStatus"] != "ACTIVE":+ return error_response_json("ResourceInUseException", f"Stream {name} is {stream['StreamStatus']}", 400)++ _expire_records(stream)partition_key = data.get("PartitionKey", "")record_data = data.get("Data", "")+ explicit_hash = data.get("ExplicitHashKey")+ if not partition_key:+ return error_response_json("ValidationException", "PartitionKey is required", 400)- # Route to shard based on partition key hash- shard_id = _get_shard_for_key(partition_key, len(stream["shards"]))- shard = stream["shards"][shard_id]- shard["sequence_counter"] += 1- seq = f"{int(time.time() * 1000):020d}{shard['sequence_counter']:010d}"+ hash_int = int(explicit_hash) if explicit_hash else _partition_key_to_hash(partition_key)+ shard_id = _route_to_shard(hash_int, stream)+ seq = _next_sequence_number()- shard["records"].append({+ stream["shards"][shard_id]["records"].append({"SequenceNumber": seq,"ApproximateArrivalTimestamp": time.time(),"Data": record_data,"PartitionKey": partition_key,})-- return json_response({"ShardId": shard_id, "SequenceNumber": seq})+ return json_response({+ "ShardId": shard_id,+ "SequenceNumber": seq,+ "EncryptionType": stream.get("EncryptionType", "NONE"),+ })def _put_records(data):- name = data.get("StreamName")- stream = _streams.get(name)+ name, stream = _resolve_stream(data)if not stream:return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ if stream["StreamStatus"] != "ACTIVE":+ return error_response_json("ResourceInUseException", f"Stream {name} is {stream['StreamStatus']}", 400)++ _expire_records(stream)- records = data.get("Records", [])results = []- failed = 0-- for rec in records:- partition_key = rec.get("PartitionKey", "")- record_data = rec.get("Data", "")- shard_id = _get_shard_for_key(partition_key, len(stream["shards"]))- shard = stream["shards"][shard_id]- shard["sequence_counter"] += 1- seq = f"{int(time.time() * 1000):020d}{shard['sequence_counter']:010d}"- shard["records"].append({+ for rec in data.get("Records", []):+ pk = rec.get("PartitionKey", "")+ rd = rec.get("Data", "")+ eh = rec.get("ExplicitHashKey")+ hash_int = int(eh) if eh else _partition_key_to_hash(pk)+ sid = _route_to_shard(hash_int, stream)+ seq = _next_sequence_number()+ stream["shards"][sid]["records"].append({"SequenceNumber": seq,"ApproximateArrivalTimestamp": time.time(),- "Data": record_data,- "PartitionKey": partition_key,+ "Data": rd,+ "PartitionKey": pk,+ })+ results.append({+ "SequenceNumber": seq,+ "ShardId": sid,+ "EncryptionType": stream.get("EncryptionType", "NONE"),})- results.append({"SequenceNumber": seq, "ShardId": shard_id})+ return json_response({+ "FailedRecordCount": 0,+ "Records": results,+ "EncryptionType": stream.get("EncryptionType", "NONE"),+ })- return json_response({"FailedRecordCount": failed, "Records": results})+# ---------------------------------------------------------------------------+# Shard iterators / GetRecords+# ---------------------------------------------------------------------------def _get_shard_iterator(data):- name = data.get("StreamName")- shard_id = data.get("ShardId")- iterator_type = data.get("ShardIteratorType", "LATEST")- seq = data.get("StartingSequenceNumber", "")-- stream = _streams.get(name)+ name, stream = _resolve_stream(data)if not stream:return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)++ shard_id = data.get("ShardId")if shard_id not in stream["shards"]:return error_response_json("ResourceNotFoundException", f"Shard {shard_id} not found", 400)+ _expire_records(stream)shard = stream["shards"][shard_id]- if iterator_type == "TRIM_HORIZON":+ records = shard["records"]+ it_type = data.get("ShardIteratorType", "LATEST")+ seq = data.get("StartingSequenceNumber", "")+ at_ts = data.get("Timestamp")++ if it_type == "TRIM_HORIZON":position = 0- elif iterator_type == "LATEST":- position = len(shard["records"])- elif iterator_type in ("AT_SEQUENCE_NUMBER", "AFTER_SEQUENCE_NUMBER"):- records = shard["records"]+ elif it_type == "LATEST":+ position = len(records)+ elif it_type == "AT_SEQUENCE_NUMBER":position = next((i for i, r in enumerate(records) if r["SequenceNumber"] >= seq), len(records))- if iterator_type == "AFTER_SEQUENCE_NUMBER":- position += 1+ elif it_type == "AFTER_SEQUENCE_NUMBER":+ position = next((i for i, r in enumerate(records) if r["SequenceNumber"] > seq), len(records))+ elif it_type == "AT_TIMESTAMP":+ if at_ts is None:+ return error_response_json("ValidationException", "Timestamp required for AT_TIMESTAMP", 400)+ ts_val = float(at_ts)+ position = next((i for i, r in enumerate(records) if r["ApproximateArrivalTimestamp"] >= ts_val), len(records))else:- position = len(shard["records"])+ return error_response_json("ValidationException", f"Invalid ShardIteratorType: {it_type}", 400)+ resolved_name = name if name else next((n for n, s in _streams.items() if s is stream), "")token = new_uuid()- _shard_iterators[token] = {"stream": name, "shard_id": shard_id, "position": position}+ _shard_iterators[token] = {+ "stream": resolved_name,+ "shard_id": shard_id,+ "position": position,+ "created_at": time.time(),+ }return json_response({"ShardIterator": token})+def _ensure_base64(value):+ """Return a base64-encoded string regardless of input format."""+ if isinstance(value, bytes):+ return base64.b64encode(value).decode("ascii")+ if isinstance(value, str):+ try:+ base64.b64decode(value, validate=True)+ return value+ except Exception:+ return base64.b64encode(value.encode("utf-8")).decode("ascii")+ return base64.b64encode(str(value).encode("utf-8")).decode("ascii")++def _get_records(data):iterator = data.get("ShardIterator")- limit = data.get("Limit", 10000)+ limit = min(data.get("Limit", 10000), 10000)- state = _shard_iterators.get(iterator)+ state = _shard_iterators.pop(iterator, None)if not state:- return error_response_json("ExpiredIteratorException", "Shard iterator has expired", 400)+ return error_response_json("ExpiredIteratorException", "Iterator has expired or is invalid", 400)+ if time.time() - state["created_at"] > ITERATOR_EXPIRY_SECONDS:+ return error_response_json("ExpiredIteratorException", "Iterator has expired", 400)stream = _streams.get(state["stream"])if not stream:return error_response_json("ResourceNotFoundException", "Stream not found", 400)+ _expire_records(stream)shard = stream["shards"].get(state["shard_id"])if not shard:return error_response_json("ResourceNotFoundException", "Shard not found", 400)- pos = state["position"]- records = shard["records"][pos:pos + limit]- new_pos = pos + len(records)- state["position"] = new_pos+ pos = min(state["position"], len(shard["records"]))+ raw = shard["records"][pos:pos + limit]+ new_pos = pos + len(raw)- next_token = new_uuid()- _shard_iterators[next_token] = {"stream": state["stream"], "shard_id": state["shard_id"], "position": new_pos}+ out_records = [{+ "SequenceNumber": r["SequenceNumber"],+ "ApproximateArrivalTimestamp": r["ApproximateArrivalTimestamp"],+ "Data": _ensure_base64(r["Data"]),+ "PartitionKey": r["PartitionKey"],+ "EncryptionType": stream.get("EncryptionType", "NONE"),+ } for r in raw]++ millis_behind = 0+ if shard["records"] and new_pos < len(shard["records"]):+ millis_behind = max(0, int((time.time() - shard["records"][new_pos]["ApproximateArrivalTimestamp"]) * 1000))+ next_token = new_uuid()+ _shard_iterators[next_token] = {+ "stream": state["stream"],+ "shard_id": state["shard_id"],+ "position": new_pos,+ "created_at": time.time(),+ }return json_response({- "Records": records,+ "Records": out_records,"NextShardIterator": next_token,- "MillisBehindLatest": 0,+ "MillisBehindLatest": millis_behind,})+# ---------------------------------------------------------------------------+# Retention period+# ---------------------------------------------------------------------------+def _increase_retention(data):- name = data.get("StreamName")- hours = data.get("RetentionPeriodHours", 24)- if name in _streams:- _streams[name]["RetentionPeriodHours"] = hours+ name, stream = _resolve_stream(data)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ hours = data.get("RetentionPeriodHours")+ if hours is None:+ return error_response_json("ValidationException", "RetentionPeriodHours is required", 400)+ hours = int(hours)+ if hours <= stream["RetentionPeriodHours"]:+ return error_response_json("ValidationException",+ "RetentionPeriodHours must be greater than current value", 400)+ if hours > 8760:+ return error_response_json("ValidationException",+ "RetentionPeriodHours cannot exceed 8760", 400)+ stream["RetentionPeriodHours"] = hoursreturn json_response({})def _decrease_retention(data):- name = data.get("StreamName")- hours = data.get("RetentionPeriodHours", 24)- if name in _streams:- _streams[name]["RetentionPeriodHours"] = hours+ name, stream = _resolve_stream(data)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ hours = data.get("RetentionPeriodHours")+ if hours is None:+ return error_response_json("ValidationException", "RetentionPeriodHours is required", 400)+ hours = int(hours)+ if hours >= stream["RetentionPeriodHours"]:+ return error_response_json("ValidationException",+ "RetentionPeriodHours must be less than current value", 400)+ if hours < 24:+ return error_response_json("ValidationException",+ "RetentionPeriodHours cannot be less than 24", 400)+ stream["RetentionPeriodHours"] = hoursreturn json_response({})+# ---------------------------------------------------------------------------+# Tags+# ---------------------------------------------------------------------------+def _add_tags(data):- name = data.get("StreamName")- tags = data.get("Tags", {})- if name in _streams:- _streams[name]["tags"].update(tags)+ name, stream = _resolve_stream(data)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ stream["tags"].update(data.get("Tags", {}))+ return json_response({})+++def _remove_tags(data):+ name, stream = _resolve_stream(data)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ for key in data.get("TagKeys", []):+ stream["tags"].pop(key, None)return json_response({})def _list_tags(data):- name = data.get("StreamName")- stream = _streams.get(name)+ name, stream = _resolve_stream(data)if not stream:return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)- tags = [{"Key": k, "Value": v} for k, v in stream["tags"].items()]- return json_response({"Tags": tags, "HasMoreTags": False})+ limit = data.get("Limit", 50)+ exclusive_start = data.get("ExclusiveStartTagKey")+ items = sorted(stream["tags"].items())+ if exclusive_start:+ items = [(k, v) for k, v in items if k > exclusive_start]+ page = items[:limit]+ return json_response({+ "Tags": [{"Key": k, "Value": v} for k, v in page],+ "HasMoreTags": len(items) > limit,+ })+++# ---------------------------------------------------------------------------+# MergeShards / SplitShard / UpdateShardCount+# ---------------------------------------------------------------------------+def _merge_shards(data):+ name, stream = _resolve_stream(data)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ s1_id = data.get("ShardToMerge")+ s2_id = data.get("AdjacentShardToMerge")+ if s1_id not in stream["shards"]:+ return error_response_json("ResourceNotFoundException", f"Shard {s1_id} not found", 400)+ if s2_id not in stream["shards"]:+ return error_response_json("ResourceNotFoundException", f"Shard {s2_id} not found", 400)++ s1, s2 = stream["shards"][s1_id], stream["shards"][s2_id]+ new_start = str(min(int(s1["starting_hash_key"]), int(s2["starting_hash_key"])))+ new_end = str(max(int(s1["ending_hash_key"]), int(s2["ending_hash_key"])))++ new_idx = _max_shard_index(stream) + 1+ new_sid = f"shardId-{new_idx:012d}"+ stream["shards"][new_sid] = {+ "records": [],+ "starting_hash_key": new_start,+ "ending_hash_key": new_end,+ "starting_sequence_number": _next_sequence_number(),+ "parent_shard_id": s1_id,+ "adjacent_parent_shard_id": s2_id,+ }+ del stream["shards"][s1_id]+ del stream["shards"][s2_id]+ return json_response({})-# --- Helpers ----def _get_shard_for_key(partition_key: str, shard_count: int) -> str:- h = int(hashlib.md5(partition_key.encode()).hexdigest(), 16)- idx = h % shard_count- return f"shardId-{idx:012d}"+def _split_shard(data):+ name, stream = _resolve_stream(data)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ shard_id = data.get("ShardToSplit")+ new_hash = data.get("NewStartingHashKey")+ if shard_id not in stream["shards"]:+ return error_response_json("ResourceNotFoundException", f"Shard {shard_id} not found", 400)+ if not new_hash:+ return error_response_json("ValidationException", "NewStartingHashKey is required", 400)++ old = stream["shards"][shard_id]+ split_pt = int(new_hash)+ old_start, old_end = int(old["starting_hash_key"]), int(old["ending_hash_key"])+ if split_pt <= old_start or split_pt > old_end:+ return error_response_json("ValidationException",+ "NewStartingHashKey must be within the shard range", 400)++ base = _max_shard_index(stream) + 1+ c1 = f"shardId-{base:012d}"+ c2 = f"shardId-{base + 1:012d}"+ stream["shards"][c1] = {+ "records": [],+ "starting_hash_key": str(old_start),+ "ending_hash_key": str(split_pt - 1),+ "starting_sequence_number": _next_sequence_number(),+ "parent_shard_id": shard_id,+ "adjacent_parent_shard_id": None,+ }+ stream["shards"][c2] = {+ "records": [],+ "starting_hash_key": str(split_pt),+ "ending_hash_key": str(old_end),+ "starting_sequence_number": _next_sequence_number(),+ "parent_shard_id": shard_id,+ "adjacent_parent_shard_id": None,+ }+ del stream["shards"][shard_id]+ return json_response({})+def _update_shard_count(data):+ name, stream = _resolve_stream(data)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ target = data.get("TargetShardCount")+ if target is None:+ return error_response_json("ValidationException", "TargetShardCount is required", 400)+ target = int(target)+ if target < 1:+ return error_response_json("ValidationException", "TargetShardCount must be >= 1", 400)++ current = len(stream["shards"])+ stream["shards"] = _build_shards(target)+ return json_response({+ "StreamName": stream["StreamName"],+ "CurrentShardCount": current,+ "TargetShardCount": target,+ "StreamARN": stream["StreamARN"],+ })+++# ---------------------------------------------------------------------------+# Enhanced fan-out consumers+# ---------------------------------------------------------------------------++def _register_consumer(data):+ stream_arn = data.get("StreamARN")+ consumer_name = data.get("ConsumerName")+ if not stream_arn or not consumer_name:+ return error_response_json("ValidationException",+ "StreamARN and ConsumerName are required", 400)+ stream = next((s for s in _streams.values() if s["StreamARN"] == stream_arn), None)+ if not stream:+ return error_response_json("ResourceNotFoundException",+ f"Stream with ARN {stream_arn} not found", 400)+ for c in _consumers.values():+ if c["StreamARN"] == stream_arn and c["ConsumerName"] == consumer_name:+ return error_response_json("ResourceInUseException",+ f"Consumer {consumer_name} already exists", 400)++ consumer_arn = f"{stream_arn}/consumer/{consumer_name}:{int(time.time())}"+ now = time.time()+ _consumers[consumer_arn] = {+ "ConsumerName": consumer_name,+ "ConsumerARN": consumer_arn,+ "ConsumerStatus": "ACTIVE",+ "ConsumerCreationTimestamp": now,+ "StreamARN": stream_arn,+ }+ return json_response({"Consumer": {+ "ConsumerName": consumer_name,+ "ConsumerARN": consumer_arn,+ "ConsumerStatus": "ACTIVE",+ "ConsumerCreationTimestamp": now,+ }})+++def _deregister_consumer(data):+ consumer_arn = data.get("ConsumerARN")+ stream_arn = data.get("StreamARN")+ consumer_name = data.get("ConsumerName")+ if consumer_arn:+ if consumer_arn not in _consumers:+ return error_response_json("ResourceNotFoundException", "Consumer not found", 400)+ del _consumers[consumer_arn]+ elif stream_arn and consumer_name:+ found = next((a for a, c in _consumers.items()+ if c["StreamARN"] == stream_arn and c["ConsumerName"] == consumer_name), None)+ if not found:+ return error_response_json("ResourceNotFoundException", "Consumer not found", 400)+ del _consumers[found]+ else:+ return error_response_json("ValidationException",+ "ConsumerARN or StreamARN+ConsumerName required", 400)+ return json_response({})+++def _list_consumers(data):+ stream_arn = data.get("StreamARN")+ if not stream_arn:+ return error_response_json("ValidationException", "StreamARN is required", 400)+ max_results = data.get("MaxResults", 100)+ next_token = data.get("NextToken")++ items = [{+ "ConsumerName": c["ConsumerName"],+ "ConsumerARN": c["ConsumerARN"],+ "ConsumerStatus": c["ConsumerStatus"],+ "ConsumerCreationTimestamp": c["ConsumerCreationTimestamp"],+ } for c in _consumers.values() if c["StreamARN"] == stream_arn]++ start = 0+ if next_token:+ try:+ start = int(next_token)+ except ValueError:+ start = 0+ page = items[start:start + max_results]+ result = {"Consumers": page}+ if start + max_results < len(items):+ result["NextToken"] = str(start + max_results)+ return json_response(result)+++def _describe_stream_consumer(data):+ consumer_arn = data.get("ConsumerARN")+ stream_arn = data.get("StreamARN")+ consumer_name = data.get("ConsumerName")++ consumer = None+ if consumer_arn:+ consumer = _consumers.get(consumer_arn)+ elif stream_arn and consumer_name:+ consumer = next(+ (c for c in _consumers.values()+ if c["StreamARN"] == stream_arn and c["ConsumerName"] == consumer_name),+ None,+ )++ if not consumer:+ return error_response_json("ResourceNotFoundException", "Consumer not found", 400)++ return json_response({"ConsumerDescription": {+ "ConsumerName": consumer["ConsumerName"],+ "ConsumerARN": consumer["ConsumerARN"],+ "ConsumerStatus": consumer["ConsumerStatus"],+ "ConsumerCreationTimestamp": consumer["ConsumerCreationTimestamp"],+ "StreamARN": consumer["StreamARN"],+ }})+++# ---------------------------------------------------------------------------+# Stream encryption+# ---------------------------------------------------------------------------++def _start_stream_encryption(data):+ name, stream = _resolve_stream(data)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ encryption_type = data.get("EncryptionType", "KMS")+ key_id = data.get("KeyId", "")+ stream["EncryptionType"] = encryption_type+ stream["KeyId"] = key_id+ return json_response({})+++def _stop_stream_encryption(data):+ name, stream = _resolve_stream(data)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ stream["EncryptionType"] = "NONE"+ stream.pop("KeyId", None)+ return json_response({})+++# ---------------------------------------------------------------------------+# Enhanced monitoring+# ---------------------------------------------------------------------------++def _enable_enhanced_monitoring(data):+ name, stream = _resolve_stream(data)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ desired = data.get("ShardLevelMetrics", [])+ current = stream.get("ShardLevelMetrics", [])+ merged = list(set(current) | set(desired))+ stream["ShardLevelMetrics"] = merged+ return json_response({+ "StreamName": stream["StreamName"],+ "StreamARN": stream["StreamARN"],+ "CurrentShardLevelMetrics": current,+ "DesiredShardLevelMetrics": merged,+ })+++def _disable_enhanced_monitoring(data):+ name, stream = _resolve_stream(data)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ to_disable = set(data.get("ShardLevelMetrics", []))+ current = stream.get("ShardLevelMetrics", [])+ remaining = [m for m in current if m not in to_disable]+ stream["ShardLevelMetrics"] = remaining+ return json_response({+ "StreamName": stream["StreamName"],+ "StreamARN": stream["StreamARN"],+ "CurrentShardLevelMetrics": current,+ "DesiredShardLevelMetrics": remaining,+ })+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+def _shard_out(shard_id, shard):- return {+ result = {"ShardId": shard_id,- "HashKeyRange": {"StartingHashKey": "0", "EndingHashKey": "340282366920938463463374607431768211455"},- "SequenceNumberRange": {"StartingSequenceNumber": "0"},+ "HashKeyRange": {+ "StartingHashKey": shard["starting_hash_key"],+ "EndingHashKey": shard["ending_hash_key"],+ },+ "SequenceNumberRange": {+ "StartingSequenceNumber": shard["starting_sequence_number"],+ },}+ if shard.get("parent_shard_id"):+ result["ParentShardId"] = shard["parent_shard_id"]+ if shard.get("adjacent_parent_shard_id"):+ result["AdjacentParentShardId"] = shard["adjacent_parent_shard_id"]+ return result-def _stream_desc(stream):+def _stream_desc(stream, shard_ids=None):+ if shard_ids is None:+ shard_ids = sorted(stream["shards"].keys())return {"StreamName": stream["StreamName"],"StreamARN": stream["StreamARN"],"StreamStatus": stream["StreamStatus"],+ "StreamModeDetails": stream.get("StreamModeDetails", {"StreamMode": "PROVISIONED"}),"RetentionPeriodHours": stream["RetentionPeriodHours"],"StreamCreationTimestamp": stream["CreationTimestamp"],- "Shards": [_shard_out(sid, s) for sid, s in stream["shards"].items()],+ "Shards": [_shard_out(sid, stream["shards"][sid]) for sid in shard_ids],"HasMoreShards": False,"EnhancedMonitoring": [{"ShardLevelMetrics": []}],+ "EncryptionType": stream.get("EncryptionType", "NONE"),}+++def reset():+ _streams.clear()+ _shard_iterators.clear()+ _consumers.clear()diff --git a/services/lambda_svc.py b/services/lambda_svc.pyindex 37cfd63b..00024c73 100644--- a/services/lambda_svc.py+++ b/services/lambda_svc.py@@ -1,66 +1,313 @@"""Lambda Service Emulator.-Supports: CreateFunction, DeleteFunction, GetFunction, ListFunctions,- Invoke, UpdateFunctionCode, UpdateFunctionConfiguration,+Supports: CreateFunction, DeleteFunction, GetFunction, GetFunctionConfiguration,+ ListFunctions (paginated with Marker/MaxItems), Invoke (RequestResponse / Event / DryRun),+ UpdateFunctionCode, UpdateFunctionConfiguration,+ PublishVersion, ListVersionsByFunction,+ CreateAlias, GetAlias, UpdateAlias, DeleteAlias, ListAliases,+ AddPermission, RemovePermission, GetPolicy,+ ListTags, TagResource, UntagResource,+ PublishLayerVersion, GetLayerVersion, ListLayerVersions,+ DeleteLayerVersion, ListLayers,CreateEventSourceMapping, DeleteEventSourceMapping,- GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping.-Functions are stored in-memory. Invocation runs code in a subprocess (Python only) or returns mock results.-SQS event source mappings poll the queue in a background thread and invoke the Lambda with batches.+ GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping,+ GetFunctionEventInvokeConfig, PutFunctionEventInvokeConfig (stub),+ PutFunctionConcurrency, GetFunctionConcurrency, DeleteFunctionConcurrency,+ GetFunctionCodeSigningConfig (stub),+ CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig,+ DeleteFunctionUrlConfig, ListFunctionUrlConfigs.++Functions are stored in-memory. Python functions are executed in a subprocess+with the event piped through stdin (safe from injection).+SQS event source mappings poll the queue in a background thread."""import os+import copyimport jsonimport timeimport base64+import hashlibimport zipfileimport tempfileimport subprocessimport threadingimport logging+import re+from urllib.parse import unquotefrom core.responses import json_response, error_response_json, new_uuidlogger = logging.getLogger("lambda")ACCOUNT_ID = "000000000000"-REGION = "us-east-1"--_functions: dict = {} # function_name -> {config, code_zip}-_esms: dict = {} # uuid -> esm dict+REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1")+LAMBDA_EXECUTOR = os.environ.get("LAMBDA_EXECUTOR", "local").lower()+LAMBDA_DOCKER_VOLUME_MOUNT = os.environ.get("LAMBDA_REMOTE_DOCKER_VOLUME_MOUNT", "")++try:+ import docker as docker_lib+ _docker_available = True+except ImportError:+ _docker_available = False++_functions: dict = {} # function_name -> FunctionRecord+_layers: dict = {} # layer_name -> {"versions": [...], "next_version": int}+_esms: dict = {} # uuid -> esm dict+_function_urls: dict = {} # function_name -> FunctionUrlConfig dict_poller_started = False_poller_lock = threading.Lock()+# ---------------------------------------------------------------------------+# Wrapper script executed inside the subprocess.+# All configuration is passed through env vars; event data arrives on stdin.+# ---------------------------------------------------------------------------+_WRAPPER_SCRIPT = """\+import sys, os, json++sys.path.insert(0, os.environ["_LAMBDA_CODE_DIR"])++for _ld in filter(None, os.environ.get("_LAMBDA_LAYERS_DIRS", "").split(os.pathsep)):+ _py = os.path.join(_ld, "python")+ if os.path.isdir(_py):+ sys.path.insert(0, _py)+ sys.path.insert(0, _ld)++_mod_path = os.environ["_LAMBDA_HANDLER_MODULE"]+_fn_name = os.environ["_LAMBDA_HANDLER_FUNC"]++event = json.loads(sys.stdin.read())++class LambdaContext:+ function_name = os.environ.get("AWS_LAMBDA_FUNCTION_NAME", "")+ memory_limit_in_mb = int(os.environ.get("AWS_LAMBDA_FUNCTION_MEMORY_SIZE", "128"))+ invoked_function_arn = os.environ.get("_LAMBDA_FUNCTION_ARN", "")+ aws_request_id = os.environ.get("AWS_LAMBDA_LOG_STREAM_NAME", "")+ log_group_name = "/aws/lambda/" + function_name+ log_stream_name = aws_request_id++ @staticmethod+ def get_remaining_time_in_millis():+ return int(float(os.environ.get("_LAMBDA_TIMEOUT", "3")) * 1000)++_mod = __import__(_mod_path)+for _part in _mod_path.split(".")[1:]:+ _mod = getattr(_mod, _part)+_result = getattr(_mod, _fn_name)(event, LambdaContext())+if _result is not None:+ print(json.dumps(_result))+"""++# Docker variant: paths fixed to /var/task (code) and /opt (layers).+_DOCKER_WRAPPER_SCRIPT = """\+import sys, os, json++sys.path.insert(0, "/var/task")++for _ld in filter(None, os.environ.get("_LAMBDA_LAYERS_DIRS", "").split(":")):+ _py = os.path.join(_ld, "python")+ if os.path.isdir(_py):+ sys.path.insert(0, _py)+ sys.path.insert(0, _ld)++_mod_path = os.environ["_LAMBDA_HANDLER_MODULE"]+_fn_name = os.environ["_LAMBDA_HANDLER_FUNC"]++event = json.loads(sys.stdin.read())++class LambdaContext:+ function_name = os.environ.get("AWS_LAMBDA_FUNCTION_NAME", "")+ memory_limit_in_mb = int(os.environ.get("AWS_LAMBDA_FUNCTION_MEMORY_SIZE", "128"))+ invoked_function_arn = os.environ.get("_LAMBDA_FUNCTION_ARN", "")+ aws_request_id = os.environ.get("AWS_LAMBDA_LOG_STREAM_NAME", "")+ log_group_name = "/aws/lambda/" + function_name+ log_stream_name = aws_request_id++ @staticmethod+ def get_remaining_time_in_millis():+ return int(float(os.environ.get("_LAMBDA_TIMEOUT", "3")) * 1000)++_mod = __import__(_mod_path)+for _part in _mod_path.split(".")[1:]:+ _mod = getattr(_mod, _part)+_result = getattr(_mod, _fn_name)(event, LambdaContext())+if _result is not None:+ print(json.dumps(_result))+"""+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _resolve_name(name_or_arn: str) -> str:+ """Extract plain function name from a name, partial ARN, or full ARN."""+ if not name_or_arn:+ return ""+ if name_or_arn.startswith("arn:"):+ segs = name_or_arn.split(":")+ return segs[6] if len(segs) >= 7 else name_or_arn+ if ":" in name_or_arn:+ return name_or_arn.split(":")[0]+ return name_or_arn+++def _resolve_name_and_qualifier(name_or_arn: str) -> tuple[str, str | None]:+ """Extract (function_name, qualifier) from a name, partial ARN, or full ARN.++ Handles:+ my-function -> ("my-function", None)+ my-function:v1 -> ("my-function", "v1")+ arn:...:function:my-func -> ("my-func", None)+ arn:...:function:my-func:3 -> ("my-func", "3")+ """+ if not name_or_arn:+ return "", None+ if name_or_arn.startswith("arn:"):+ segs = name_or_arn.split(":")+ name = segs[6] if len(segs) >= 7 else name_or_arn+ qualifier = segs[7] if len(segs) >= 8 and segs[7] else None+ return name, qualifier+ if ":" in name_or_arn:+ name, qualifier = name_or_arn.split(":", 1)+ return name, qualifier or None+ return name_or_arn, None+++def _func_arn(name: str) -> str:+ return f"arn:aws:lambda:{REGION}:{ACCOUNT_ID}:function:{name}"+++def _layer_arn(name: str) -> str:+ return f"arn:aws:lambda:{REGION}:{ACCOUNT_ID}:layer:{name}"+++def _now_iso() -> str:+ return time.strftime("%Y-%m-%dT%H:%M:%S.000+0000")+++def _build_config(name: str, data: dict, code_zip: bytes | None = None) -> dict:+ code_size = len(code_zip) if code_zip else 0+ code_sha = base64.b64encode(hashlib.sha256(code_zip).digest()).decode() if code_zip else ""++ layers_cfg = []+ for layer in data.get("Layers", []):+ if isinstance(layer, str):+ layers_cfg.append({"Arn": layer, "CodeSize": 0})+ elif isinstance(layer, dict):+ layers_cfg.append(layer)++ env = data.get("Environment")+ if env is None:+ env = {"Variables": {}}+ elif "Variables" not in env:+ env["Variables"] = {}++ return {+ "FunctionName": name,+ "FunctionArn": _func_arn(name),+ "Runtime": data.get("Runtime", "python3.9"),+ "Role": data.get("Role", f"arn:aws:iam::{ACCOUNT_ID}:role/lambda-role"),+ "Handler": data.get("Handler", "index.handler"),+ "CodeSize": code_size,+ "CodeSha256": code_sha,+ "Description": data.get("Description", ""),+ "Timeout": data.get("Timeout", 3),+ "MemorySize": data.get("MemorySize", 128),+ "LastModified": _now_iso(),+ "Version": "$LATEST",+ "State": "Active",+ "StateReason": "",+ "StateReasonCode": "",+ "LastUpdateStatus": "Successful",+ "LastUpdateStatusReason": "",+ "LastUpdateStatusReasonCode": "",+ "PackageType": data.get("PackageType", "Zip"),+ "Architectures": data.get("Architectures", ["x86_64"]),+ "Environment": env,+ "Layers": layers_cfg,+ "TracingConfig": data.get("TracingConfig", {"Mode": "PassThrough"}),+ "VpcConfig": data.get("VpcConfig", {+ "SubnetIds": [],+ "SecurityGroupIds": [],+ "VpcId": "",+ }),+ "DeadLetterConfig": data.get("DeadLetterConfig", {"TargetArn": ""}),+ "KMSKeyArn": data.get("KMSKeyArn", ""),+ "RevisionId": new_uuid(),+ "EphemeralStorage": data.get("EphemeralStorage", {"Size": 512}),+ "SnapStart": {"ApplyOn": "None", "OptimizationStatus": "Off"},+ "LoggingConfig": data.get("LoggingConfig", {+ "LogFormat": "Text",+ "LogGroup": f"/aws/lambda/{name}",+ }),+ "RuntimeVersionConfig": {+ "RuntimeVersionArn": "",+ },+ }+++def _qp_first(query_params: dict, key: str, default: str = "") -> str:+ """Return the first value for *key* from raw query_params (list or str)."""+ val = query_params.get(key, default)+ if isinstance(val, list):+ return val[0] if val else default+ return val+++def _get_func_record_for_qualifier(name: str, qualifier: str | None) -> tuple[dict | None, dict | None]:+ """Return (func_record, effective_config) for a given name + qualifier.++ For $LATEST or None, returns the primary record/config.+ For a version number, returns the versioned snapshot.+ For an alias, resolves to the alias target version.+ """+ func = _functions.get(name)+ if func is None:+ return None, None++ if qualifier is None or qualifier == "$LATEST":+ return func, func["config"]++ if qualifier in func.get("aliases", {}):+ target_ver = func["aliases"][qualifier].get("FunctionVersion", "$LATEST")+ if target_ver == "$LATEST":+ return func, func["config"]+ ver = func["versions"].get(target_ver)+ if ver:+ return ver, ver["config"]+ return func, func["config"]++ ver = func["versions"].get(qualifier)+ if ver:+ return ver, ver["config"]++ return func, func["config"]+++# ---------------------------------------------------------------------------+# Request router+# ----------------------------------------------------------------------------async def handle_request(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:+async def handle_request(method: str, path: str, headers: dict,+ body: bytes, query_params: dict) -> tuple:"""Route Lambda REST API requests."""- # Parse path: /2015-03-31/functions[/name[/invocations|/code|/configuration]]+ path = unquote(path)parts = path.rstrip("/").split("/")- # parts: ['', '2015-03-31', 'functions', ...]-- if len(parts) < 3:- return error_response_json("InvalidRequest", "Invalid path", 400)try:data = json.loads(body) if body else {}except json.JSONDecodeError:data = {}- # POST /2015-03-31/functions — CreateFunction- if method == "POST" and len(parts) == 3 and parts[2] == "functions":- return _create_function(data)-- # GET /2015-03-31/functions — ListFunctions- if method == "GET" and len(parts) == 3 and parts[2] == "functions":- return _list_functions()-- # Event Source Mappings: /2015-03-31/event-source-mappings+ # --- Event Source Mappings: /2015-03-31/event-source-mappings[/{uuid}] ---if len(parts) >= 3 and parts[2] == "event-source-mappings":esm_id = parts[3] if len(parts) > 3 else Noneif method == "POST" and not esm_id:return _create_esm(data)if method == "GET" and not esm_id:- return _list_esms(data)+ return _list_esms(query_params)if method == "GET" and esm_id:return _get_esm(esm_id)if method == "PUT" and esm_id:@@ -68,98 +315,1398 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, queif method == "DELETE" and esm_id:return _delete_esm(esm_id)- func_name = parts[3] if len(parts) > 3 else None- if not func_name:- return error_response_json("InvalidRequest", "Missing function name", 400)+ # --- Tags: /2015-03-31/tags/{arn+} ---+ if len(parts) >= 3 and parts[2] == "tags":+ resource_arn = "/".join(parts[3:]) if len(parts) > 3 else ""+ if method == "GET":+ return _list_tags(resource_arn)+ if method == "POST":+ return _tag_resource(resource_arn, data)+ if method == "DELETE":+ return _untag_resource(resource_arn, query_params)++ # --- Layers: /2015-03-31/layers[/{name}[/versions[/{num}]]] ---+ if len(parts) >= 3 and parts[2] == "layers":+ if len(parts) == 3 and method == "GET":+ return _list_layers(query_params)+ layer_name = parts[3] if len(parts) > 3 else None+ if layer_name and len(parts) >= 5 and parts[4] == "versions":+ ver_str = parts[5] if len(parts) > 5 else None+ ver_num = int(ver_str) if ver_str and ver_str.isdigit() else None+ if method == "POST" and ver_num is None:+ return _publish_layer_version(layer_name, data)+ if method == "GET" and ver_num is None:+ return _list_layer_versions(layer_name, query_params)+ if method == "GET" and ver_num is not None:+ return _get_layer_version(layer_name, ver_num)+ if method == "DELETE" and ver_num is not None:+ return _delete_layer_version(layer_name, ver_num)++ # --- Event Invoke Config: /2019-09-25/functions/{name}/event-invoke-config ---+ if "event-invoke-config" in path:+ m = re.search(r"/functions/([^/]+)/event-invoke-config", path)+ fname = _resolve_name(m.group(1)) if m else ""+ if method == "GET":+ return _get_event_invoke_config(fname)+ if method == "PUT":+ return _put_event_invoke_config(fname, data)+ if method == "DELETE":+ return _delete_event_invoke_config(fname)++ # --- Provisioned Concurrency: /2019-09-30/functions/{name}/provisioned-concurrency ---+ if "provisioned-concurrency" in path:+ m = re.search(r"/functions/([^/]+)/provisioned-concurrency", path)+ fname = _resolve_name(m.group(1)) if m else ""+ qualifier = _qp_first(query_params, "Qualifier")+ if method == "GET":+ return _get_provisioned_concurrency(fname, qualifier)+ if method == "PUT":+ return _put_provisioned_concurrency(fname, qualifier, data)+ if method == "DELETE":+ return _delete_provisioned_concurrency(fname, qualifier)++ # --- Code Signing Config (stub) ---+ if "code-signing-config" in path:+ m = re.search(r"/functions/([^/]+)/code-signing-config", path)+ fname = _resolve_name(m.group(1)) if m else ""+ return json_response({"CodeSigningConfigArn": "", "FunctionName": fname})++ # --- Function URL Config ---+ if "/urls" in path and "/functions/" in path:+ m = re.search(r"/functions/([^/]+)/urls", path)+ fname = _resolve_name(m.group(1)) if m else ""+ if method == "GET":+ return _list_function_url_configs(fname, query_params)+ if "/url" in path and "/functions/" in path:+ m = re.search(r"/functions/([^/]+)/url", path)+ fname = _resolve_name(m.group(1)) if m else ""+ qualifier = _qp_first(query_params, "Qualifier") or None+ if method == "POST":+ return _create_function_url_config(fname, data, qualifier)+ if method == "GET":+ return _get_function_url_config(fname, qualifier)+ if method == "PUT":+ return _update_function_url_config(fname, data, qualifier)+ if method == "DELETE":+ return _delete_function_url_config(fname, qualifier)++ # --- Functions: /...date.../functions[/{name}[/{sub}[/{sub2}]]] ---+ if len(parts) >= 3 and parts[2] == "functions":+ if method == "POST" and len(parts) == 3:+ return _create_function(data)++ if method == "GET" and len(parts) == 3:+ return _list_functions(query_params)++ raw_name = parts[3] if len(parts) > 3 else None+ if not raw_name:+ return error_response_json("InvalidRequest", "Missing function name", 400)++ func_name, path_qualifier = _resolve_name_and_qualifier(raw_name)+ sub = parts[4] if len(parts) > 4 else None+ sub2 = parts[5] if len(parts) > 5 else None++ # Invoke+ if method == "POST" and sub == "invocations":+ return _invoke(func_name, data, headers, path_qualifier)++ # PublishVersion+ if method == "POST" and sub == "versions":+ return _publish_version(func_name, data)++ # ListVersionsByFunction: GET .../functions/{name}/versions+ if method == "GET" and sub == "versions" and sub2 is None:+ return _list_versions(func_name, query_params)++ # --- Aliases ---+ if sub == "aliases":+ alias_name = sub2+ if method == "POST" and not alias_name:+ return _create_alias(func_name, data)+ if method == "GET" and not alias_name:+ return _list_aliases(func_name, query_params)+ if method == "GET" and alias_name:+ return _get_alias(func_name, alias_name)+ if method == "PUT" and alias_name:+ return _update_alias(func_name, alias_name, data)+ if method == "DELETE" and alias_name:+ return _delete_alias(func_name, alias_name)++ # --- Policy / Permissions ---+ if sub == "policy":+ sid = sub2+ if method == "GET" and not sid:+ return _get_policy(func_name, query_params)+ if method == "POST" and not sid:+ return _add_permission(func_name, data, query_params)+ if method == "DELETE" and sid:+ return _remove_permission(func_name, sid, query_params)++ # --- Concurrency ---+ if sub == "concurrency":+ if method == "GET":+ return _get_function_concurrency(func_name)+ if method == "PUT":+ return _put_function_concurrency(func_name, data)+ if method == "DELETE":+ return _delete_function_concurrency(func_name)++ # GetFunction+ if method == "GET" and not sub:+ qualifier = path_qualifier or _qp_first(query_params, "Qualifier") or None+ return _get_function(func_name, qualifier)++ # GetFunctionConfiguration+ if method == "GET" and sub == "configuration":+ qualifier = path_qualifier or _qp_first(query_params, "Qualifier") or None+ return _get_function_config(func_name, qualifier)++ # DeleteFunction+ if method == "DELETE" and not sub:+ return _delete_function(func_name, query_params)++ # UpdateFunctionCode+ if method == "PUT" and sub == "code":+ return _update_code(func_name, data)++ # UpdateFunctionConfiguration+ if method == "PUT" and sub == "configuration":+ return _update_config(func_name, data)++ if method == "GET":+ return json_response({})++ if method == "GET":+ return json_response({})- # POST /2015-03-31/functions/{name}/invocations — Invoke- if method == "POST" and len(parts) >= 5 and parts[4] == "invocations":- return _invoke(func_name, data, headers)+ return error_response_json("InvalidRequest", f"Unhandled Lambda path: {path}", 400)- # GET /2015-03-31/functions/{name} — GetFunction- if method == "GET" and len(parts) == 4:- return _get_function(func_name)- # GET /2015-03-31/functions/{name}/configuration- if method == "GET" and len(parts) >= 5 and parts[4] == "configuration":- return _get_function_config(func_name)+# ---------------------------------------------------------------------------+# Function CRUD+# ---------------------------------------------------------------------------- # DELETE /2015-03-31/functions/{name}- if method == "DELETE" and len(parts) == 4:- return _delete_function(func_name)+def _create_function(data: dict):+ name = data.get("FunctionName")+ if not name:+ return error_response_json(+ "InvalidParameterValueException", "FunctionName is required", 400,+ )+ if name in _functions:+ return error_response_json(+ "ResourceConflictException",+ f"Function already exist: {name}", 409,+ )- # PUT /2015-03-31/functions/{name}/code- if method == "PUT" and len(parts) >= 5 and parts[4] == "code":- return _update_code(func_name, data)+ code_zip = None+ code_data = data.get("Code", {})+ if "ZipFile" in code_data:+ code_zip = base64.b64decode(code_data["ZipFile"])- # PUT /2015-03-31/functions/{name}/configuration- if method == "PUT" and len(parts) >= 5 and parts[4] == "configuration":- return _update_config(func_name, data)+ config = _build_config(name, data, code_zip)++ _functions[name] = {+ "config": config,+ "code_zip": code_zip,+ "versions": {},+ "next_version": 1,+ "tags": data.get("Tags", {}),+ "policy": {"Version": "2012-10-17", "Id": "default", "Statement": []},+ "event_invoke_config": None,+ "aliases": {},+ "concurrency": None,+ "provisioned_concurrency": {},+ }- return error_response_json("InvalidRequest", f"Unhandled Lambda path: {path}", 400)+ return json_response(config, 201)+++def _get_function(name: str, qualifier: str | None = None):+ if name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(name)}", 404,+ )+ func = _functions[name]+ _, effective_config = _get_func_record_for_qualifier(name, qualifier)+ if effective_config is None:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(name)}", 404,+ )++ result: dict = {+ "Configuration": effective_config,+ "Code": {"RepositoryType": "S3", "Location": ""},+ "Tags": func.get("tags", {}),+ }+ if func.get("concurrency") is not None:+ result["Concurrency"] = {+ "ReservedConcurrentExecutions": func["concurrency"],+ }+ return json_response(result)+++def _get_function_config(name: str, qualifier: str | None = None):+ if name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(name)}", 404,+ )+ _, effective_config = _get_func_record_for_qualifier(name, qualifier)+ if effective_config is None:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(name)}", 404,+ )+ return json_response(effective_config)+++def _list_functions(query_params: dict):+ all_names = sorted(_functions.keys())+ marker = _qp_first(query_params, "Marker")+ max_items = int(_qp_first(query_params, "MaxItems", "50"))++ start = 0+ if marker:+ for i, n in enumerate(all_names):+ if n == marker:+ start = i + 1+ break++ page = all_names[start:start + max_items]+ configs = [_functions[n]["config"] for n in page]+ result: dict = {"Functions": configs}+ if start + max_items < len(all_names):+ result["NextMarker"] = page[-1] if page else ""++ return json_response(result)+++def _delete_function(name: str, query_params: dict):+ qualifier = _qp_first(query_params, "Qualifier")+ if name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(name)}", 404,+ )+ if qualifier and qualifier != "$LATEST":+ _functions[name]["versions"].pop(qualifier, None)+ else:+ del _functions[name]+ return 204, {}, b""+++def _update_code(name: str, data: dict):+ if name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(name)}", 404,+ )+ func = _functions[name]+ if "ZipFile" in data:+ code_zip = base64.b64decode(data["ZipFile"])+ func["code_zip"] = code_zip+ func["config"]["CodeSize"] = len(code_zip)+ func["config"]["CodeSha256"] = base64.b64encode(+ hashlib.sha256(code_zip).digest(),+ ).decode()+ func["config"]["LastModified"] = _now_iso()+ func["config"]["LastUpdateStatus"] = "Successful"+ func["config"]["RevisionId"] = new_uuid()+ return json_response(func["config"])+++def _update_config(name: str, data: dict):+ if name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(name)}", 404,+ )+ config = _functions[name]["config"]+ for key in ("Runtime", "Handler", "Description", "Timeout", "MemorySize",+ "Role", "Environment", "Layers", "TracingConfig",+ "DeadLetterConfig", "KMSKeyArn", "EphemeralStorage",+ "LoggingConfig", "VpcConfig", "Architectures",+ "FileSystemConfigs", "ImageConfig"):+ if key in data:+ config[key] = data[key]+ config["LastModified"] = _now_iso()+ config["LastUpdateStatus"] = "Successful"+ config["RevisionId"] = new_uuid()+ return json_response(config)+++# ---------------------------------------------------------------------------+# Invoke+# ---------------------------------------------------------------------------++def _invoke(name: str, event: dict, headers: dict,+ path_qualifier: str | None = None):+ if name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(name)}", 404,+ )++ func = _functions[name]+ invocation_type = (+ headers.get("x-amz-invocation-type")+ or headers.get("X-Amz-Invocation-Type")+ or "RequestResponse"+ )+ qualifier = path_qualifier or _qp_first(headers, "x-amz-qualifier") or None+ executed_version = "$LATEST"++ exec_record = func+ if qualifier and qualifier != "$LATEST":+ if qualifier in func.get("aliases", {}):+ target_ver = func["aliases"][qualifier].get("FunctionVersion", "$LATEST")+ executed_version = target_ver+ if target_ver != "$LATEST" and target_ver in func["versions"]:+ exec_record = func["versions"][target_ver]+ elif qualifier in func["versions"]:+ exec_record = func["versions"][qualifier]+ executed_version = qualifier+ else:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(name)}:{qualifier}",+ 404,+ )++ if invocation_type == "DryRun":+ return 204, {"X-Amz-Executed-Version": executed_version}, b""++ if invocation_type == "Event":+ threading.Thread(+ target=_execute_function, args=(exec_record, event), daemon=True,+ ).start()+ return 202, {"X-Amz-Executed-Version": executed_version}, b""++ # RequestResponse — synchronous execution+ result = _execute_function(exec_record, event)++ resp_headers: dict = {+ "Content-Type": "application/json",+ "X-Amz-Executed-Version": executed_version,+ }++ log_output = result.get("log", "")+ if log_output:+ resp_headers["X-Amz-Log-Result"] = base64.b64encode(+ log_output.encode("utf-8"),+ ).decode()++ if result.get("error"):+ resp_headers["X-Amz-Function-Error"] = "Unhandled"++ payload = result.get("body")+ if payload is None:+ return 200, resp_headers, b"null"+ if isinstance(payload, (str, bytes)):+ raw = payload.encode("utf-8") if isinstance(payload, str) else payload+ return 200, resp_headers, raw+ return 200, resp_headers, json.dumps(payload).encode("utf-8")+++# ---------------------------------------------------------------------------+# Runtime → Docker image mapping+# ---------------------------------------------------------------------------++_RUNTIME_IMAGE_MAP: dict[str, str] = {+ "python3.8": "python:3.8-slim",+ "python3.9": "python:3.9-slim",+ "python3.10": "python:3.10-slim",+ "python3.11": "python:3.11-slim",+ "python3.12": "python:3.12-slim",+ "python3.13": "python:3.13-slim",+ "nodejs14.x": "node:14-slim",+ "nodejs16.x": "node:16-slim",+ "nodejs18.x": "node:18-slim",+ "nodejs20.x": "node:20-slim",+}+++def _docker_image_for_runtime(runtime: str) -> str | None:+ if runtime in _RUNTIME_IMAGE_MAP:+ return _RUNTIME_IMAGE_MAP[runtime]+ if runtime.startswith("python"):+ ver = runtime.replace("python", "")+ return f"python:{ver}-slim"+ if runtime.startswith("nodejs"):+ ver = runtime.replace("nodejs", "").rstrip(".x")+ return f"node:{ver}-slim"+ return None+++# ---------------------------------------------------------------------------+# Function execution – Docker mode+# ---------------------------------------------------------------------------++def _execute_function_docker(func: dict, event: dict) -> dict:+ """Execute a Lambda function inside a Docker container.++ Mirrors the subprocess executor's interface: returns+ ``{"body": ..., "log": ..., "error": ...}``.+ """+ if not _docker_available:+ logger.warning("docker SDK unavailable – falling back to local subprocess executor")+ return _execute_function_local(func, event)++ config = func.get("config") or func+ code_zip = func.get("code_zip")+ if not code_zip:+ return {"body": {"statusCode": 200, "body": "Mock response - no code deployed"}}++ handler = config["Handler"]+ runtime = config["Runtime"]+ timeout = config.get("Timeout", 3)+ env_vars = config.get("Environment", {}).get("Variables", {})++ image = _docker_image_for_runtime(runtime)+ if image is None:+ return {+ "body": {+ "statusCode": 200,+ "body": f"Mock response - {runtime} not supported for docker execution",+ },+ }++ if not runtime.startswith("python"):+ return {+ "body": {+ "statusCode": 200,+ "body": f"Mock response - {runtime} docker wrapper only supports Python runtimes",+ },+ }++ try:+ client = docker_lib.from_env()+ except Exception as exc:+ logger.warning("Cannot connect to Docker daemon (%s) – falling back to local subprocess", exc)+ return _execute_function_local(func, event)++ container = None+ try:+ with tempfile.TemporaryDirectory() as tmpdir:+ # Extract code zip+ zip_path = os.path.join(tmpdir, "code.zip")+ with open(zip_path, "wb") as f:+ f.write(code_zip)+ code_dir = os.path.join(tmpdir, "code")+ os.makedirs(code_dir)+ with zipfile.ZipFile(zip_path) as zf:+ zf.extractall(code_dir)++ # Write the docker wrapper into the code dir+ wrapper_path = os.path.join(code_dir, "_wrapper.py")+ with open(wrapper_path, "w") as wf:+ wf.write(_DOCKER_WRAPPER_SCRIPT)++ # Extract layers+ layers_dirs: list[str] = []+ for layer_ref in config.get("Layers", []):+ layer_arn_str = layer_ref if isinstance(layer_ref, str) else layer_ref.get("Arn", "")+ layer_zip = _resolve_layer_zip(layer_arn_str)+ if layer_zip:+ layer_dir = os.path.join(tmpdir, f"layer_{len(layers_dirs)}")+ os.makedirs(layer_dir)+ lzip_path = os.path.join(tmpdir, f"layer_{len(layers_dirs)}.zip")+ with open(lzip_path, "wb") as lf:+ lf.write(layer_zip)+ with zipfile.ZipFile(lzip_path) as lzf:+ lzf.extractall(layer_dir)+ layers_dirs.append(layer_dir)++ module_name, func_name = handler.rsplit(".", 1)++ # Build volume mounts+ volumes: dict = {}+ if LAMBDA_DOCKER_VOLUME_MOUNT:+ volumes[LAMBDA_DOCKER_VOLUME_MOUNT] = {"bind": "/var/task", "mode": "ro"}+ else:+ volumes[code_dir] = {"bind": "/var/task", "mode": "ro"}++ container_layer_dirs: list[str] = []+ for idx, ld in enumerate(layers_dirs):+ container_path = f"/opt/layer_{idx}"+ volumes[ld] = {"bind": container_path, "mode": "ro"}+ container_layer_dirs.append(container_path)++ # Build environment+ container_env: dict[str, str] = {+ "AWS_DEFAULT_REGION": REGION,+ "AWS_REGION": REGION,+ "AWS_ACCESS_KEY_ID": os.environ.get("AWS_ACCESS_KEY_ID", "test"),+ "AWS_SECRET_ACCESS_KEY": os.environ.get("AWS_SECRET_ACCESS_KEY", "test"),+ "AWS_SESSION_TOKEN": os.environ.get("AWS_SESSION_TOKEN", ""),+ "AWS_LAMBDA_FUNCTION_NAME": config["FunctionName"],+ "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": str(config["MemorySize"]),+ "AWS_LAMBDA_FUNCTION_VERSION": config.get("Version", "$LATEST"),+ "AWS_LAMBDA_LOG_STREAM_NAME": new_uuid(),+ "_LAMBDA_HANDLER_MODULE": module_name,+ "_LAMBDA_HANDLER_FUNC": func_name,+ "_LAMBDA_FUNCTION_ARN": config["FunctionArn"],+ "_LAMBDA_TIMEOUT": str(timeout),+ "_LAMBDA_LAYERS_DIRS": ":".join(container_layer_dirs),+ }+ endpoint = os.environ.get("AWS_ENDPOINT_URL", "")+ if endpoint:+ container_env["AWS_ENDPOINT_URL"] = endpoint+ container_env.update(env_vars)++ event_file = os.path.join(code_dir, "_event.json")+ with open(event_file, "w") as ef:+ ef.write(json.dumps(event))++ container = client.containers.run(+ image,+ command=["sh", "-c", "python3 /var/task/_wrapper.py < /var/task/_event.json"],+ environment=container_env,+ volumes=volumes,+ network_mode="host",+ detach=True,+ stdin_open=False,+ )++ result = container.wait(timeout=timeout)+ exit_code = result.get("StatusCode", -1)+ stdout = container.logs(stdout=True, stderr=False).decode("utf-8", errors="replace").strip()+ stderr = container.logs(stdout=False, stderr=True).decode("utf-8", errors="replace").strip()++ if exit_code == 0:+ if not stdout:+ return {"body": None, "log": stderr}+ try:+ return {"body": json.loads(stdout), "log": stderr}+ except json.JSONDecodeError:+ return {"body": stdout, "log": stderr}+ else:+ return {+ "body": {+ "errorMessage": stderr or "Unknown error",+ "errorType": "Runtime.HandlerError",+ },+ "error": True,+ "log": stderr,+ }++ except Exception as exc:+ if "timed out" in str(exc).lower() or "read timed out" in str(exc).lower():+ return {+ "body": {+ "errorMessage": f"Task timed out after {timeout}.00 seconds",+ "errorType": "Runtime.ExitError",+ },+ "error": True,+ "log": "",+ }+ logger.error("Lambda docker execution error: %s", exc)+ return {+ "body": {"errorMessage": str(exc), "errorType": type(exc).__name__},+ "error": True,+ "log": "",+ }+ finally:+ if container is not None:+ try:+ container.remove(force=True)+ except Exception:+ pass+++# ---------------------------------------------------------------------------+# Function execution (subprocess, stdin-piped, no string interpolation)+# ---------------------------------------------------------------------------++def _execute_function(func: dict, event: dict) -> dict:+ """Dispatch to Docker or local subprocess executor."""+ if LAMBDA_EXECUTOR == "docker":+ return _execute_function_docker(func, event)+ return _execute_function_local(func, event)+++def _execute_function_local(func: dict, event: dict) -> dict:+ """Execute a Python Lambda function in a subprocess.++ The event is serialised to JSON and piped through stdin. Handler module,+ function name, and all configuration are passed via environment variables so+ there is zero string interpolation of user data into code.+ """+ config = func.get("config") or func+ code_zip = func.get("code_zip")+ if not code_zip:+ return {"body": {"statusCode": 200, "body": "Mock response - no code deployed"}}++ handler = config["Handler"]+ runtime = config["Runtime"]+ timeout = config.get("Timeout", 3)+ env_vars = config.get("Environment", {}).get("Variables", {})++ if not runtime.startswith("python"):+ return {+ "body": {+ "statusCode": 200,+ "body": f"Mock response - {runtime} not supported for local execution",+ },+ }++ try:+ with tempfile.TemporaryDirectory() as tmpdir:+ zip_path = os.path.join(tmpdir, "code.zip")+ with open(zip_path, "wb") as f:+ f.write(code_zip)+ code_dir = os.path.join(tmpdir, "code")+ os.makedirs(code_dir)+ with zipfile.ZipFile(zip_path) as zf:+ zf.extractall(code_dir)++ layers_dirs: list[str] = []+ for layer_ref in config.get("Layers", []):+ layer_arn_str = layer_ref if isinstance(layer_ref, str) else layer_ref.get("Arn", "")+ layer_zip = _resolve_layer_zip(layer_arn_str)+ if layer_zip:+ layer_dir = os.path.join(tmpdir, f"layer_{len(layers_dirs)}")+ os.makedirs(layer_dir)+ lzip_path = os.path.join(tmpdir, f"layer_{len(layers_dirs)}.zip")+ with open(lzip_path, "wb") as lf:+ lf.write(layer_zip)+ with zipfile.ZipFile(lzip_path) as lzf:+ lzf.extractall(layer_dir)+ layers_dirs.append(layer_dir)++ module_name, func_name = handler.rsplit(".", 1)++ wrapper_path = os.path.join(tmpdir, "_wrapper.py")+ with open(wrapper_path, "w") as wf:+ wf.write(_WRAPPER_SCRIPT)++ env = dict(os.environ)+ env.update({+ "AWS_DEFAULT_REGION": REGION,+ "AWS_REGION": REGION,+ "AWS_ACCESS_KEY_ID": os.environ.get("AWS_ACCESS_KEY_ID", "test"),+ "AWS_SECRET_ACCESS_KEY": os.environ.get("AWS_SECRET_ACCESS_KEY", "test"),+ "AWS_SESSION_TOKEN": os.environ.get("AWS_SESSION_TOKEN", ""),+ "AWS_LAMBDA_FUNCTION_NAME": config["FunctionName"],+ "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": str(config["MemorySize"]),+ "AWS_LAMBDA_FUNCTION_VERSION": config.get("Version", "$LATEST"),+ "AWS_LAMBDA_LOG_STREAM_NAME": new_uuid(),+ "_LAMBDA_CODE_DIR": code_dir,+ "_LAMBDA_HANDLER_MODULE": module_name,+ "_LAMBDA_HANDLER_FUNC": func_name,+ "_LAMBDA_FUNCTION_ARN": config["FunctionArn"],+ "_LAMBDA_TIMEOUT": str(timeout),+ "_LAMBDA_LAYERS_DIRS": os.pathsep.join(layers_dirs),+ })+ endpoint = os.environ.get("AWS_ENDPOINT_URL", "")+ if endpoint:+ env["AWS_ENDPOINT_URL"] = endpoint+ env.update(env_vars)++ proc = subprocess.run(+ ["python3", wrapper_path],+ input=json.dumps(event),+ capture_output=True,+ text=True,+ timeout=timeout,+ env=env,+ )++ log_tail = proc.stderr.strip()++ if proc.returncode == 0:+ stdout = proc.stdout.strip()+ if not stdout:+ return {"body": None, "log": log_tail}+ try:+ return {"body": json.loads(stdout), "log": log_tail}+ except json.JSONDecodeError:+ return {"body": stdout, "log": log_tail}+ else:+ return {+ "body": {+ "errorMessage": log_tail or "Unknown error",+ "errorType": "Runtime.HandlerError",+ },+ "error": True,+ "log": log_tail,+ }++ except subprocess.TimeoutExpired:+ return {+ "body": {+ "errorMessage": f"Task timed out after {timeout}.00 seconds",+ "errorType": "Runtime.ExitError",+ },+ "error": True,+ "log": "",+ }+ except Exception as e:+ logger.error(f"Lambda execution error: {e}")+ return {+ "body": {"errorMessage": str(e), "errorType": type(e).__name__},+ "error": True,+ "log": "",+ }+++def _resolve_layer_zip(layer_arn_str: str) -> bytes | None:+ """Given a layer version ARN return the stored zip bytes, or None."""+ segs = layer_arn_str.split(":")+ if len(segs) < 8:+ return None+ layer_name = segs[6]+ try:+ version = int(segs[7])+ except (ValueError, IndexError):+ return None+ layer = _layers.get(layer_name)+ if not layer:+ return None+ for v in layer["versions"]:+ if v["Version"] == version:+ return v.get("_zip_data")+ return None+++# ---------------------------------------------------------------------------+# Versioning+# ---------------------------------------------------------------------------++def _publish_version(name: str, data: dict):+ if name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(name)}", 404,+ )+ func = _functions[name]+ ver_num = func["next_version"]+ func["next_version"] = ver_num + 1++ ver_config = copy.deepcopy(func["config"])+ ver_config["Version"] = str(ver_num)+ ver_config["FunctionArn"] = f"{_func_arn(name)}:{ver_num}"+ ver_config["RevisionId"] = new_uuid()+ if data.get("Description"):+ ver_config["Description"] = data["Description"]++ func["versions"][str(ver_num)] = {+ "config": ver_config,+ "code_zip": func.get("code_zip"),+ }+ return json_response(ver_config, 201)+++def _list_versions(name: str, query_params: dict):+ if name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(name)}", 404,+ )+ func = _functions[name]+ versions = [func["config"]]+ for vnum in sorted(func["versions"].keys(), key=int):+ versions.append(func["versions"][vnum]["config"])++ marker = _qp_first(query_params, "Marker")+ max_items = int(_qp_first(query_params, "MaxItems", "50"))+ start = 0+ if marker:+ for i, v in enumerate(versions):+ if v["Version"] == marker:+ start = i + 1+ break++ page = versions[start:start + max_items]+ result: dict = {"Versions": page}+ if start + max_items < len(versions):+ result["NextMarker"] = page[-1]["Version"] if page else ""+ return json_response(result)+++# ---------------------------------------------------------------------------+# Aliases+# ---------------------------------------------------------------------------++def _create_alias(func_name: str, data: dict):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ alias_name = data.get("Name", "")+ if not alias_name:+ return error_response_json(+ "InvalidParameterValueException", "Alias name is required", 400,+ )+ func = _functions[func_name]+ if alias_name in func["aliases"]:+ return error_response_json(+ "ResourceConflictException",+ f"Alias already exists: {alias_name}", 409,+ )++ alias: dict = {+ "AliasArn": f"{_func_arn(func_name)}:{alias_name}",+ "Name": alias_name,+ "FunctionVersion": data.get("FunctionVersion", "$LATEST"),+ "Description": data.get("Description", ""),+ "RevisionId": new_uuid(),+ }+ rc = data.get("RoutingConfig")+ if rc:+ alias["RoutingConfig"] = rc+ func["aliases"][alias_name] = alias+ return json_response(alias, 201)+++def _get_alias(func_name: str, alias_name: str):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ alias = _functions[func_name]["aliases"].get(alias_name)+ if not alias:+ return error_response_json(+ "ResourceNotFoundException",+ f"Alias not found: {_func_arn(func_name)}:{alias_name}", 404,+ )+ return json_response(alias)+++def _update_alias(func_name: str, alias_name: str, data: dict):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ alias = _functions[func_name]["aliases"].get(alias_name)+ if not alias:+ return error_response_json(+ "ResourceNotFoundException",+ f"Alias not found: {_func_arn(func_name)}:{alias_name}", 404,+ )+ for key in ("FunctionVersion", "Description", "RoutingConfig"):+ if key in data:+ alias[key] = data[key]+ alias["RevisionId"] = new_uuid()+ return json_response(alias)+++def _delete_alias(func_name: str, alias_name: str):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ if alias_name not in _functions[func_name]["aliases"]:+ return error_response_json(+ "ResourceNotFoundException",+ f"Alias not found: {_func_arn(func_name)}:{alias_name}", 404,+ )+ del _functions[func_name]["aliases"][alias_name]+ return 204, {}, b""+++def _list_aliases(func_name: str, query_params: dict):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ aliases = list(_functions[func_name]["aliases"].values())++ marker = _qp_first(query_params, "Marker")+ max_items = int(_qp_first(query_params, "MaxItems", "50"))+ start = 0+ if marker:+ for i, a in enumerate(aliases):+ if a["Name"] == marker:+ start = i + 1+ break+ page = aliases[start:start + max_items]+ result: dict = {"Aliases": page}+ if start + max_items < len(aliases):+ result["NextMarker"] = page[-1]["Name"] if page else ""+ return json_response(result)+++# ---------------------------------------------------------------------------+# Permissions / Policy (required by Terraform aws_lambda_permission)+# ---------------------------------------------------------------------------++def _add_permission(func_name: str, data: dict, query_params: dict | None = None):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ func = _functions[func_name]+ sid = data.get("StatementId", new_uuid())++ for stmt in func["policy"]["Statement"]:+ if stmt.get("Sid") == sid:+ return error_response_json(+ "ResourceConflictException",+ f"The statement id ({sid}) provided already exists. "+ "Please provide a new statement id, or remove the existing statement.",+ 409,+ )++ principal_raw = data.get("Principal", "")+ if "amazonaws.com" in principal_raw:+ principal = {"Service": principal_raw}+ elif principal_raw == "*":+ principal = "*"+ else:+ principal = {"AWS": principal_raw}++ qualifier = (query_params or {}).get("Qualifier") if query_params else None+ if isinstance(qualifier, list):+ qualifier = qualifier[0] if qualifier else None+ resource_arn = _func_arn(func_name)+ if qualifier:+ resource_arn = f"{resource_arn}:{qualifier}"++ statement: dict = {+ "Sid": sid,+ "Effect": "Allow",+ "Principal": principal,+ "Action": data.get("Action", "lambda:InvokeFunction"),+ "Resource": resource_arn,+ }+ condition: dict = {}+ if "SourceArn" in data:+ condition["ArnLike"] = {"AWS:SourceArn": data["SourceArn"]}+ if "SourceAccount" in data:+ condition["StringEquals"] = {"AWS:SourceAccount": data["SourceAccount"]}+ if "PrincipalOrgID" in data:+ condition.setdefault("StringEquals", {})["aws:PrincipalOrgID"] = data["PrincipalOrgID"]+ if "FunctionUrlAuthType" in data:+ condition.setdefault("StringEquals", {})["lambda:FunctionUrlAuthType"] = data["FunctionUrlAuthType"]+ if condition:+ statement["Condition"] = condition++ func["policy"]["Statement"].append(statement)+ return json_response({"Statement": json.dumps(statement)}, 201)+++def _remove_permission(func_name: str, sid: str, query_params: dict):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ func = _functions[func_name]+ before = len(func["policy"]["Statement"])+ func["policy"]["Statement"] = [+ s for s in func["policy"]["Statement"] if s.get("Sid") != sid+ ]+ if len(func["policy"]["Statement"]) == before:+ return error_response_json(+ "ResourceNotFoundException",+ "No policy is associated with the given resource.", 404,+ )+ return 204, {}, b""+++def _get_policy(func_name: str, query_params: dict | None = None):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ func = _functions[func_name]+ if not func["policy"]["Statement"]:+ return error_response_json(+ "ResourceNotFoundException",+ "The resource you requested does not exist.", 404,+ )+ return json_response({+ "Policy": json.dumps(func["policy"]),+ "RevisionId": func["config"]["RevisionId"],+ })-# ---- Event Source Mappings ----+# ---------------------------------------------------------------------------+# Tags+# ---------------------------------------------------------------------------++def _list_tags(resource_arn: str):+ func_name = _resolve_name(resource_arn)+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {resource_arn}", 404,+ )+ return json_response({"Tags": _functions[func_name].get("tags", {})})+++def _tag_resource(resource_arn: str, data: dict):+ func_name = _resolve_name(resource_arn)+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {resource_arn}", 404,+ )+ _functions[func_name].setdefault("tags", {}).update(data.get("Tags", {}))+ return 204, {}, b""+++def _untag_resource(resource_arn: str, query_params: dict):+ func_name = _resolve_name(resource_arn)+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {resource_arn}", 404,+ )+ raw = query_params.get("tagKeys", query_params.get("TagKeys", []))+ if isinstance(raw, list):+ tag_keys = raw+ elif isinstance(raw, str):+ tag_keys = [raw]+ else:+ tag_keys = []+ tags = _functions[func_name].setdefault("tags", {})+ for k in tag_keys:+ tags.pop(k.strip(), None)+ return 204, {}, b""+-def _create_esm(data):+# ---------------------------------------------------------------------------+# Layers+# ---------------------------------------------------------------------------++def _publish_layer_version(layer_name: str, data: dict):+ if layer_name not in _layers:+ _layers[layer_name] = {"versions": [], "next_version": 1}+ layer = _layers[layer_name]+ ver = layer["next_version"]+ layer["next_version"] = ver + 1++ zip_data = None+ content = data.get("Content", {})+ if "ZipFile" in content:+ zip_data = base64.b64decode(content["ZipFile"])++ ver_config: dict = {+ "LayerArn": _layer_arn(layer_name),+ "LayerVersionArn": f"{_layer_arn(layer_name)}:{ver}",+ "Version": ver,+ "Description": data.get("Description", ""),+ "CompatibleRuntimes": data.get("CompatibleRuntimes", []),+ "CompatibleArchitectures": data.get("CompatibleArchitectures", []),+ "LicenseInfo": data.get("LicenseInfo", ""),+ "CreatedDate": _now_iso(),+ "Content": {+ "Location": "",+ "CodeSha256": (+ base64.b64encode(hashlib.sha256(zip_data).digest()).decode()+ if zip_data else ""+ ),+ "CodeSize": len(zip_data) if zip_data else 0,+ },+ "_zip_data": zip_data,+ }+ layer["versions"].append(ver_config)+ out = {k: v for k, v in ver_config.items() if not k.startswith("_")}+ return json_response(out, 201)+++def _list_layer_versions(layer_name: str, query_params: dict):+ layer = _layers.get(layer_name)+ if not layer:+ return json_response({"LayerVersions": []})+ versions = [+ {k: v for k, v in vc.items() if not k.startswith("_")}+ for vc in layer["versions"]+ ]+ return json_response({"LayerVersions": versions})+++def _get_layer_version(layer_name: str, version: int):+ layer = _layers.get(layer_name)+ if not layer:+ return error_response_json(+ "ResourceNotFoundException", f"Layer {layer_name} not found", 404,+ )+ for vc in layer["versions"]:+ if vc["Version"] == version:+ out = {k: v for k, v in vc.items() if not k.startswith("_")}+ return json_response(out)+ return error_response_json(+ "ResourceNotFoundException",+ f"Layer version {version} not found for {layer_name}", 404,+ )+++def _delete_layer_version(layer_name: str, version: int):+ layer = _layers.get(layer_name)+ if not layer:+ return 204, {}, b""+ layer["versions"] = [vc for vc in layer["versions"] if vc["Version"] != version]+ return 204, {}, b""+++def _list_layers(query_params: dict):+ result = []+ for name, layer in _layers.items():+ if layer["versions"]:+ latest = layer["versions"][-1]+ result.append({+ "LayerName": name,+ "LayerArn": _layer_arn(name),+ "LatestMatchingVersion": {+ k: v for k, v in latest.items() if not k.startswith("_")+ },+ })+ return json_response({"Layers": result})+++# ---------------------------------------------------------------------------+# Event Invoke Config (stubs — enough for Terraform to not error)+# ---------------------------------------------------------------------------++def _get_event_invoke_config(func_name: str):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ eic = _functions[func_name].get("event_invoke_config")+ if not eic:+ return error_response_json(+ "ResourceNotFoundException",+ f"The function {func_name} doesn't have an EventInvokeConfig", 404,+ )+ return json_response(eic)+++def _put_event_invoke_config(func_name: str, data: dict):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ eic = {+ "FunctionArn": _func_arn(func_name),+ "MaximumRetryAttempts": data.get("MaximumRetryAttempts", 2),+ "MaximumEventAgeInSeconds": data.get("MaximumEventAgeInSeconds", 21600),+ "LastModified": time.time(),+ "DestinationConfig": data.get("DestinationConfig", {+ "OnSuccess": {},+ "OnFailure": {},+ }),+ }+ _functions[func_name]["event_invoke_config"] = eic+ return json_response(eic)+++def _delete_event_invoke_config(func_name: str):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ _functions[func_name]["event_invoke_config"] = None+ return 204, {}, b""+++# ---------------------------------------------------------------------------+# Concurrency (reserved)+# ---------------------------------------------------------------------------++def _get_function_concurrency(func_name: str):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ conc = _functions[func_name].get("concurrency")+ if conc is None:+ return json_response({"ReservedConcurrentExecutions": 0})+ return json_response({"ReservedConcurrentExecutions": conc})+++def _put_function_concurrency(func_name: str, data: dict):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ value = data.get("ReservedConcurrentExecutions", 0)+ _functions[func_name]["concurrency"] = value+ return json_response({"ReservedConcurrentExecutions": value})+++def _delete_function_concurrency(func_name: str):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ _functions[func_name]["concurrency"] = None+ return 204, {}, b""+++# ---------------------------------------------------------------------------+# Provisioned Concurrency (stubs)+# ---------------------------------------------------------------------------++def _get_provisioned_concurrency(func_name: str, qualifier: str):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ key = qualifier or "$LATEST"+ pc = _functions[func_name].get("provisioned_concurrency", {}).get(key)+ if not pc:+ return error_response_json(+ "ProvisionedConcurrencyConfigNotFoundException",+ f"No Provisioned Concurrency Config found for function: {_func_arn(func_name)}", 404,+ )+ return json_response(pc)+++def _put_provisioned_concurrency(func_name: str, qualifier: str, data: dict):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ key = qualifier or "$LATEST"+ requested = data.get("ProvisionedConcurrentExecutions", 0)+ pc = {+ "RequestedProvisionedConcurrentExecutions": requested,+ "AvailableProvisionedConcurrentExecutions": requested,+ "AllocatedProvisionedConcurrentExecutions": requested,+ "Status": "READY",+ "LastModified": _now_iso(),+ }+ _functions[func_name].setdefault("provisioned_concurrency", {})[key] = pc+ return json_response(pc, 202)+++def _delete_provisioned_concurrency(func_name: str, qualifier: str):+ if func_name not in _functions:+ return error_response_json(+ "ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404,+ )+ key = qualifier or "$LATEST"+ _functions[func_name].get("provisioned_concurrency", {}).pop(key, None)+ return 204, {}, b""+++# ---------------------------------------------------------------------------+# Event Source Mappings+# ---------------------------------------------------------------------------++def _create_esm(data: dict):esm_id = new_uuid()- func_name = data.get("FunctionName", "")- # Resolve to just the name if ARN given- if ":" in func_name:- func_name = func_name.split(":")[-1]+ func_name = _resolve_name(data.get("FunctionName", ""))esm = {"UUID": esm_id,"EventSourceArn": data.get("EventSourceArn", ""),- "FunctionArn": f"arn:aws:lambda:{REGION}:{ACCOUNT_ID}:function:{func_name}",+ "FunctionArn": _func_arn(func_name),"FunctionName": func_name,"State": "Enabled",+ "StateTransitionReason": "USER_INITIATED","BatchSize": data.get("BatchSize", 10),"MaximumBatchingWindowInSeconds": data.get("MaximumBatchingWindowInSeconds", 0),"LastModified": time.time(),"LastProcessingResult": "No records processed","StartingPosition": data.get("StartingPosition", "LATEST"),"Enabled": True,+ "FunctionResponseTypes": data.get("FunctionResponseTypes", []),}_esms[esm_id] = esm_ensure_poller()- return json_response(esm)+ return json_response(esm, 202)-def _get_esm(esm_id):+def _get_esm(esm_id: str):esm = _esms.get(esm_id)if not esm:- return error_response_json("ResourceNotFoundException", f"ESM {esm_id} not found", 404)+ return error_response_json(+ "ResourceNotFoundException",+ f"The resource you requested does not exist. (Service: Lambda, "+ f"Status Code: 404, Request ID: {new_uuid()})",+ 404,+ )return json_response(esm)-def _list_esms(data):- func = data.get("FunctionName", "")- if ":" in func:- func = func.split(":")[-1]- result = [e for e in _esms.values() if not func or e["FunctionName"] == func]- return json_response({"EventSourceMappings": result})+def _list_esms(query_params: dict):+ func = _resolve_name(_qp_first(query_params, "FunctionName"))+ source_arn = _qp_first(query_params, "EventSourceArn")+ marker = _qp_first(query_params, "Marker")+ max_items = int(_qp_first(query_params, "MaxItems", "100"))+ result = list(_esms.values())+ if func:+ result = [e for e in result if e["FunctionName"] == func]+ if source_arn:+ result = [e for e in result if e["EventSourceArn"] == source_arn]-def _update_esm(esm_id, data):+ start = 0+ if marker:+ for i, e in enumerate(result):+ if e["UUID"] == marker:+ start = i + 1+ break++ page = result[start:start + max_items]+ resp: dict = {"EventSourceMappings": page}+ if start + max_items < len(result):+ resp["NextMarker"] = page[-1]["UUID"] if page else ""+ return json_response(resp)+++def _update_esm(esm_id: str, data: dict):esm = _esms.get(esm_id)if not esm:- return error_response_json("ResourceNotFoundException", f"ESM {esm_id} not found", 404)- if "BatchSize" in data:- esm["BatchSize"] = data["BatchSize"]+ return error_response_json(+ "ResourceNotFoundException",+ f"Event source mapping not found: {esm_id}", 404,+ )+ for key in ("BatchSize", "MaximumBatchingWindowInSeconds",+ "FunctionResponseTypes", "MaximumRetryAttempts",+ "MaximumRecordAgeInSeconds", "BisectBatchOnFunctionError",+ "ParallelizationFactor", "DestinationConfig",+ "FilterCriteria"):+ if key in data:+ esm[key] = data[key]if "Enabled" in data:esm["Enabled"] = data["Enabled"]esm["State"] = "Enabled" if data["Enabled"] else "Disabled"+ if "FunctionName" in data:+ new_name = _resolve_name(data["FunctionName"])+ esm["FunctionName"] = new_name+ esm["FunctionArn"] = _func_arn(new_name)esm["LastModified"] = time.time()return json_response(esm)-def _delete_esm(esm_id):+def _delete_esm(esm_id: str):esm = _esms.pop(esm_id, None)if not esm:- return error_response_json("ResourceNotFoundException", f"ESM {esm_id} not found", 404)- return json_response(esm)+ return error_response_json(+ "ResourceNotFoundException",+ f"Event source mapping not found: {esm_id}", 404,+ )+ esm["State"] = "Deleting"+ return json_response(esm, 202)++# ---------------------------------------------------------------------------+# SQS ESM Poller (kept as-is — works well)+# ---------------------------------------------------------------------------def _ensure_poller():global _poller_started@@ -195,7 +1742,6 @@ def _poll_once():if func_name not in _functions:continue- # Resolve queue URL from ARN: arn:aws:sqs:region:account:queue-namequeue_name = source_arn.split(":")[-1]queue_url = _sqs._queue_url(queue_name)queue = _sqs._queues.get(queue_url)@@ -205,7 +1751,6 @@ def _poll_once():batch_size = esm.get("BatchSize", 10)now = time.time()- # Grab up to batch_size visible messagesbatch = []for msg in list(queue["messages"]):if len(batch) >= batch_size:@@ -216,12 +1761,10 @@ def _poll_once():if not batch:continue- # Mark as in-flightfor msg in batch:msg["receipt_handle"] = new_uuid()- msg["visible_at"] = now + 30 # visibility timeout+ msg["visible_at"] = now + 30- # Build SQS event payloadrecords = []for msg in batch:records.append({@@ -245,187 +1788,95 @@ def _poll_once():result = _execute_function(_functions[func_name], event)if result.get("error"):- # On failure, make messages visible again immediatelyfor msg in batch:msg["receipt_handle"] = Nonemsg["visible_at"] = nowesm["LastProcessingResult"] = "FAILED"- logger.warning(f"ESM: Lambda {func_name} failed processing batch from {queue_name}")+ logger.warning(+ f"ESM: Lambda {func_name} failed processing batch from {queue_name}",+ )else:- # Success — delete processed messagesreceipt_handles = {msg["receipt_handle"] for msg in batch}- queue["messages"] = [m for m in queue["messages"] if m.get("receipt_handle") not in receipt_handles]- esm["LastProcessingResult"] = f"OK — {len(batch)} records"- logger.info(f"ESM: Lambda {func_name} processed {len(batch)} messages from {queue_name}")---def _create_function(data):- name = data.get("FunctionName")- if not name:- return error_response_json("InvalidParameterValueException", "FunctionName required", 400)- if name in _functions:- return error_response_json("ResourceConflictException", f"Function {name} already exists", 409)-- func_arn = f"arn:aws:lambda:{REGION}:{ACCOUNT_ID}:function:{name}"- config = {- "FunctionName": name,- "FunctionArn": func_arn,- "Runtime": data.get("Runtime", "python3.9"),- "Role": data.get("Role", f"arn:aws:iam::{ACCOUNT_ID}:role/lambda-role"),- "Handler": data.get("Handler", "index.handler"),- "CodeSize": 0,- "Description": data.get("Description", ""),- "Timeout": data.get("Timeout", 3),- "MemorySize": data.get("MemorySize", 128),- "LastModified": time.strftime("%Y-%m-%dT%H:%M:%S.000+0000"),- "Version": "$LATEST",- "State": "Active",- "PackageType": "Zip",- "Environment": data.get("Environment", {"Variables": {}}),- "Layers": data.get("Layers", []),- }-- code_zip = None- code_data = data.get("Code", {})- if "ZipFile" in code_data:- code_zip = base64.b64decode(code_data["ZipFile"])- config["CodeSize"] = len(code_zip)- config["CodeSha256"] = base64.b64encode(b"fakehash").decode()-- _functions[name] = {"config": config, "code_zip": code_zip}-- return json_response(config, 201)---def _get_function(name):- if name not in _functions:- return error_response_json("ResourceNotFoundException", f"Function {name} not found", 404)- func = _functions[name]- return json_response({- "Configuration": func["config"],- "Code": {"RepositoryType": "S3", "Location": ""},- })---def _get_function_config(name):- if name not in _functions:- return error_response_json("ResourceNotFoundException", f"Function {name} not found", 404)- return json_response(_functions[name]["config"])---def _list_functions():- funcs = [f["config"] for f in _functions.values()]- return json_response({"Functions": funcs})---def _delete_function(name):- if name not in _functions:- return error_response_json("ResourceNotFoundException", f"Function {name} not found", 404)- del _functions[name]- return 204, {}, b""---def _update_code(name, data):- if name not in _functions:- return error_response_json("ResourceNotFoundException", f"Function {name} not found", 404)- if "ZipFile" in data:- code_zip = base64.b64decode(data["ZipFile"])- _functions[name]["code_zip"] = code_zip- _functions[name]["config"]["CodeSize"] = len(code_zip)- _functions[name]["config"]["LastModified"] = time.strftime("%Y-%m-%dT%H:%M:%S.000+0000")- return json_response(_functions[name]["config"])---def _update_config(name, data):- if name not in _functions:- return error_response_json("ResourceNotFoundException", f"Function {name} not found", 404)- config = _functions[name]["config"]- for key in ["Runtime", "Handler", "Description", "Timeout", "MemorySize", "Role", "Environment", "Layers"]:- if key in data:- config[key] = data[key]- config["LastModified"] = time.strftime("%Y-%m-%dT%H:%M:%S.000+0000")- return json_response(config)---def _invoke(name, event, headers):- if name not in _functions:- return error_response_json("ResourceNotFoundException", f"Function {name} not found", 404)-- func = _functions[name]- invocation_type = headers.get("x-amz-invocation-type", "RequestResponse")-- if invocation_type == "Event":- # Async — just acknowledge- return 202, {"X-Amz-Function-Error": ""}, b""-- # Try to actually execute the function if we have the code- result = _execute_function(func, event)-- resp_headers = {- "Content-Type": "application/json",- "X-Amz-Executed-Version": "$LATEST",- }- if result.get("error"):- resp_headers["X-Amz-Function-Error"] = "Unhandled"-- return 200, resp_headers, json.dumps(result.get("body", {})).encode("utf-8")---def _execute_function(func, event):- """Attempt to execute a Python Lambda function."""- code_zip = func.get("code_zip")- if not code_zip:- return {"body": {"statusCode": 200, "body": "Mock response — no code deployed"}}-- handler = func["config"]["Handler"]- runtime = func["config"]["Runtime"]- env_vars = func["config"].get("Environment", {}).get("Variables", {})-- if not runtime.startswith("python"):- return {"body": {"statusCode": 200, "body": f"Mock response — {runtime} not supported for local execution"}}-- try:- with tempfile.TemporaryDirectory() as tmpdir:- zip_path = os.path.join(tmpdir, "code.zip")- with open(zip_path, "wb") as f:- f.write(code_zip)-- code_dir = os.path.join(tmpdir, "code")- os.makedirs(code_dir)- with zipfile.ZipFile(zip_path) as zf:- zf.extractall(code_dir)-- module_name, func_name = handler.rsplit(".", 1)- event_json = json.dumps(event)-- script = f"""-import sys, json-sys.path.insert(0, '{code_dir}')-import {module_name}-event = json.loads('''{event_json}''')-context = type('Context', (), {{'function_name': '{func["config"]["FunctionName"]}', 'memory_limit_in_mb': {func["config"]["MemorySize"]}, 'invoked_function_arn': '{func["config"]["FunctionArn"]}', 'aws_request_id': '{new_uuid()}'}})()-result = {module_name}.{func_name}(event, context)-print(json.dumps(result))-"""- env = dict(os.environ)- env.update(env_vars)-- proc = subprocess.run(- ["python3", "-c", script],- capture_output=True, text=True, timeout=func["config"]["Timeout"],- env=env,+ queue["messages"] = [+ m for m in queue["messages"]+ if m.get("receipt_handle") not in receipt_handles+ ]+ esm["LastProcessingResult"] = f"OK - {len(batch)} records"+ logger.info(+ f"ESM: Lambda {func_name} processed {len(batch)} messages from {queue_name}",)- if proc.returncode == 0:- try:- return {"body": json.loads(proc.stdout.strip())}- except json.JSONDecodeError:- return {"body": proc.stdout.strip()}- else:- return {"body": {"errorMessage": proc.stderr.strip(), "errorType": "RuntimeError"}, "error": True}- except subprocess.TimeoutExpired:- return {"body": {"errorMessage": "Task timed out", "errorType": "TimeoutError"}, "error": True}- except Exception as e:- logger.error(f"Lambda execution error: {e}")- return {"body": {"errorMessage": str(e), "errorType": type(e).__name__}, "error": True}+# ---------------------------------------------------------------------------+# Function URL Config+# ---------------------------------------------------------------------------++def _url_config_key(func_name: str, qualifier: str | None) -> str:+ return f"{func_name}:{qualifier}" if qualifier else func_name+++def _create_function_url_config(func_name: str, data: dict, qualifier: str | None):+ if func_name not in _functions:+ return error_response_json("ResourceNotFoundException",+ f"Function not found: {_func_arn(func_name)}", 404)+ key = _url_config_key(func_name, qualifier)+ if key in _function_urls:+ return error_response_json("ResourceConflictException",+ f"Function URL config already exists for {func_name}", 409)+ cfg = {+ "FunctionUrl": f"https://{new_uuid()}.lambda-url.us-east-1.on.aws/",+ "FunctionArn": _func_arn(func_name),+ "AuthType": data.get("AuthType", "NONE"),+ "Cors": data.get("Cors", {}),+ "CreationTime": _now_iso(),+ "LastModifiedTime": _now_iso(),+ }+ _function_urls[key] = cfg+ return json_response(cfg, status=201)+++def _get_function_url_config(func_name: str, qualifier: str | None):+ key = _url_config_key(func_name, qualifier)+ cfg = _function_urls.get(key)+ if not cfg:+ return error_response_json("ResourceNotFoundException",+ f"Function URL config not found for {func_name}", 404)+ return json_response(cfg)+++def _update_function_url_config(func_name: str, data: dict, qualifier: str | None):+ key = _url_config_key(func_name, qualifier)+ cfg = _function_urls.get(key)+ if not cfg:+ return error_response_json("ResourceNotFoundException",+ f"Function URL config not found for {func_name}", 404)+ if "AuthType" in data:+ cfg["AuthType"] = data["AuthType"]+ if "Cors" in data:+ cfg["Cors"] = data["Cors"]+ cfg["LastModifiedTime"] = _now_iso()+ return json_response(cfg)+++def _delete_function_url_config(func_name: str, qualifier: str | None):+ key = _url_config_key(func_name, qualifier)+ if key not in _function_urls:+ return error_response_json("ResourceNotFoundException",+ f"Function URL config not found for {func_name}", 404)+ del _function_urls[key]+ return json_response({}, status=204)+++def _list_function_url_configs(func_name: str, query_params: dict):+ configs = [v for k, v in _function_urls.items()+ if k == func_name or k.startswith(f"{func_name}:")]+ return json_response({"FunctionUrlConfigs": configs})+++def reset():+ from core import lambda_runtime+ _functions.clear()+ _layers.clear()+ _esms.clear()+ _function_urls.clear()+ lambda_runtime.reset()diff --git a/services/rds.py b/services/rds.pyindex 4656124a..25f2b619 100644--- a/services/rds.py+++ b/services/rds.py@@ -1,12 +1,21 @@"""RDS Service Emulator.Query API (Action=...) for control plane + optional Docker-based real Postgres/MySQL.-Supports: CreateDBInstance, DeleteDBInstance, DescribeDBInstances,- CreateDBCluster, DeleteDBCluster, DescribeDBClusters,- CreateDBSubnetGroup, DescribeDBSubnetGroups,- CreateDBParameterGroup, DescribeDBParameterGroups,+Supports: CreateDBInstance, DeleteDBInstance, DescribeDBInstances, ModifyDBInstance,StartDBInstance, StopDBInstance, RebootDBInstance,- ListTagsForResource, AddTagsToResource.+ CreateDBCluster, DeleteDBCluster, DescribeDBClusters, ModifyDBCluster,+ StartDBCluster, StopDBCluster,+ CreateDBSubnetGroup, DeleteDBSubnetGroup, DescribeDBSubnetGroups, ModifyDBSubnetGroup,+ CreateDBParameterGroup, DeleteDBParameterGroup, DescribeDBParameterGroups,+ DescribeDBParameters, ModifyDBParameterGroup,+ CreateDBClusterParameterGroup, DescribeDBClusterParameterGroups,+ DeleteDBClusterParameterGroup, DescribeDBClusterParameters, ModifyDBClusterParameterGroup,+ CreateDBSnapshot, DeleteDBSnapshot, DescribeDBSnapshots,+ CreateDBClusterSnapshot, DescribeDBClusterSnapshots, DeleteDBClusterSnapshot,+ CreateOptionGroup, DeleteOptionGroup, DescribeOptionGroups, DescribeOptionGroupOptions,+ CreateDBInstanceReadReplica (stub), RestoreDBInstanceFromDBSnapshot (stub),+ ListTagsForResource, AddTagsToResource, RemoveTagsFromResource,+ DescribeDBEngineVersions, DescribeOrderableDBInstanceOptions.When Docker is available, CreateDBInstance spins up a real Postgres/MySQL containerand returns the actual host:port as the endpoint.@@ -14,7 +23,6 @@ and returns the actual host:port as the endpoint.import osimport time-import jsonimport loggingfrom urllib.parse import parse_qs@@ -22,17 +30,24 @@ from core.responses import new_uuidlogger = logging.getLogger("rds")-ACCOUNT_ID = "000000000000"-REGION = "us-east-1"+ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")BASE_PORT = int(os.environ.get("RDS_BASE_PORT", "15432"))-_instances: dict = {} # db_instance_id -> instance dict-_clusters: dict = {} # db_cluster_id -> cluster dict+_instances: dict = {}+_clusters: dict = {}_subnet_groups: dict = {}_param_groups: dict = {}+_snapshots: dict = {}+_db_cluster_param_groups: dict = {}+_db_cluster_snapshots: dict = {}+_option_groups: dict = {}+_tags: dict = {}_port_counter = [BASE_PORT]_docker = None++def _get_docker():global _dockerif _docker is None:@@ -44,91 +59,71 @@ def _get_docker():return _docker+def _next_port():+ port = _port_counter[0]+ _port_counter[0] += 1+ return port+++# ---------------------------------------------------------------------------+# Request routing+# ---------------------------------------------------------------------------+async def handle_request(method, path, headers, body, query_params):params = dict(query_params)if method == "POST" and body:- form_params = parse_qs(body.decode("utf-8", errors="replace"))+ raw = body if isinstance(body, str) else body.decode("utf-8", errors="replace")+ form_params = parse_qs(raw)for k, v in form_params.items():params[k] = v- action = _p(params, "Action")-- handlers = {- "CreateDBInstance": _create_db_instance,- "DeleteDBInstance": _delete_db_instance,- "DescribeDBInstances": _describe_db_instances,- "StartDBInstance": _start_db_instance,- "StopDBInstance": _stop_db_instance,- "RebootDBInstance": _reboot_db_instance,- "ModifyDBInstance": _modify_db_instance,- "CreateDBCluster": _create_db_cluster,- "DeleteDBCluster": _delete_db_cluster,- "DescribeDBClusters": _describe_db_clusters,- "CreateDBSubnetGroup": _create_subnet_group,- "DescribeDBSubnetGroups": _describe_subnet_groups,- "DeleteDBSubnetGroup": _delete_subnet_group,- "CreateDBParameterGroup": _create_param_group,- "DescribeDBParameterGroups": _describe_param_groups,- "DeleteDBParameterGroup": _delete_param_group,- "ListTagsForResource": _list_tags,- "AddTagsToResource": _add_tags,- "RemoveTagsFromResource": _remove_tags,- "DescribeDBEngineVersions": _describe_engine_versions,- "DescribeOrderableDBInstanceOptions": _describe_orderable_options,- }+ target = headers.get("x-amz-target", "") or headers.get("X-Amz-Target", "")+ if target:+ action = target.split(".")[-1]+ else:+ action = _p(params, "Action")- handler = handlers.get(action)+ handler = _ACTION_MAP.get(action)if not handler:return _error("InvalidAction", f"Unknown RDS action: {action}", 400)return handler(params)+# ---------------------------------------------------------------------------+# DB Instances+# ---------------------------------------------------------------------------+def _create_db_instance(p):db_id = _p(p, "DBInstanceIdentifier")+ if not db_id:+ return _error("MissingParameter", "DBInstanceIdentifier is required", 400)+ if db_id in _instances:+ return _error("DBInstanceAlreadyExists", f"DB instance {db_id} already exists", 400)+engine = _p(p, "Engine") or "postgres"- engine_version = _p(p, "EngineVersion") or ("15.3" if "postgres" in engine else "8.0.33")+ engine_version = _p(p, "EngineVersion") or _default_engine_version(engine)db_class = _p(p, "DBInstanceClass") or "db.t3.micro"master_user = _p(p, "MasterUsername") or "admin"master_pass = _p(p, "MasterUserPassword") or "password"db_name = _p(p, "DBName") or "mydb"- port = int(_p(p, "Port") or ("5432" if "postgres" in engine else "3306"))+ port = int(_p(p, "Port") or _default_port(engine))allocated_storage = int(_p(p, "AllocatedStorage") or "20")-- if db_id in _instances:- return _error("DBInstanceAlreadyExists", f"DB instance {db_id} already exists", 400)+ storage_type = _p(p, "StorageType") or "gp2"+ subnet_group_name = _p(p, "DBSubnetGroupName") or "default"arn = f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:db:{db_id}"+ dbi_resource_id = f"db-{new_uuid().replace('-', '')[:20].upper()}"endpoint_host = "localhost"endpoint_port = portdocker_container_id = None- # Try to spin up a real DB containerdocker_client = _get_docker()if docker_client:- host_port = _port_counter[0]- _port_counter[0] += 1+ host_port = _next_port()endpoint_port = host_port-- if "postgres" in engine or "aurora-postgresql" in engine:- image = f"postgres:{engine_version.split('.')[0]}-alpine"- env = {- "POSTGRES_USER": master_user,- "POSTGRES_PASSWORD": master_pass,- "POSTGRES_DB": db_name,- }- container_port = 5432- elif "mysql" in engine or "aurora-mysql" in engine or "mariadb" in engine:- image = "mysql:8" if "mysql" in engine else "mariadb:latest"- env = {- "MYSQL_ROOT_PASSWORD": master_pass,- "MYSQL_DATABASE": db_name,- "MYSQL_USER": master_user,- "MYSQL_PASSWORD": master_pass,- }- container_port = 3306- else:- image = None-+ image, env, container_port = _docker_image_for_engine(+ engine, engine_version, master_user, master_pass, db_name+ )if image:try:container = docker_client.containers.run(@@ -143,6 +138,22 @@ def _create_db_instance(p):except Exception as e:logger.warning(f"RDS: Docker failed for {db_id}: {e}")+ cluster_id = _p(p, "DBClusterIdentifier")+ param_group_name = _p(p, "DBParameterGroupName") or f"default.{engine}{engine_version.split('.')[0]}"+ now_ts = time.time()++ vpc_sgs = _parse_member_list(p, "VpcSecurityGroupIds")+ vpc_sg_list = [{"VpcSecurityGroupId": sg, "Status": "active"} for sg in vpc_sgs] if vpc_sgs else []++ subnet_group = _subnet_groups.get(subnet_group_name, {+ "DBSubnetGroupName": subnet_group_name,+ "DBSubnetGroupDescription": "default",+ "SubnetGroupStatus": "Complete",+ "Subnets": [],+ "VpcId": "vpc-00000000",+ "DBSubnetGroupArn": f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:subgrp:{subnet_group_name}",+ })+instance = {"DBInstanceIdentifier": db_id,"DBInstanceClass": db_class,@@ -151,63 +162,122 @@ def _create_db_instance(p):"DBInstanceStatus": "available","MasterUsername": master_user,"DBName": db_name,- "Endpoint": {"Address": endpoint_host, "Port": endpoint_port, "HostedZoneId": "Z2R2ITUGPM61AM"},+ "Endpoint": {+ "Address": endpoint_host,+ "Port": endpoint_port,+ "HostedZoneId": "Z2R2ITUGPM61AM",+ },"AllocatedStorage": allocated_storage,- "InstanceCreateTime": time.time(),+ "InstanceCreateTime": _format_time(now_ts),"PreferredBackupWindow": "03:00-04:00","BackupRetentionPeriod": int(_p(p, "BackupRetentionPeriod") or "1"),"DBSecurityGroups": [],- "VpcSecurityGroups": [],- "DBParameterGroups": [{"DBParameterGroupName": f"default.{engine}{engine_version[:3]}", "ParameterApplyStatus": "in-sync"}],- "AvailabilityZone": f"{REGION}a",- "DBSubnetGroup": {"DBSubnetGroupName": _p(p, "DBSubnetGroupName") or "default", "SubnetGroupStatus": "Complete", "Subnets": []},+ "VpcSecurityGroups": vpc_sg_list,+ "DBParameterGroups": [{+ "DBParameterGroupName": param_group_name,+ "ParameterApplyStatus": "in-sync",+ }],+ "AvailabilityZone": _p(p, "AvailabilityZone") or f"{REGION}a",+ "DBSubnetGroup": subnet_group,"PreferredMaintenanceWindow": "sun:05:00-sun:06:00","PendingModifiedValues": {},+ "LatestRestorableTime": _format_time(now_ts),"MultiAZ": _p(p, "MultiAZ") == "true",- "AutoMinorVersionUpgrade": True,+ "AutoMinorVersionUpgrade": _p(p, "AutoMinorVersionUpgrade") != "false","ReadReplicaDBInstanceIdentifiers": [],- "LicenseModel": "general-public-license",- "OptionGroupMemberships": [],+ "ReadReplicaSourceDBInstanceIdentifier": "",+ "ReadReplicaDBClusterIdentifiers": [],+ "ReplicaMode": "",+ "LicenseModel": _license_model(engine),+ "Iops": int(_p(p, "Iops") or "0") if _p(p, "Iops") else None,+ "OptionGroupMemberships": [{+ "OptionGroupName": f"default:{engine}-{engine_version.split('.')[0]}",+ "Status": "in-sync",+ }],+ "CharacterSetName": "",+ "NcharCharacterSetName": "",+ "SecondaryAvailabilityZone": "","PubliclyAccessible": _p(p, "PubliclyAccessible") == "true",- "StorageType": _p(p, "StorageType") or "gp2",- "DbInstancePort": endpoint_port,+ "StatusInfos": [],+ "StorageType": storage_type,+ "TdeCredentialArn": "",+ "DbInstancePort": 0,+ "DBClusterIdentifier": cluster_id,"StorageEncrypted": _p(p, "StorageEncrypted") == "true",- "DbiResourceId": f"db-{new_uuid()[:8].upper()}",- "CACertificateIdentifier": "rds-ca-2019",+ "KmsKeyId": _p(p, "KmsKeyId") or "",+ "DbiResourceId": dbi_resource_id,+ "CACertificateIdentifier": "rds-ca-rsa2048-g1","DomainMemberships": [],- "CopyTagsToSnapshot": False,- "MonitoringInterval": 0,+ "CopyTagsToSnapshot": _p(p, "CopyTagsToSnapshot") == "true",+ "MonitoringInterval": int(_p(p, "MonitoringInterval") or "0"),+ "EnhancedMonitoringResourceArn": "",+ "MonitoringRoleArn": _p(p, "MonitoringRoleArn") or "",+ "PromotionTier": int(_p(p, "PromotionTier") or "1"),"DBInstanceArn": arn,- "IAMDatabaseAuthenticationEnabled": False,- "PerformanceInsightsEnabled": False,+ "Timezone": "",+ "IAMDatabaseAuthenticationEnabled": _p(p, "EnableIAMDatabaseAuthentication") == "true",+ "PerformanceInsightsEnabled": _p(p, "EnablePerformanceInsights") == "true",+ "PerformanceInsightsKMSKeyId": "",+ "PerformanceInsightsRetentionPeriod": 7,+ "EnabledCloudwatchLogsExports": [],+ "ProcessorFeatures": [],"DeletionProtection": _p(p, "DeletionProtection") == "true",+ "AssociatedRoles": [],+ "MaxAllocatedStorage": int(_p(p, "MaxAllocatedStorage") or str(allocated_storage)),"TagList": [],+ "CustomerOwnedIpEnabled": False,+ "ActivityStreamStatus": "stopped",+ "BackupTarget": "region",+ "NetworkType": "IPV4",+ "StorageThroughput": 0,+ "CertificateDetails": {+ "CAIdentifier": "rds-ca-rsa2048-g1",+ "ValidTill": "2061-01-01T00:00:00Z",+ },+ "IsStorageConfigUpgradeAvailable": False,+ "MultiTenant": False,"_docker_container_id": docker_container_id,}_instances[db_id] = instance- return _xml_instance_response("CreateDBInstanceResponse", "CreateDBInstanceResult", instance)++ req_tags = _parse_tags(p)+ if req_tags:+ _tags[arn] = req_tags+ instance["TagList"] = req_tags++ return _single_instance_response("CreateDBInstanceResponse", "CreateDBInstanceResult", instance)def _delete_db_instance(p):db_id = _p(p, "DBInstanceIdentifier")instance = _instances.get(db_id)if not instance:- return _error("DBInstanceNotFound", f"DB instance {db_id} not found", 404)+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)++ if instance.get("DeletionProtection"):+ return _error("InvalidParameterCombination",+ "Cannot delete a DB instance when DeletionProtection is enabled.", 400)- # Stop Docker containerdocker_client = _get_docker()if docker_client and instance.get("_docker_container_id"):try:- container = docker_client.containers.get(instance["_docker_container_id"])- container.stop(timeout=5)- container.remove()+ c = docker_client.containers.get(instance["_docker_container_id"])+ c.stop(timeout=5)+ c.remove()logger.info(f"RDS: removed container for {db_id}")except Exception as e:logger.warning(f"RDS: failed to remove container for {db_id}: {e}")+ skip_snapshot = _p(p, "SkipFinalSnapshot") == "true"+ final_snap_id = _p(p, "FinalDBSnapshotIdentifier")+ if not skip_snapshot and final_snap_id:+ _create_snapshot_internal(final_snap_id, instance)+instance["DBInstanceStatus"] = "deleting"+ arn = instance["DBInstanceArn"]+ _tags.pop(arn, None)del _instances[db_id]- return _xml_instance_response("DeleteDBInstanceResponse", "DeleteDBInstanceResult", instance)+ return _single_instance_response("DeleteDBInstanceResponse", "DeleteDBInstanceResult", instance)def _describe_db_instances(p):@@ -215,85 +285,327 @@ def _describe_db_instances(p):if db_id:instance = _instances.get(db_id)if not instance:- return _error("DBInstanceNotFound", f"DB instance {db_id} not found", 404)+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)instances = [instance]else:instances = list(_instances.values())+ filters = _parse_filters(p)+ if filters:+ instances = _apply_instance_filters(instances, filters)- members = "".join(_instance_xml(i) for i in instances)+ members = "".join(f"<DBInstance>{_instance_xml(i)}</DBInstance>" for i in instances)return _xml(200, "DescribeDBInstancesResponse",f"<DescribeDBInstancesResult><DBInstances>{members}</DBInstances></DescribeDBInstancesResult>")+def _modify_db_instance(p):+ db_id = _p(p, "DBInstanceIdentifier")+ instance = _instances.get(db_id)+ if not instance:+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)++ apply_immediately = _p(p, "ApplyImmediately") == "true"++ field_map = {+ "DBInstanceClass": "DBInstanceClass",+ "AllocatedStorage": "AllocatedStorage",+ "MasterUserPassword": None,+ "MultiAZ": "MultiAZ",+ "EngineVersion": "EngineVersion",+ "StorageType": "StorageType",+ "Iops": "Iops",+ "DBParameterGroupName": None,+ "BackupRetentionPeriod": "BackupRetentionPeriod",+ "PreferredBackupWindow": "PreferredBackupWindow",+ "PreferredMaintenanceWindow": "PreferredMaintenanceWindow",+ "PubliclyAccessible": "PubliclyAccessible",+ "CACertificateIdentifier": "CACertificateIdentifier",+ "DeletionProtection": "DeletionProtection",+ "MaxAllocatedStorage": "MaxAllocatedStorage",+ "MonitoringInterval": "MonitoringInterval",+ "MonitoringRoleArn": "MonitoringRoleArn",+ "CopyTagsToSnapshot": "CopyTagsToSnapshot",+ }++ pending = {}+ for param_key, instance_key in field_map.items():+ val = _p(p, param_key)+ if not val:+ continue+ if instance_key is None:+ continue+ if param_key in ("AllocatedStorage", "BackupRetentionPeriod",+ "MonitoringInterval", "Iops", "MaxAllocatedStorage"):+ val = int(val)+ elif param_key in ("MultiAZ", "PubliclyAccessible",+ "DeletionProtection", "CopyTagsToSnapshot"):+ val = val == "true"++ if apply_immediately:+ instance[instance_key] = val+ else:+ pending[instance_key] = val++ if _p(p, "DBParameterGroupName"):+ instance["DBParameterGroups"] = [{+ "DBParameterGroupName": _p(p, "DBParameterGroupName"),+ "ParameterApplyStatus": "applying" if apply_immediately else "pending-reboot",+ }]++ vpc_sgs = _parse_member_list(p, "VpcSecurityGroupIds")+ if vpc_sgs:+ instance["VpcSecurityGroups"] = [+ {"VpcSecurityGroupId": sg, "Status": "active"} for sg in vpc_sgs+ ]++ if pending:+ instance["PendingModifiedValues"] = pending++ return _single_instance_response("ModifyDBInstanceResponse", "ModifyDBInstanceResult", instance)++def _start_db_instance(p):db_id = _p(p, "DBInstanceIdentifier")instance = _instances.get(db_id)if not instance:- return _error("DBInstanceNotFound", f"DB instance {db_id} not found", 404)+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)instance["DBInstanceStatus"] = "available"- return _xml_instance_response("StartDBInstanceResponse", "StartDBInstanceResult", instance)+ return _single_instance_response("StartDBInstanceResponse", "StartDBInstanceResult", instance)def _stop_db_instance(p):db_id = _p(p, "DBInstanceIdentifier")instance = _instances.get(db_id)if not instance:- return _error("DBInstanceNotFound", f"DB instance {db_id} not found", 404)+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)instance["DBInstanceStatus"] = "stopped"- return _xml_instance_response("StopDBInstanceResponse", "StopDBInstanceResult", instance)+ return _single_instance_response("StopDBInstanceResponse", "StopDBInstanceResult", instance)def _reboot_db_instance(p):db_id = _p(p, "DBInstanceIdentifier")instance = _instances.get(db_id)if not instance:- return _error("DBInstanceNotFound", f"DB instance {db_id} not found", 404)+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)+ instance["DBInstanceStatus"] = "rebooting"instance["DBInstanceStatus"] = "available"- return _xml_instance_response("RebootDBInstanceResponse", "RebootDBInstanceResult", instance)+ return _single_instance_response("RebootDBInstanceResponse", "RebootDBInstanceResult", instance)-def _modify_db_instance(p):+# ---------------------------------------------------------------------------+# Read Replica (stub)+# ---------------------------------------------------------------------------++def _create_read_replica(p):+ source_id = _p(p, "SourceDBInstanceIdentifier")+ replica_id = _p(p, "DBInstanceIdentifier")++ source = _instances.get(source_id)+ if not source:+ return _error("DBInstanceNotFound", f"DBInstance {source_id} not found.", 404)+ if replica_id in _instances:+ return _error("DBInstanceAlreadyExists", f"DBInstance {replica_id} already exists.", 400)++ arn = f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:db:{replica_id}"+ replica = dict(source)+ replica.update({+ "DBInstanceIdentifier": replica_id,+ "DBInstanceArn": arn,+ "ReadReplicaSourceDBInstanceIdentifier": source_id,+ "DBInstanceStatus": "available",+ "DbiResourceId": f"db-{new_uuid().replace('-', '')[:20].upper()}",+ "InstanceCreateTime": _format_time(time.time()),+ "ReadReplicaDBInstanceIdentifiers": [],+ "Endpoint": {+ "Address": "localhost",+ "Port": _next_port(),+ "HostedZoneId": "Z2R2ITUGPM61AM",+ },+ "TagList": [],+ "_docker_container_id": None,+ })+ _instances[replica_id] = replica+ source.setdefault("ReadReplicaDBInstanceIdentifiers", []).append(replica_id)++ req_tags = _parse_tags(p)+ if req_tags:+ _tags[arn] = req_tags+ replica["TagList"] = req_tags++ return _single_instance_response("CreateDBInstanceReadReplicaResponse",+ "CreateDBInstanceReadReplicaResult", replica)+++# ---------------------------------------------------------------------------+# Restore from Snapshot (stub)+# ---------------------------------------------------------------------------++def _restore_from_snapshot(p):db_id = _p(p, "DBInstanceIdentifier")- instance = _instances.get(db_id)- if not instance:- return _error("DBInstanceNotFound", f"DB instance {db_id} not found", 404)- if _p(p, "DBInstanceClass"):- instance["DBInstanceClass"] = _p(p, "DBInstanceClass")- if _p(p, "AllocatedStorage"):- instance["AllocatedStorage"] = int(_p(p, "AllocatedStorage"))- return _xml_instance_response("ModifyDBInstanceResponse", "ModifyDBInstanceResult", instance)+ snap_id = _p(p, "DBSnapshotIdentifier")+ if db_id in _instances:+ return _error("DBInstanceAlreadyExists", f"DBInstance {db_id} already exists.", 400)++ snap = _snapshots.get(snap_id)+ if not snap:+ return _error("DBSnapshotNotFound", f"DBSnapshot {snap_id} not found.", 404)++ arn = f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:db:{db_id}"+ instance = {+ "DBInstanceIdentifier": db_id,+ "DBInstanceClass": _p(p, "DBInstanceClass") or snap.get("DBInstanceClass", "db.t3.micro"),+ "Engine": snap.get("Engine", "postgres"),+ "EngineVersion": snap.get("EngineVersion", "15.3"),+ "DBInstanceStatus": "available",+ "MasterUsername": snap.get("MasterUsername", "admin"),+ "DBName": snap.get("DBName", ""),+ "Endpoint": {+ "Address": "localhost",+ "Port": _next_port(),+ "HostedZoneId": "Z2R2ITUGPM61AM",+ },+ "AllocatedStorage": snap.get("AllocatedStorage", 20),+ "InstanceCreateTime": _format_time(time.time()),+ "PreferredBackupWindow": "03:00-04:00",+ "BackupRetentionPeriod": 1,+ "DBSecurityGroups": [],+ "VpcSecurityGroups": [],+ "DBParameterGroups": [{+ "DBParameterGroupName": f"default.{snap.get('Engine', 'postgres')}",+ "ParameterApplyStatus": "in-sync",+ }],+ "AvailabilityZone": _p(p, "AvailabilityZone") or f"{REGION}a",+ "DBSubnetGroup": {"DBSubnetGroupName": _p(p, "DBSubnetGroupName") or "default",+ "SubnetGroupStatus": "Complete", "Subnets": [], "VpcId": "vpc-00000000",+ "DBSubnetGroupArn": ""},+ "PreferredMaintenanceWindow": "sun:05:00-sun:06:00",+ "PendingModifiedValues": {},+ "MultiAZ": _p(p, "MultiAZ") == "true",+ "AutoMinorVersionUpgrade": True,+ "ReadReplicaDBInstanceIdentifiers": [],+ "ReadReplicaSourceDBInstanceIdentifier": "",+ "ReadReplicaDBClusterIdentifiers": [],+ "LicenseModel": _license_model(snap.get("Engine", "postgres")),+ "OptionGroupMemberships": [],+ "PubliclyAccessible": _p(p, "PubliclyAccessible") == "true",+ "StorageType": _p(p, "StorageType") or snap.get("StorageType", "gp2"),+ "StorageEncrypted": snap.get("StorageEncrypted", False),+ "DbiResourceId": f"db-{new_uuid().replace('-', '')[:20].upper()}",+ "CACertificateIdentifier": "rds-ca-rsa2048-g1",+ "DomainMemberships": [],+ "CopyTagsToSnapshot": False,+ "MonitoringInterval": 0,+ "DBInstanceArn": arn,+ "IAMDatabaseAuthenticationEnabled": False,+ "PerformanceInsightsEnabled": False,+ "DeletionProtection": False,+ "TagList": [],+ "_docker_container_id": None,+ }+ _instances[db_id] = instance+ return _single_instance_response("RestoreDBInstanceFromDBSnapshotResponse",+ "RestoreDBInstanceFromDBSnapshotResult", instance)+++# ---------------------------------------------------------------------------+# DB Clusters+# ---------------------------------------------------------------------------def _create_db_cluster(p):cluster_id = _p(p, "DBClusterIdentifier")+ if not cluster_id:+ return _error("MissingParameter", "DBClusterIdentifier is required", 400)+ if cluster_id in _clusters:+ return _error("DBClusterAlreadyExistsFault",+ f"DB cluster {cluster_id} already exists.", 400)+engine = _p(p, "Engine") or "aurora-postgresql"+ engine_version = _p(p, "EngineVersion") or _default_engine_version(engine)+ port = int(_p(p, "Port") or _default_port(engine))+ master_user = _p(p, "MasterUsername") or "admin"arn = f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:cluster:{cluster_id}"- _clusters[cluster_id] = {+ unique_suffix = new_uuid()[:8]+ now_ts = time.time()++ vpc_sgs = _parse_member_list(p, "VpcSecurityGroupIds")+ vpc_sg_list = [{"VpcSecurityGroupId": sg, "Status": "active"} for sg in vpc_sgs] if vpc_sgs else []+ az_list = _parse_member_list(p, "AvailabilityZones")+ if not az_list:+ az_list = [f"{REGION}a", f"{REGION}b", f"{REGION}c"]++ cluster = {"DBClusterIdentifier": cluster_id,"DBClusterArn": arn,"Engine": engine,- "EngineVersion": _p(p, "EngineVersion") or "15.3",+ "EngineVersion": engine_version,+ "EngineMode": _p(p, "EngineMode") or "provisioned","Status": "available",- "MasterUsername": _p(p, "MasterUsername") or "admin",+ "MasterUsername": master_user,"DatabaseName": _p(p, "DatabaseName") or "",- "Endpoint": f"{cluster_id}.cluster-{new_uuid()[:8]}.{REGION}.rds.amazonaws.com",- "ReaderEndpoint": f"{cluster_id}.cluster-ro-{new_uuid()[:8]}.{REGION}.rds.amazonaws.com",- "Port": int(_p(p, "Port") or "5432"),- "MultiAZ": False,+ "Endpoint": f"{cluster_id}.cluster-{unique_suffix}.{REGION}.rds.amazonaws.com",+ "ReaderEndpoint": f"{cluster_id}.cluster-ro-{unique_suffix}.{REGION}.rds.amazonaws.com",+ "Port": port,+ "MultiAZ": _p(p, "MultiAZ") == "true",+ "AvailabilityZones": az_list,"DBClusterMembers": [],- "ClusterCreateTime": time.time(),+ "VpcSecurityGroups": vpc_sg_list,+ "DBSubnetGroup": _p(p, "DBSubnetGroupName") or "default",+ "DBClusterParameterGroup": _p(p, "DBClusterParameterGroupName") or f"default.{engine}",+ "BackupRetentionPeriod": int(_p(p, "BackupRetentionPeriod") or "1"),+ "PreferredBackupWindow": _p(p, "PreferredBackupWindow") or "03:00-04:00",+ "PreferredMaintenanceWindow": _p(p, "PreferredMaintenanceWindow") or "sun:05:00-sun:06:00",+ "ClusterCreateTime": _format_time(now_ts),+ "EarliestRestorableTime": _format_time(now_ts),+ "LatestRestorableTime": _format_time(now_ts),+ "StorageEncrypted": _p(p, "StorageEncrypted") == "true",+ "KmsKeyId": _p(p, "KmsKeyId") or "",+ "DeletionProtection": _p(p, "DeletionProtection") == "true",+ "IAMDatabaseAuthenticationEnabled": _p(p, "EnableIAMDatabaseAuthentication") == "true",+ "EnabledCloudwatchLogsExports": [],+ "HttpEndpointEnabled": _p(p, "EnableHttpEndpoint") == "true",+ "CopyTagsToSnapshot": _p(p, "CopyTagsToSnapshot") == "true",+ "CrossAccountClone": False,+ "DbClusterResourceId": f"cluster-{new_uuid().replace('-', '')[:20].upper()}",+ "TagList": [],+ "HostedZoneId": "Z2R2ITUGPM61AM",+ "AssociatedRoles": [],+ "ActivityStreamStatus": "stopped",+ "AllocatedStorage": 1,+ "Capacity": 0,+ "ClusterScalabilityType": "standard",}- members = _cluster_xml(_clusters[cluster_id])- return _xml(200, "CreateDBClusterResponse", f"<CreateDBClusterResult><DBCluster>{members}</DBCluster></CreateDBClusterResult>")+ _clusters[cluster_id] = cluster++ req_tags = _parse_tags(p)+ if req_tags:+ _tags[arn] = req_tags+ cluster["TagList"] = req_tags++ return _xml(200, "CreateDBClusterResponse",+ f"<CreateDBClusterResult><DBCluster>{_cluster_xml(cluster)}</DBCluster></CreateDBClusterResult>")def _delete_db_cluster(p):cluster_id = _p(p, "DBClusterIdentifier")- cluster = _clusters.pop(cluster_id, None)+ cluster = _clusters.get(cluster_id)if not cluster:- return _error("DBClusterNotFoundFault", f"Cluster {cluster_id} not found", 404)- members = _cluster_xml(cluster)- return _xml(200, "DeleteDBClusterResponse", f"<DeleteDBClusterResult><DBCluster>{members}</DBCluster></DeleteDBClusterResult>")+ return _error("DBClusterNotFoundFault", f"DBCluster {cluster_id} not found.", 404)++ if cluster.get("DeletionProtection"):+ return _error("InvalidParameterCombination",+ "Cannot delete a DB cluster when DeletionProtection is enabled.", 400)++ skip_snapshot = _p(p, "SkipFinalSnapshot") == "true"+ final_snap_id = _p(p, "FinalDBSnapshotIdentifier")+ if not skip_snapshot and final_snap_id:+ pass++ cluster["Status"] = "deleting"+ _tags.pop(cluster["DBClusterArn"], None)+ del _clusters[cluster_id]+ return _xml(200, "DeleteDBClusterResponse",+ f"<DeleteDBClusterResult><DBCluster>{_cluster_xml(cluster)}</DBCluster></DeleteDBClusterResult>")def _describe_db_clusters(p):@@ -301,94 +613,873 @@ def _describe_db_clusters(p):if cluster_id:cluster = _clusters.get(cluster_id)if not cluster:- return _error("DBClusterNotFoundFault", f"Cluster {cluster_id} not found", 404)+ return _error("DBClusterNotFoundFault", f"DBCluster {cluster_id} not found.", 404)clusters = [cluster]else:clusters = list(_clusters.values())- members = "".join(f"<member>{_cluster_xml(c)}</member>" for c in clusters)+ filters = _parse_filters(p)+ if filters:+ clusters = _apply_cluster_filters(clusters, filters)++ members = "".join(f"<DBCluster>{_cluster_xml(c)}</DBCluster>" for c in clusters)return _xml(200, "DescribeDBClustersResponse",f"<DescribeDBClustersResult><DBClusters>{members}</DBClusters></DescribeDBClustersResult>")+def _modify_db_cluster(p):+ cluster_id = _p(p, "DBClusterIdentifier")+ cluster = _clusters.get(cluster_id)+ if not cluster:+ return _error("DBClusterNotFoundFault", f"DBCluster {cluster_id} not found.", 404)++ if _p(p, "EngineVersion"):+ cluster["EngineVersion"] = _p(p, "EngineVersion")+ if _p(p, "MasterUserPassword"):+ pass+ if _p(p, "Port"):+ cluster["Port"] = int(_p(p, "Port"))+ if _p(p, "BackupRetentionPeriod"):+ cluster["BackupRetentionPeriod"] = int(_p(p, "BackupRetentionPeriod"))+ if _p(p, "PreferredBackupWindow"):+ cluster["PreferredBackupWindow"] = _p(p, "PreferredBackupWindow")+ if _p(p, "PreferredMaintenanceWindow"):+ cluster["PreferredMaintenanceWindow"] = _p(p, "PreferredMaintenanceWindow")+ if _p(p, "DeletionProtection"):+ cluster["DeletionProtection"] = _p(p, "DeletionProtection") == "true"+ if _p(p, "EnableIAMDatabaseAuthentication"):+ cluster["IAMDatabaseAuthenticationEnabled"] = _p(p, "EnableIAMDatabaseAuthentication") == "true"+ if _p(p, "EnableHttpEndpoint"):+ cluster["HttpEndpointEnabled"] = _p(p, "EnableHttpEndpoint") == "true"+ if _p(p, "CopyTagsToSnapshot"):+ cluster["CopyTagsToSnapshot"] = _p(p, "CopyTagsToSnapshot") == "true"+ if _p(p, "DBClusterParameterGroupName"):+ cluster["DBClusterParameterGroup"] = _p(p, "DBClusterParameterGroupName")++ vpc_sgs = _parse_member_list(p, "VpcSecurityGroupIds")+ if vpc_sgs:+ cluster["VpcSecurityGroups"] = [+ {"VpcSecurityGroupId": sg, "Status": "active"} for sg in vpc_sgs+ ]++ return _xml(200, "ModifyDBClusterResponse",+ f"<ModifyDBClusterResult><DBCluster>{_cluster_xml(cluster)}</DBCluster></ModifyDBClusterResult>")+++# ---------------------------------------------------------------------------+# Snapshots+# ---------------------------------------------------------------------------++def _create_snapshot_internal(snap_id, instance):+ """Internal helper — creates a snapshot dict from an instance."""+ arn = f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:snapshot:{snap_id}"+ now_ts = time.time()+ snap = {+ "DBSnapshotIdentifier": snap_id,+ "DBInstanceIdentifier": instance["DBInstanceIdentifier"],+ "DBSnapshotArn": arn,+ "Engine": instance["Engine"],+ "EngineVersion": instance["EngineVersion"],+ "SnapshotCreateTime": _format_time(now_ts),+ "InstanceCreateTime": instance.get("InstanceCreateTime", _format_time(now_ts)),+ "Status": "available",+ "AllocatedStorage": instance.get("AllocatedStorage", 20),+ "AvailabilityZone": instance.get("AvailabilityZone", f"{REGION}a"),+ "VpcId": "vpc-00000000",+ "Port": instance.get("Endpoint", {}).get("Port", 5432),+ "MasterUsername": instance.get("MasterUsername", "admin"),+ "DBName": instance.get("DBName", ""),+ "SnapshotType": "manual",+ "LicenseModel": instance.get("LicenseModel", "general-public-license"),+ "StorageType": instance.get("StorageType", "gp2"),+ "DBInstanceClass": instance.get("DBInstanceClass", "db.t3.micro"),+ "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(_tags.get(instance.get("DBInstanceArn", ""), [])),+ "OriginalSnapshotCreateTime": _format_time(now_ts),+ "SnapshotDatabaseTime": _format_time(now_ts),+ "SnapshotTarget": "region",+ }+ _snapshots[snap_id] = snap+ return snap+++def _create_db_snapshot(p):+ snap_id = _p(p, "DBSnapshotIdentifier")+ db_id = _p(p, "DBInstanceIdentifier")+ if not snap_id:+ return _error("MissingParameter", "DBSnapshotIdentifier is required", 400)+ if snap_id in _snapshots:+ return _error("DBSnapshotAlreadyExists", f"Snapshot {snap_id} already exists.", 400)++ instance = _instances.get(db_id)+ if not instance:+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)++ snap = _create_snapshot_internal(snap_id, instance)++ req_tags = _parse_tags(p)+ if req_tags:+ _tags[snap["DBSnapshotArn"]] = req_tags+ snap["TagList"] = req_tags++ return _xml(200, "CreateDBSnapshotResponse",+ f"<CreateDBSnapshotResult><DBSnapshot>{_snapshot_xml(snap)}</DBSnapshot></CreateDBSnapshotResult>")+++def _delete_db_snapshot(p):+ snap_id = _p(p, "DBSnapshotIdentifier")+ snap = _snapshots.pop(snap_id, None)+ if not snap:+ return _error("DBSnapshotNotFound", f"Snapshot {snap_id} not found.", 404)+ _tags.pop(snap.get("DBSnapshotArn", ""), None)+ snap["Status"] = "deleted"+ return _xml(200, "DeleteDBSnapshotResponse",+ f"<DeleteDBSnapshotResult><DBSnapshot>{_snapshot_xml(snap)}</DBSnapshot></DeleteDBSnapshotResult>")+++def _describe_db_snapshots(p):+ snap_id = _p(p, "DBSnapshotIdentifier")+ db_id = _p(p, "DBInstanceIdentifier")+ snap_type = _p(p, "SnapshotType")++ if snap_id:+ snap = _snapshots.get(snap_id)+ if not snap:+ return _error("DBSnapshotNotFound", f"Snapshot {snap_id} not found.", 404)+ snaps = [snap]+ else:+ snaps = list(_snapshots.values())+ if db_id:+ snaps = [s for s in snaps if s["DBInstanceIdentifier"] == db_id]+ if snap_type:+ snaps = [s for s in snaps if s["SnapshotType"] == snap_type]++ members = "".join(f"<DBSnapshot>{_snapshot_xml(s)}</DBSnapshot>" for s in snaps)+ return _xml(200, "DescribeDBSnapshotsResponse",+ f"<DescribeDBSnapshotsResult><DBSnapshots>{members}</DBSnapshots></DescribeDBSnapshotsResult>")+++# ---------------------------------------------------------------------------+# Subnet Groups+# ---------------------------------------------------------------------------+def _create_subnet_group(p):name = _p(p, "DBSubnetGroupName")- _subnet_groups[name] = {"DBSubnetGroupName": name, "DBSubnetGroupDescription": _p(p, "DBSubnetGroupDescription"), "Subnets": []}+ if not name:+ return _error("MissingParameter", "DBSubnetGroupName is required", 400)+ desc = _p(p, "DBSubnetGroupDescription") or name+ subnet_ids = _parse_member_list(p, "SubnetIds")+ arn = f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:subgrp:{name}"++ subnets = [{"SubnetIdentifier": sid, "SubnetAvailabilityZone": {"Name": f"{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(p)+ if req_tags:+ _tags[arn] = req_tags++ sg = _subnet_groups[name]return _xml(200, "CreateDBSubnetGroupResponse",- f"<CreateDBSubnetGroupResult><DBSubnetGroup><DBSubnetGroupName>{name}</DBSubnetGroupName></DBSubnetGroup></CreateDBSubnetGroupResult>")+ f"<CreateDBSubnetGroupResult><DBSubnetGroup>{_subnet_group_xml(sg)}</DBSubnetGroup></CreateDBSubnetGroupResult>")+++def _delete_subnet_group(p):+ name = _p(p, "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(p):name = _p(p, "DBSubnetGroupName")- groups = [_subnet_groups[name]] if name and name in _subnet_groups else list(_subnet_groups.values())- members = "".join(f"<member><DBSubnetGroupName>{g['DBSubnetGroupName']}</DBSubnetGroupName></member>" for g in groups)+ 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",f"<DescribeDBSubnetGroupsResult><DBSubnetGroups>{members}</DBSubnetGroups></DescribeDBSubnetGroupsResult>")-def _delete_subnet_group(p):- _subnet_groups.pop(_p(p, "DBSubnetGroupName"), None)- return _xml(200, "DeleteDBSubnetGroupResponse", "")-+# ---------------------------------------------------------------------------+# Parameter Groups+# ---------------------------------------------------------------------------def _create_param_group(p):name = _p(p, "DBParameterGroupName")- _param_groups[name] = {"DBParameterGroupName": name, "DBParameterGroupFamily": _p(p, "DBParameterGroupFamily"), "Description": _p(p, "Description")}+ if not name:+ return _error("MissingParameter", "DBParameterGroupName is required", 400)+ family = _p(p, "DBParameterGroupFamily") or "postgres15"+ desc = _p(p, "Description") or name+ arn = f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:pg:{name}"++ _param_groups[name] = {+ "DBParameterGroupName": name,+ "DBParameterGroupFamily": family,+ "Description": desc,+ "DBParameterGroupArn": arn,+ "Parameters": {},+ }++ req_tags = _parse_tags(p)+ if req_tags:+ _tags[arn] = req_tags+return _xml(200, "CreateDBParameterGroupResponse",- f"<CreateDBParameterGroupResult><DBParameterGroup><DBParameterGroupName>{name}</DBParameterGroupName></DBParameterGroup></CreateDBParameterGroupResult>")+ f"""<CreateDBParameterGroupResult><DBParameterGroup>+ <DBParameterGroupName>{name}</DBParameterGroupName>+ <DBParameterGroupFamily>{family}</DBParameterGroupFamily>+ <Description>{desc}</Description>+ <DBParameterGroupArn>{arn}</DBParameterGroupArn>+ </DBParameterGroup></CreateDBParameterGroupResult>""")+++def _delete_param_group(p):+ name = _p(p, "DBParameterGroupName")+ pg = _param_groups.pop(name, None)+ if not pg:+ return _error("DBParameterGroupNotFoundFault", f"Parameter group {name} not found.", 404)+ _tags.pop(pg.get("DBParameterGroupArn", ""), None)+ return _xml(200, "DeleteDBParameterGroupResponse", "")def _describe_param_groups(p):name = _p(p, "DBParameterGroupName")- groups = [_param_groups[name]] if name and name in _param_groups else list(_param_groups.values())- members = "".join(f"<member><DBParameterGroupName>{g['DBParameterGroupName']}</DBParameterGroupName></member>" for g in groups)+ if name:+ pg = _param_groups.get(name)+ if not pg:+ return _error("DBParameterGroupNotFoundFault", f"Parameter group {name} not found.", 404)+ groups = [pg]+ else:+ groups = list(_param_groups.values())++ members = "".join(f"""<DBParameterGroup>+ <DBParameterGroupName>{g['DBParameterGroupName']}</DBParameterGroupName>+ <DBParameterGroupFamily>{g['DBParameterGroupFamily']}</DBParameterGroupFamily>+ <Description>{g['Description']}</Description>+ <DBParameterGroupArn>{g.get('DBParameterGroupArn','')}</DBParameterGroupArn>+ </DBParameterGroup>""" for g in groups)return _xml(200, "DescribeDBParameterGroupsResponse",f"<DescribeDBParameterGroupsResult><DBParameterGroups>{members}</DBParameterGroups></DescribeDBParameterGroupsResult>")-def _delete_param_group(p):- _param_groups.pop(_p(p, "DBParameterGroupName"), None)- return _xml(200, "DeleteDBParameterGroupResponse", "")+def _describe_db_parameters(p):+ name = _p(p, "DBParameterGroupName")+ pg = _param_groups.get(name)+ if not pg:+ return _error("DBParameterGroupNotFoundFault", f"Parameter group {name} not found.", 404)++ family = pg.get("DBParameterGroupFamily", "")+ default_params = _default_parameters_for_family(family)++ custom = pg.get("Parameters", {})+ params_xml = ""+ for param in default_params:+ pname = param["name"]+ value = custom.get(pname, param.get("default", ""))+ source = "user" if pname in custom else "engine-default"+ params_xml += f"""<Parameter>+ <ParameterName>{pname}</ParameterName>+ <ParameterValue>{value}</ParameterValue>+ <Description>{param.get('description', '')}</Description>+ <Source>{source}</Source>+ <ApplyType>{param.get('apply_type', 'dynamic')}</ApplyType>+ <DataType>{param.get('data_type', 'string')}</DataType>+ <IsModifiable>{str(param.get('modifiable', True)).lower()}</IsModifiable>+ <ApplyMethod>pending-reboot</ApplyMethod>+ </Parameter>"""++ return _xml(200, "DescribeDBParametersResponse",+ f"<DescribeDBParametersResult><Parameters>{params_xml}</Parameters></DescribeDBParametersResult>")+++# ---------------------------------------------------------------------------+# ModifyDBParameterGroup+# ---------------------------------------------------------------------------++def _modify_param_group(p):+ name = _p(p, "DBParameterGroupName")+ pg = _param_groups.get(name)+ if not pg:+ return _error("DBParameterGroupNotFoundFault", f"Parameter group {name} not found.", 404)++ params = pg.setdefault("Parameters", {})+ idx = 1+ while _p(p, f"Parameters.member.{idx}.ParameterName"):+ pname = _p(p, f"Parameters.member.{idx}.ParameterName")+ pvalue = _p(p, f"Parameters.member.{idx}.ParameterValue")+ params[pname] = pvalue+ idx += 1++ return _xml(200, "ModifyDBParameterGroupResponse",+ f"<ModifyDBParameterGroupResult><DBParameterGroupName>{name}</DBParameterGroupName></ModifyDBParameterGroupResult>")+++# ---------------------------------------------------------------------------+# DB Cluster Parameter Groups+# ---------------------------------------------------------------------------++def _create_db_cluster_param_group(p):+ name = _p(p, "DBClusterParameterGroupName")+ if not name:+ return _error("MissingParameter", "DBClusterParameterGroupName is required", 400)+ family = _p(p, "DBParameterGroupFamily") or "aurora-postgresql15"+ desc = _p(p, "Description") or name+ arn = f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:cluster-pg:{name}"++ _db_cluster_param_groups[name] = {+ "DBClusterParameterGroupName": name,+ "DBParameterGroupFamily": family,+ "Description": desc,+ "DBClusterParameterGroupArn": arn,+ "Parameters": {},+ }+ req_tags = _parse_tags(p)+ if req_tags:+ _tags[arn] = req_tags++ return _xml(200, "CreateDBClusterParameterGroupResponse",+ f"""<CreateDBClusterParameterGroupResult><DBClusterParameterGroup>+ <DBClusterParameterGroupName>{name}</DBClusterParameterGroupName>+ <DBParameterGroupFamily>{family}</DBParameterGroupFamily>+ <Description>{desc}</Description>+ <DBClusterParameterGroupArn>{arn}</DBClusterParameterGroupArn>+ </DBClusterParameterGroup></CreateDBClusterParameterGroupResult>""")+++def _describe_db_cluster_param_groups(p):+ name = _p(p, "DBClusterParameterGroupName")+ if name:+ pg = _db_cluster_param_groups.get(name)+ if not pg:+ return _error("DBParameterGroupNotFoundFault",+ f"DB cluster parameter group {name} not found.", 404)+ groups = [pg]+ else:+ groups = list(_db_cluster_param_groups.values())++ members = "".join(f"""<DBClusterParameterGroup>+ <DBClusterParameterGroupName>{g['DBClusterParameterGroupName']}</DBClusterParameterGroupName>+ <DBParameterGroupFamily>{g['DBParameterGroupFamily']}</DBParameterGroupFamily>+ <Description>{g['Description']}</Description>+ <DBClusterParameterGroupArn>{g.get('DBClusterParameterGroupArn','')}</DBClusterParameterGroupArn>+ </DBClusterParameterGroup>""" for g in groups)+ return _xml(200, "DescribeDBClusterParameterGroupsResponse",+ f"<DescribeDBClusterParameterGroupsResult><DBClusterParameterGroups>{members}</DBClusterParameterGroups></DescribeDBClusterParameterGroupsResult>")+++def _delete_db_cluster_param_group(p):+ name = _p(p, "DBClusterParameterGroupName")+ pg = _db_cluster_param_groups.pop(name, None)+ if not pg:+ return _error("DBParameterGroupNotFoundFault",+ f"DB cluster parameter group {name} not found.", 404)+ _tags.pop(pg.get("DBClusterParameterGroupArn", ""), None)+ return _xml(200, "DeleteDBClusterParameterGroupResponse", "")+++def _describe_db_cluster_parameters(p):+ name = _p(p, "DBClusterParameterGroupName")+ pg = _db_cluster_param_groups.get(name)+ if not pg:+ return _error("DBParameterGroupNotFoundFault",+ f"DB cluster parameter group {name} not found.", 404)+ return _xml(200, "DescribeDBClusterParametersResponse",+ "<DescribeDBClusterParametersResult><Parameters/></DescribeDBClusterParametersResult>")+++def _modify_db_cluster_param_group(p):+ name = _p(p, "DBClusterParameterGroupName")+ pg = _db_cluster_param_groups.get(name)+ if not pg:+ return _error("DBParameterGroupNotFoundFault",+ f"DB cluster parameter group {name} not found.", 404)++ params = pg.setdefault("Parameters", {})+ idx = 1+ while _p(p, f"Parameters.member.{idx}.ParameterName"):+ pname = _p(p, f"Parameters.member.{idx}.ParameterName")+ pvalue = _p(p, f"Parameters.member.{idx}.ParameterValue")+ params[pname] = pvalue+ idx += 1++ return _xml(200, "ModifyDBClusterParameterGroupResponse",+ f"<ModifyDBClusterParameterGroupResult><DBClusterParameterGroupName>{name}</DBClusterParameterGroupName></ModifyDBClusterParameterGroupResult>")+++# ---------------------------------------------------------------------------+# DB Cluster Snapshots+# ---------------------------------------------------------------------------++def _create_db_cluster_snapshot(p):+ snap_id = _p(p, "DBClusterSnapshotIdentifier")+ cluster_id = _p(p, "DBClusterIdentifier")+ 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)-def _list_tags(p):- return _xml(200, "ListTagsForResourceResponse", "<ListTagsForResourceResult><TagList/></ListTagsForResourceResult>")+ cluster = _clusters.get(cluster_id)+ if not cluster:+ return _error("DBClusterNotFoundFault", f"DBCluster {cluster_id} not found.", 404)+ arn = f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:cluster-snapshot:{snap_id}"+ now_ts = time.time()+ snap = {+ "DBClusterSnapshotIdentifier": snap_id,+ "DBClusterIdentifier": cluster_id,+ "DBClusterSnapshotArn": arn,+ "Engine": cluster["Engine"],+ "EngineVersion": cluster["EngineVersion"],+ "SnapshotCreateTime": _format_time(now_ts),+ "ClusterCreateTime": cluster.get("ClusterCreateTime", _format_time(now_ts)),+ "Status": "available",+ "Port": cluster.get("Port", 5432),+ "VpcId": "vpc-00000000",+ "MasterUsername": cluster.get("MasterUsername", "admin"),+ "SnapshotType": "manual",+ "PercentProgress": 100,+ "StorageEncrypted": cluster.get("StorageEncrypted", False),+ "KmsKeyId": cluster.get("KmsKeyId", ""),+ "AvailabilityZones": cluster.get("AvailabilityZones", []),+ "LicenseModel": _license_model(cluster.get("Engine", "aurora-postgresql")),+ "TagList": list(_tags.get(cluster.get("DBClusterArn", ""), [])),+ "DbClusterResourceId": cluster.get("DbClusterResourceId", ""),+ "IAMDatabaseAuthenticationEnabled": cluster.get("IAMDatabaseAuthenticationEnabled", False),+ "AllocatedStorage": cluster.get("AllocatedStorage", 1),+ }+ _db_cluster_snapshots[snap_id] = snap++ req_tags = _parse_tags(p)+ if req_tags:+ _tags[arn] = req_tags+ snap["TagList"] = req_tags++ return _xml(200, "CreateDBClusterSnapshotResponse",+ f"<CreateDBClusterSnapshotResult><DBClusterSnapshot>{_cluster_snapshot_xml(snap)}</DBClusterSnapshot></CreateDBClusterSnapshotResult>")+++def _describe_db_cluster_snapshots(p):+ snap_id = _p(p, "DBClusterSnapshotIdentifier")+ cluster_id = _p(p, "DBClusterIdentifier")+ snap_type = _p(p, "SnapshotType")++ 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())+ if cluster_id:+ snaps = [s for s in snaps if s["DBClusterIdentifier"] == cluster_id]+ if snap_type:+ snaps = [s for s in snaps if s["SnapshotType"] == snap_type]++ members = "".join(+ f"<DBClusterSnapshot>{_cluster_snapshot_xml(s)}</DBClusterSnapshot>" for s in snaps)+ return _xml(200, "DescribeDBClusterSnapshotsResponse",+ f"<DescribeDBClusterSnapshotsResult><DBClusterSnapshots>{members}</DBClusterSnapshots></DescribeDBClusterSnapshotsResult>")+++def _delete_db_cluster_snapshot(p):+ snap_id = _p(p, "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",+ f"<DeleteDBClusterSnapshotResult><DBClusterSnapshot>{_cluster_snapshot_xml(snap)}</DBClusterSnapshot></DeleteDBClusterSnapshotResult>")+++# ---------------------------------------------------------------------------+# ModifyDBSubnetGroup+# ---------------------------------------------------------------------------++def _modify_subnet_group(p):+ name = _p(p, "DBSubnetGroupName")+ sg = _subnet_groups.get(name)+ if not sg:+ return _error("DBSubnetGroupNotFoundFault", f"Subnet group {name} not found.", 404)++ if _p(p, "DBSubnetGroupDescription"):+ sg["DBSubnetGroupDescription"] = _p(p, "DBSubnetGroupDescription")++ subnet_ids = _parse_member_list(p, "SubnetIds")+ if subnet_ids:+ sg["Subnets"] = [+ {"SubnetIdentifier": sid, "SubnetAvailabilityZone": {"Name": f"{REGION}a"},+ "SubnetOutpost": {}, "SubnetStatus": "Active"} for sid in subnet_ids+ ]++ return _xml(200, "ModifyDBSubnetGroupResponse",+ f"<ModifyDBSubnetGroupResult><DBSubnetGroup>{_subnet_group_xml(sg)}</DBSubnetGroup></ModifyDBSubnetGroupResult>")+++# ---------------------------------------------------------------------------+# StartDBCluster / StopDBCluster+# ---------------------------------------------------------------------------++def _start_db_cluster(p):+ cluster_id = _p(p, "DBClusterIdentifier")+ cluster = _clusters.get(cluster_id)+ if not cluster:+ return _error("DBClusterNotFoundFault", f"DBCluster {cluster_id} not found.", 404)+ cluster["Status"] = "available"+ return _xml(200, "StartDBClusterResponse",+ f"<StartDBClusterResult><DBCluster>{_cluster_xml(cluster)}</DBCluster></StartDBClusterResult>")+++def _stop_db_cluster(p):+ cluster_id = _p(p, "DBClusterIdentifier")+ cluster = _clusters.get(cluster_id)+ if not cluster:+ return _error("DBClusterNotFoundFault", f"DBCluster {cluster_id} not found.", 404)+ cluster["Status"] = "stopped"+ return _xml(200, "StopDBClusterResponse",+ f"<StopDBClusterResult><DBCluster>{_cluster_xml(cluster)}</DBCluster></StopDBClusterResult>")+++# ---------------------------------------------------------------------------+# Option Groups+# ---------------------------------------------------------------------------++def _create_option_group(p):+ name = _p(p, "OptionGroupName")+ if not name:+ return _error("MissingParameter", "OptionGroupName is required", 400)+ if name in _option_groups:+ return _error("OptionGroupAlreadyExistsFault",+ f"Option group {name} already exists.", 400)++ engine = _p(p, "EngineName") or "postgres"+ major_version = _p(p, "MajorEngineVersion") or "15"+ desc = _p(p, "OptionGroupDescription") or name+ arn = f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:og:{name}"++ _option_groups[name] = {+ "OptionGroupName": name,+ "OptionGroupDescription": desc,+ "EngineName": engine,+ "MajorEngineVersion": major_version,+ "Options": [],+ "AllowsVpcAndNonVpcInstanceMemberships": True,+ "VpcId": "",+ "OptionGroupArn": arn,+ "SourceAccountId": "",+ "SourceOptionGroup": "",+ }++ req_tags = _parse_tags(p)+ if req_tags:+ _tags[arn] = req_tags++ og = _option_groups[name]+ return _xml(200, "CreateOptionGroupResponse",+ f"<CreateOptionGroupResult><OptionGroup>{_option_group_xml(og)}</OptionGroup></CreateOptionGroupResult>")+++def _delete_option_group(p):+ name = _p(p, "OptionGroupName")+ og = _option_groups.pop(name, None)+ if not og:+ return _error("OptionGroupNotFoundFault", f"Option group {name} not found.", 404)+ _tags.pop(og.get("OptionGroupArn", ""), None)+ return _xml(200, "DeleteOptionGroupResponse", "")+++def _describe_option_groups(p):+ name = _p(p, "OptionGroupName")+ engine = _p(p, "EngineName")+ major_version = _p(p, "MajorEngineVersion")++ if name:+ og = _option_groups.get(name)+ if not og:+ return _error("OptionGroupNotFoundFault", f"Option group {name} not found.", 404)+ groups = [og]+ else:+ groups = list(_option_groups.values())+ if engine:+ groups = [g for g in groups if g["EngineName"] == engine]+ if major_version:+ groups = [g for g in groups if g["MajorEngineVersion"] == major_version]++ members = "".join(+ f"<OptionGroup>{_option_group_xml(g)}</OptionGroup>" for g in groups)+ return _xml(200, "DescribeOptionGroupsResponse",+ f"<DescribeOptionGroupsResult><OptionGroupsList>{members}</OptionGroupsList></DescribeOptionGroupsResult>")+++def _describe_option_group_options(p):+ return _xml(200, "DescribeOptionGroupOptionsResponse",+ "<DescribeOptionGroupOptionsResult><OptionGroupOptions/></DescribeOptionGroupOptionsResult>")+++# ---------------------------------------------------------------------------+# Tags+# ---------------------------------------------------------------------------def _add_tags(p):+ arn = _p(p, "ResourceName")+ new_tags = _parse_tags(p)+ if not arn:+ return _error("MissingParameter", "ResourceName is required", 400)++ existing = _tags.get(arn, [])+ existing_keys = {t["Key"]: i for i, t in enumerate(existing)}+ for tag in new_tags:+ k = tag["Key"]+ if k in existing_keys:+ existing[existing_keys[k]] = tag+ else:+ existing.append(tag)+ existing_keys[k] = len(existing) - 1+ _tags[arn] = existing++ _sync_tag_list_to_resource(arn)return _xml(200, "AddTagsToResourceResponse", "")def _remove_tags(p):+ arn = _p(p, "ResourceName")+ keys_to_remove = set(_parse_member_list(p, "TagKeys"))+ if not arn:+ return _error("MissingParameter", "ResourceName is required", 400)++ existing = _tags.get(arn, [])+ _tags[arn] = [t for t in existing if t["Key"] not in keys_to_remove]++ _sync_tag_list_to_resource(arn)return _xml(200, "RemoveTagsFromResourceResponse", "")+def _list_tags(p):+ arn = _p(p, "ResourceName")+ if not arn:+ return _xml(200, "ListTagsForResourceResponse",+ "<ListTagsForResourceResult><TagList/></ListTagsForResourceResult>")++ tag_list = _tags.get(arn, [])+ members = "".join(f"<Tag><Key>{t['Key']}</Key><Value>{t['Value']}</Value></Tag>" for t in tag_list)+ return _xml(200, "ListTagsForResourceResponse",+ f"<ListTagsForResourceResult><TagList>{members}</TagList></ListTagsForResourceResult>")+++def _sync_tag_list_to_resource(arn):+ """Keep the embedded TagList on instances/clusters in sync with _tags."""+ tag_list = _tags.get(arn, [])+ for inst in _instances.values():+ if inst.get("DBInstanceArn") == arn:+ inst["TagList"] = list(tag_list)+ return+ for cl in _clusters.values():+ 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+++# ---------------------------------------------------------------------------+# Engine Versions & Orderable Options+# ---------------------------------------------------------------------------+def _describe_engine_versions(p):engine = _p(p, "Engine") or "postgres"- versions = {- "postgres": ["15.3", "14.8", "13.11", "12.15"],- "mysql": ["8.0.33", "8.0.28", "5.7.43"],- "mariadb": ["10.6.14", "10.5.21"],- "aurora-postgresql": ["15.3", "14.8"],- "aurora-mysql": ["8.0.mysql_aurora.3.03.0"],+ version_filter = _p(p, "EngineVersion")+ versions_map = {+ "postgres": [+ ("15.3", "15"), ("14.8", "14"), ("13.11", "13"), ("12.15", "12"),+ ],+ "mysql": [+ ("8.0.33", "8.0"), ("8.0.28", "8.0"), ("5.7.43", "5.7"),+ ],+ "mariadb": [+ ("10.6.14", "10.6"), ("10.5.21", "10.5"),+ ],+ "aurora-postgresql": [+ ("15.3", "aurora-postgresql15"), ("14.8", "aurora-postgresql14"),+ ],+ "aurora-mysql": [+ ("8.0.mysql_aurora.3.03.0", "aurora-mysql8.0"),+ ],}+ versions = versions_map.get(engine, [("15.3", "15")])members = ""- for v in versions.get(engine, ["15.3"]):- members += f"<member><Engine>{engine}</Engine><EngineVersion>{v}</EngineVersion><DBParameterGroupFamily>{engine}{v[:3]}</DBParameterGroupFamily><DBEngineDescription>{engine}</DBEngineDescription><DBEngineVersionDescription>{engine} {v}</DBEngineVersionDescription></member>"+ for ver, family in versions:+ if version_filter and ver != version_filter:+ continue+ members += f"""<DBEngineVersion>+ <Engine>{engine}</Engine>+ <EngineVersion>{ver}</EngineVersion>+ <DBParameterGroupFamily>{engine}{family}</DBParameterGroupFamily>+ <DBEngineDescription>{engine.replace('-', ' ').title()}</DBEngineDescription>+ <DBEngineVersionDescription>{engine} {ver}</DBEngineVersionDescription>+ <ValidUpgradeTarget/>+ <ExportableLogTypes/>+ <SupportsLogExportsToCloudwatchLogs>false</SupportsLogExportsToCloudwatchLogs>+ <SupportsReadReplica>true</SupportsReadReplica>+ <SupportedFeatureNames/>+ <Status>available</Status>+ <SupportsParallelQuery>false</SupportsParallelQuery>+ <SupportsGlobalDatabases>false</SupportsGlobalDatabases>+ <SupportsBabelfish>false</SupportsBabelfish>+ <SupportsCertificateRotationWithoutRestart>true</SupportsCertificateRotationWithoutRestart>+ </DBEngineVersion>"""return _xml(200, "DescribeDBEngineVersionsResponse",f"<DescribeDBEngineVersionsResult><DBEngineVersions>{members}</DBEngineVersions></DescribeDBEngineVersionsResult>")def _describe_orderable_options(p):+ engine = _p(p, "Engine") or "postgres"+ engine_version = _p(p, "EngineVersion")+ db_class = _p(p, "DBInstanceClass")++ instance_classes = [+ "db.t3.micro", "db.t3.small", "db.t3.medium", "db.t3.large",+ "db.r5.large", "db.r5.xlarge", "db.r5.2xlarge",+ "db.m5.large", "db.m5.xlarge", "db.m5.2xlarge",+ ]+ version = engine_version or _default_engine_version(engine)++ members = ""+ for cls in instance_classes:+ if db_class and cls != db_class:+ continue+ members += f"""<OrderableDBInstanceOption>+ <Engine>{engine}</Engine>+ <EngineVersion>{version}</EngineVersion>+ <DBInstanceClass>{cls}</DBInstanceClass>+ <LicenseModel>{_license_model(engine)}</LicenseModel>+ <AvailabilityZones>+ <AvailabilityZone><Name>{REGION}a</Name></AvailabilityZone>+ <AvailabilityZone><Name>{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>true</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>false</SupportsClusters>+ <SupportedActivityStreamModes/>+ </OrderableDBInstanceOption>"""return _xml(200, "DescribeOrderableDBInstanceOptionsResponse",- "<DescribeOrderableDBInstanceOptionsResult><OrderableDBInstanceOptions/></DescribeOrderableDBInstanceOptionsResult>")+ f"<DescribeOrderableDBInstanceOptionsResult><OrderableDBInstanceOptions>{members}</OrderableDBInstanceOptions></DescribeOrderableDBInstanceOptionsResult>")-# ---- XML helpers ----+# ---------------------------------------------------------------------------+# XML helpers+# ---------------------------------------------------------------------------def _instance_xml(i):+ """Render an instance dict to XML fields — no wrapping element."""ep = i.get("Endpoint", {})- return f"""<member>- <DBInstanceIdentifier>{i['DBInstanceIdentifier']}</DBInstanceIdentifier>+ subnet = i.get("DBSubnetGroup", {})++ vpc_sg_xml = ""+ for sg in i.get("VpcSecurityGroups", []):+ vpc_sg_xml += f"""<VpcSecurityGroupMembership>+ <VpcSecurityGroupId>{sg.get('VpcSecurityGroupId','')}</VpcSecurityGroupId>+ <Status>{sg.get('Status','active')}</Status>+ </VpcSecurityGroupMembership>"""++ db_sg_xml = ""+ for sg in i.get("DBSecurityGroups", []):+ db_sg_xml += f"""<DBSecurityGroup>+ <DBSecurityGroupName>{sg}</DBSecurityGroupName>+ <Status>active</Status>+ </DBSecurityGroup>"""++ param_xml = ""+ for pg in i.get("DBParameterGroups", []):+ param_xml += f"""<DBParameterGroup>+ <DBParameterGroupName>{pg.get('DBParameterGroupName','')}</DBParameterGroupName>+ <ParameterApplyStatus>{pg.get('ParameterApplyStatus','in-sync')}</ParameterApplyStatus>+ </DBParameterGroup>"""++ option_xml = ""+ for og in i.get("OptionGroupMemberships", []):+ option_xml += f"""<OptionGroupMembership>+ <OptionGroupName>{og.get('OptionGroupName','')}</OptionGroupName>+ <Status>{og.get('Status','in-sync')}</Status>+ </OptionGroupMembership>"""++ tag_xml = ""+ for t in i.get("TagList", []):+ tag_xml += f"<Tag><Key>{t['Key']}</Key><Value>{t['Value']}</Value></Tag>"++ read_replica_xml = ""+ for rr in i.get("ReadReplicaDBInstanceIdentifiers", []):+ read_replica_xml += f"<ReadReplicaDBInstanceIdentifier>{rr}</ReadReplicaDBInstanceIdentifier>"++ subnet_xml = ""+ for s in subnet.get("Subnets", []):+ az = s.get("SubnetAvailabilityZone", {}).get("Name", f"{REGION}a") if isinstance(s.get("SubnetAvailabilityZone"), dict) else f"{REGION}a"+ subnet_xml += f"""<Subnet>+ <SubnetIdentifier>{s.get('SubnetIdentifier','')}</SubnetIdentifier>+ <SubnetAvailabilityZone><Name>{az}</Name></SubnetAvailabilityZone>+ <SubnetOutpost/>+ <SubnetStatus>Active</SubnetStatus>+ </Subnet>"""++ pending_xml = ""+ for pk, pv in i.get("PendingModifiedValues", {}).items():+ pending_xml += f"<{pk}>{pv}</{pk}>"++ iops_xml = ""+ if i.get("Iops") is not None:+ iops_xml = f"<Iops>{i['Iops']}</Iops>"++ cert_xml = ""+ cert = i.get("CertificateDetails")+ if cert:+ cert_xml = f"""<CertificateDetails>+ <CAIdentifier>{cert.get('CAIdentifier','')}</CAIdentifier>+ <ValidTill>{cert.get('ValidTill','')}</ValidTill>+ </CertificateDetails>"""++ return f"""<DBInstanceIdentifier>{i['DBInstanceIdentifier']}</DBInstanceIdentifier><DBInstanceClass>{i['DBInstanceClass']}</DBInstanceClass><Engine>{i['Engine']}</Engine><EngineVersion>{i['EngineVersion']}</EngineVersion>@@ -398,32 +1489,415 @@ def _instance_xml(i):<Endpoint><Address>{ep.get('Address','localhost')}</Address><Port>{ep.get('Port',5432)}</Port>+ <HostedZoneId>{ep.get('HostedZoneId','Z2R2ITUGPM61AM')}</HostedZoneId></Endpoint><AllocatedStorage>{i['AllocatedStorage']}</AllocatedStorage>- <MultiAZ>{str(i['MultiAZ']).lower()}</MultiAZ>- <StorageType>{i['StorageType']}</StorageType>+ <InstanceCreateTime>{i.get('InstanceCreateTime','')}</InstanceCreateTime>+ <PreferredBackupWindow>{i.get('PreferredBackupWindow','03:00-04:00')}</PreferredBackupWindow>+ <BackupRetentionPeriod>{i.get('BackupRetentionPeriod',1)}</BackupRetentionPeriod>+ <DBSecurityGroups>{db_sg_xml}</DBSecurityGroups>+ <VpcSecurityGroups>{vpc_sg_xml}</VpcSecurityGroups>+ <DBParameterGroups>{param_xml}</DBParameterGroups>+ <AvailabilityZone>{i.get('AvailabilityZone',f'{REGION}a')}</AvailabilityZone>+ <DBSubnetGroup>+ <DBSubnetGroupName>{subnet.get('DBSubnetGroupName','default')}</DBSubnetGroupName>+ <DBSubnetGroupDescription>{subnet.get('DBSubnetGroupDescription','')}</DBSubnetGroupDescription>+ <VpcId>{subnet.get('VpcId','vpc-00000000')}</VpcId>+ <SubnetGroupStatus>{subnet.get('SubnetGroupStatus','Complete')}</SubnetGroupStatus>+ <Subnets>{subnet_xml}</Subnets>+ <DBSubnetGroupArn>{subnet.get('DBSubnetGroupArn','')}</DBSubnetGroupArn>+ </DBSubnetGroup>+ <PreferredMaintenanceWindow>{i.get('PreferredMaintenanceWindow','sun:05:00-sun:06:00')}</PreferredMaintenanceWindow>+ <PendingModifiedValues>{pending_xml}</PendingModifiedValues>+ <LatestRestorableTime>{i.get('LatestRestorableTime','')}</LatestRestorableTime>+ <MultiAZ>{str(i.get('MultiAZ',False)).lower()}</MultiAZ>+ <AutoMinorVersionUpgrade>{str(i.get('AutoMinorVersionUpgrade',True)).lower()}</AutoMinorVersionUpgrade>+ <ReadReplicaDBInstanceIdentifiers>{read_replica_xml}</ReadReplicaDBInstanceIdentifiers>+ <ReadReplicaSourceDBInstanceIdentifier>{i.get('ReadReplicaSourceDBInstanceIdentifier','')}</ReadReplicaSourceDBInstanceIdentifier>+ <ReadReplicaDBClusterIdentifiers/>+ <ReplicaMode>{i.get('ReplicaMode','')}</ReplicaMode>+ <LicenseModel>{i.get('LicenseModel','general-public-license')}</LicenseModel>+ {iops_xml}+ <OptionGroupMemberships>{option_xml}</OptionGroupMemberships>+ <PubliclyAccessible>{str(i.get('PubliclyAccessible',False)).lower()}</PubliclyAccessible>+ <StatusInfos/>+ <StorageType>{i.get('StorageType','gp2')}</StorageType>+ <DbInstancePort>{i.get('DbInstancePort',0)}</DbInstancePort>+ <DBClusterIdentifier>{i.get('DBClusterIdentifier','')}</DBClusterIdentifier>+ <StorageEncrypted>{str(i.get('StorageEncrypted',False)).lower()}</StorageEncrypted>+ <KmsKeyId>{i.get('KmsKeyId','')}</KmsKeyId>+ <DbiResourceId>{i.get('DbiResourceId','')}</DbiResourceId>+ <CACertificateIdentifier>{i.get('CACertificateIdentifier','rds-ca-rsa2048-g1')}</CACertificateIdentifier>+ <DomainMemberships/>+ <CopyTagsToSnapshot>{str(i.get('CopyTagsToSnapshot',False)).lower()}</CopyTagsToSnapshot>+ <MonitoringInterval>{i.get('MonitoringInterval',0)}</MonitoringInterval>+ <EnhancedMonitoringResourceArn>{i.get('EnhancedMonitoringResourceArn','')}</EnhancedMonitoringResourceArn>+ <MonitoringRoleArn>{i.get('MonitoringRoleArn','')}</MonitoringRoleArn>+ <PromotionTier>{i.get('PromotionTier',1)}</PromotionTier><DBInstanceArn>{i['DBInstanceArn']}</DBInstanceArn>- </member>"""+ <IAMDatabaseAuthenticationEnabled>{str(i.get('IAMDatabaseAuthenticationEnabled',False)).lower()}</IAMDatabaseAuthenticationEnabled>+ <PerformanceInsightsEnabled>{str(i.get('PerformanceInsightsEnabled',False)).lower()}</PerformanceInsightsEnabled>+ <EnabledCloudwatchLogsExports/>+ <ProcessorFeatures/>+ <DeletionProtection>{str(i.get('DeletionProtection',False)).lower()}</DeletionProtection>+ <AssociatedRoles/>+ <MaxAllocatedStorage>{i.get('MaxAllocatedStorage',i.get('AllocatedStorage',20))}</MaxAllocatedStorage>+ <TagList>{tag_xml}</TagList>+ {cert_xml}+ <CustomerOwnedIpEnabled>{str(i.get('CustomerOwnedIpEnabled',False)).lower()}</CustomerOwnedIpEnabled>+ <BackupTarget>{i.get('BackupTarget','region')}</BackupTarget>+ <NetworkType>{i.get('NetworkType','IPV4')}</NetworkType>+ <StorageThroughput>{i.get('StorageThroughput',0)}</StorageThroughput>+ <IsStorageConfigUpgradeAvailable>{str(i.get('IsStorageConfigUpgradeAvailable',False)).lower()}</IsStorageConfigUpgradeAvailable>"""def _cluster_xml(c):+ """Render a cluster dict to XML fields."""+ vpc_sg_xml = ""+ for sg in c.get("VpcSecurityGroups", []):+ vpc_sg_xml += f"""<VpcSecurityGroupMembership>+ <VpcSecurityGroupId>{sg.get('VpcSecurityGroupId','')}</VpcSecurityGroupId>+ <Status>{sg.get('Status','active')}</Status>+ </VpcSecurityGroupMembership>"""++ member_xml = ""+ for m in c.get("DBClusterMembers", []):+ member_xml += f"""<DBClusterMember>+ <DBInstanceIdentifier>{m.get('DBInstanceIdentifier','')}</DBInstanceIdentifier>+ <IsClusterWriter>{str(m.get('IsClusterWriter',True)).lower()}</IsClusterWriter>+ <DBClusterParameterGroupStatus>in-sync</DBClusterParameterGroupStatus>+ <PromotionTier>{m.get('PromotionTier',1)}</PromotionTier>+ </DBClusterMember>"""++ az_xml = ""+ for az in c.get("AvailabilityZones", []):+ az_xml += f"<AvailabilityZone>{az}</AvailabilityZone>"++ tag_xml = ""+ for t in c.get("TagList", []):+ tag_xml += f"<Tag><Key>{t['Key']}</Key><Value>{t['Value']}</Value></Tag>"+return f"""<DBClusterIdentifier>{c['DBClusterIdentifier']}</DBClusterIdentifier><DBClusterArn>{c['DBClusterArn']}</DBClusterArn><Engine>{c['Engine']}</Engine><EngineVersion>{c['EngineVersion']}</EngineVersion>+ <EngineMode>{c.get('EngineMode','provisioned')}</EngineMode><Status>{c['Status']}</Status>- <Endpoint>{c['Endpoint']}</Endpoint>- <ReaderEndpoint>{c['ReaderEndpoint']}</ReaderEndpoint>- <Port>{c['Port']}</Port>"""---def _xml_instance_response(root_tag, result_tag, instance):- return _xml(200, root_tag, f"<{result_tag}><DBInstance>{_instance_xml(instance)}</DBInstance></{result_tag}>")-+ <MasterUsername>{c.get('MasterUsername','admin')}</MasterUsername>+ <DatabaseName>{c.get('DatabaseName','')}</DatabaseName>+ <Endpoint>{c.get('Endpoint','')}</Endpoint>+ <ReaderEndpoint>{c.get('ReaderEndpoint','')}</ReaderEndpoint>+ <Port>{c['Port']}</Port>+ <MultiAZ>{str(c.get('MultiAZ',False)).lower()}</MultiAZ>+ <AvailabilityZones>{az_xml}</AvailabilityZones>+ <DBClusterMembers>{member_xml}</DBClusterMembers>+ <VpcSecurityGroups>{vpc_sg_xml}</VpcSecurityGroups>+ <DBSubnetGroup>{c.get('DBSubnetGroup','default')}</DBSubnetGroup>+ <DBClusterParameterGroup>{c.get('DBClusterParameterGroup','')}</DBClusterParameterGroup>+ <BackupRetentionPeriod>{c.get('BackupRetentionPeriod',1)}</BackupRetentionPeriod>+ <PreferredBackupWindow>{c.get('PreferredBackupWindow','03:00-04:00')}</PreferredBackupWindow>+ <PreferredMaintenanceWindow>{c.get('PreferredMaintenanceWindow','sun:05:00-sun:06:00')}</PreferredMaintenanceWindow>+ <ClusterCreateTime>{c.get('ClusterCreateTime','')}</ClusterCreateTime>+ <EarliestRestorableTime>{c.get('EarliestRestorableTime','')}</EarliestRestorableTime>+ <LatestRestorableTime>{c.get('LatestRestorableTime','')}</LatestRestorableTime>+ <StorageEncrypted>{str(c.get('StorageEncrypted',False)).lower()}</StorageEncrypted>+ <KmsKeyId>{c.get('KmsKeyId','')}</KmsKeyId>+ <DeletionProtection>{str(c.get('DeletionProtection',False)).lower()}</DeletionProtection>+ <IAMDatabaseAuthenticationEnabled>{str(c.get('IAMDatabaseAuthenticationEnabled',False)).lower()}</IAMDatabaseAuthenticationEnabled>+ <HttpEndpointEnabled>{str(c.get('HttpEndpointEnabled',False)).lower()}</HttpEndpointEnabled>+ <CopyTagsToSnapshot>{str(c.get('CopyTagsToSnapshot',False)).lower()}</CopyTagsToSnapshot>+ <CrossAccountClone>{str(c.get('CrossAccountClone',False)).lower()}</CrossAccountClone>+ <DbClusterResourceId>{c.get('DbClusterResourceId','')}</DbClusterResourceId>+ <HostedZoneId>{c.get('HostedZoneId','Z2R2ITUGPM61AM')}</HostedZoneId>+ <AssociatedRoles/>+ <TagList>{tag_xml}</TagList>+ <AllocatedStorage>{c.get('AllocatedStorage',1)}</AllocatedStorage>+ <ActivityStreamStatus>{c.get('ActivityStreamStatus','stopped')}</ActivityStreamStatus>"""+++def _snapshot_xml(s):+ tag_xml = ""+ for t in s.get("TagList", []):+ tag_xml += f"<Tag><Key>{t['Key']}</Key><Value>{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'{REGION}a')}</AvailabilityZone>+ <VpcId>{s.get('VpcId','vpc-00000000')}</VpcId>+ <Port>{s.get('Port',5432)}</Port>+ <MasterUsername>{s.get('MasterUsername','admin')}</MasterUsername>+ <DBName>{s.get('DBName','')}</DBName>+ <SnapshotType>{s.get('SnapshotType','manual')}</SnapshotType>+ <LicenseModel>{s.get('LicenseModel','general-public-license')}</LicenseModel>+ <StorageType>{s.get('StorageType','gp2')}</StorageType>+ <DBInstanceClass>{s.get('DBInstanceClass','db.t3.micro')}</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 _subnet_group_xml(sg):+ subnets_xml = ""+ for s in sg.get("Subnets", []):+ az = s.get("SubnetAvailabilityZone", {}).get("Name", f"{REGION}a") if isinstance(s.get("SubnetAvailabilityZone"), dict) else f"{REGION}a"+ subnets_xml += f"""<Subnet>+ <SubnetIdentifier>{s.get('SubnetIdentifier','')}</SubnetIdentifier>+ <SubnetAvailabilityZone><Name>{az}</Name></SubnetAvailabilityZone>+ <SubnetOutpost/>+ <SubnetStatus>Active</SubnetStatus>+ </Subnet>"""+ return f"""<DBSubnetGroupName>{sg['DBSubnetGroupName']}</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>"""+++def _cluster_snapshot_xml(s):+ tag_xml = ""+ for t in s.get("TagList", []):+ tag_xml += f"<Tag><Key>{t['Key']}</Key><Value>{t['Value']}</Value></Tag>"+ az_xml = ""+ for az in s.get("AvailabilityZones", []):+ az_xml += f"<AvailabilityZone>{az}</AvailabilityZone>"+ return f"""<DBClusterSnapshotIdentifier>{s['DBClusterSnapshotIdentifier']}</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',5432)}</Port>+ <VpcId>{s.get('VpcId','vpc-00000000')}</VpcId>+ <MasterUsername>{s.get('MasterUsername','admin')}</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','postgresql-license')}</LicenseModel>+ <DbClusterResourceId>{s.get('DbClusterResourceId','')}</DbClusterResourceId>+ <IAMDatabaseAuthenticationEnabled>{str(s.get('IAMDatabaseAuthenticationEnabled',False)).lower()}</IAMDatabaseAuthenticationEnabled>+ <AllocatedStorage>{s.get('AllocatedStorage',1)}</AllocatedStorage>+ <TagList>{tag_xml}</TagList>"""+++def _option_group_xml(og):+ options_xml = ""+ for opt in og.get("Options", []):+ options_xml += f"<Option><OptionName>{opt.get('OptionName','')}</OptionName></Option>"+ return f"""<OptionGroupName>{og['OptionGroupName']}</OptionGroupName>+ <OptionGroupDescription>{og.get('OptionGroupDescription','')}</OptionGroupDescription>+ <EngineName>{og.get('EngineName','')}</EngineName>+ <MajorEngineVersion>{og.get('MajorEngineVersion','')}</MajorEngineVersion>+ <Options>{options_xml}</Options>+ <AllowsVpcAndNonVpcInstanceMemberships>{str(og.get('AllowsVpcAndNonVpcInstanceMemberships',True)).lower()}</AllowsVpcAndNonVpcInstanceMemberships>+ <VpcId>{og.get('VpcId','')}</VpcId>+ <OptionGroupArn>{og.get('OptionGroupArn','')}</OptionGroupArn>"""+++def _single_instance_response(root_tag, result_tag, instance):+ return _xml(200, root_tag,+ f"<{result_tag}><DBInstance>{_instance_xml(instance)}</DBInstance></{result_tag}>")+++# ---------------------------------------------------------------------------+# Generic helpers+# ---------------------------------------------------------------------------def _p(params, key, default=""):val = params.get(key, [default])- return val[0] if isinstance(val, list) else val+ if isinstance(val, list):+ return val[0] if val else default+ return val+++def _parse_tags(params):+ """Parse Tags.member.N.Key / Tags.member.N.Value or Tags.Tag.N.Key / Tags.Tag.N.Value."""+ tags = []+ prefix = "Tags.member"+ if not _p(params, "Tags.member.1.Key"):+ prefix = "Tags.Tag"+ i = 1+ while True:+ key = _p(params, f"{prefix}.{i}.Key")+ if not key:+ break+ value = _p(params, f"{prefix}.{i}.Value", "")+ tags.append({"Key": key, "Value": value})+ i += 1+ return tags+++def _parse_member_list(params, prefix):+ """Parse Prefix.member.N style lists from query params."""+ items = []+ i = 1+ while True:+ val = _p(params, f"{prefix}.member.{i}")+ if not val:+ break+ items.append(val)+ i += 1+ return items+++def _parse_filters(params):+ """Parse Filters.member.N.Name / Filters.member.N.Values.member.M."""+ filters = {}+ i = 1+ while True:+ name = _p(params, f"Filters.member.{i}.Name")+ if not name:+ break+ values = []+ j = 1+ while True:+ v = _p(params, f"Filters.member.{i}.Values.member.{j}")+ if not v:+ break+ values.append(v)+ j += 1+ filters[name] = values+ i += 1+ return filters+++def _apply_instance_filters(instances, filters):+ result = []+ for inst in instances:+ match = True+ for fname, fvals in filters.items():+ if fname == "db-instance-id":+ if inst["DBInstanceIdentifier"] not in fvals:+ match = False+ elif fname == "engine":+ if inst["Engine"] not in fvals:+ match = False+ elif fname == "db-cluster-id":+ if inst.get("DBClusterIdentifier", "") not in fvals:+ match = False+ if match:+ result.append(inst)+ return result+++def _apply_cluster_filters(clusters, filters):+ result = []+ for cl in clusters:+ match = True+ for fname, fvals in filters.items():+ if fname == "db-cluster-id":+ if cl["DBClusterIdentifier"] not in fvals:+ match = False+ elif fname == "engine":+ if cl["Engine"] not in fvals:+ match = False+ if match:+ result.append(cl)+ return result+++def _format_time(ts):+ import datetime+ dt = datetime.datetime.fromtimestamp(ts, tz=datetime.timezone.utc)+ return dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+++def _default_engine_version(engine):+ defaults = {+ "postgres": "15.3", "mysql": "8.0.33", "mariadb": "10.6.14",+ "aurora-postgresql": "15.3", "aurora-mysql": "8.0.mysql_aurora.3.03.0",+ }+ return defaults.get(engine, "15.3")+++def _default_port(engine):+ if "mysql" in engine or "mariadb" in engine or "aurora-mysql" in engine:+ return "3306"+ return "5432"+++def _license_model(engine):+ if "postgres" in engine or "aurora" in engine:+ return "postgresql-license"+ return "general-public-license"+++def _docker_image_for_engine(engine, engine_version, user, password, db_name):+ """Return (image, env_dict, container_port) or (None, None, None)."""+ if "postgres" in engine or "aurora-postgresql" in engine:+ major = engine_version.split(".")[0]+ return (+ f"postgres:{major}-alpine",+ {"POSTGRES_USER": user, "POSTGRES_PASSWORD": password, "POSTGRES_DB": db_name},+ 5432,+ )+ if "mysql" in engine or "aurora-mysql" in engine:+ return (+ "mysql:8",+ {"MYSQL_ROOT_PASSWORD": password, "MYSQL_DATABASE": db_name,+ "MYSQL_USER": user, "MYSQL_PASSWORD": password},+ 3306,+ )+ if "mariadb" in engine:+ return (+ "mariadb:latest",+ {"MYSQL_ROOT_PASSWORD": password, "MYSQL_DATABASE": db_name,+ "MYSQL_USER": user, "MYSQL_PASSWORD": password},+ 3306,+ )+ return None, None, None+++def _default_parameters_for_family(family):+ """Return a minimal set of parameter definitions for DescribeDBParameters."""+ base = [+ {"name": "max_connections", "default": "100", "description": "Max number of connections",+ "apply_type": "dynamic", "data_type": "integer", "modifiable": True},+ {"name": "shared_buffers", "default": "128MB", "description": "Shared memory buffers",+ "apply_type": "static", "data_type": "string", "modifiable": True},+ {"name": "work_mem", "default": "4MB", "description": "Memory for internal sort ops",+ "apply_type": "dynamic", "data_type": "string", "modifiable": True},+ {"name": "maintenance_work_mem", "default": "64MB", "description": "Memory for maintenance ops",+ "apply_type": "dynamic", "data_type": "string", "modifiable": True},+ {"name": "effective_cache_size", "default": "4GB", "description": "Planner effective cache size",+ "apply_type": "dynamic", "data_type": "string", "modifiable": True},+ {"name": "log_statement", "default": "none", "description": "Type of statements logged",+ "apply_type": "dynamic", "data_type": "string", "modifiable": True},+ {"name": "log_min_duration_statement", "default": "-1", "description": "Min duration before logging",+ "apply_type": "dynamic", "data_type": "integer", "modifiable": True},+ ]+ if "mysql" in family.lower():+ base = [+ {"name": "max_connections", "default": "151", "description": "Max number of connections",+ "apply_type": "dynamic", "data_type": "integer", "modifiable": True},+ {"name": "innodb_buffer_pool_size", "default": "134217728", "description": "InnoDB buffer pool size",+ "apply_type": "static", "data_type": "integer", "modifiable": True},+ {"name": "character_set_server", "default": "utf8mb4", "description": "Server character set",+ "apply_type": "dynamic", "data_type": "string", "modifiable": True},+ {"name": "slow_query_log", "default": "0", "description": "Enable slow query log",+ "apply_type": "dynamic", "data_type": "boolean", "modifiable": True},+ {"name": "long_query_time", "default": "10", "description": "Slow query threshold",+ "apply_type": "dynamic", "data_type": "float", "modifiable": True},+ ]+ return basedef _xml(status, root_tag, inner):@@ -442,3 +1916,67 @@ def _error(code, message, status):<RequestId>{new_uuid()}</RequestId></ErrorResponse>""".encode("utf-8")return status, {"Content-Type": "application/xml"}, body+++# ---------------------------------------------------------------------------+# Action map+# ---------------------------------------------------------------------------++_ACTION_MAP = {+ "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,+ "CreateDBInstanceReadReplica": _create_read_replica,+ "RestoreDBInstanceFromDBSnapshot": _restore_from_snapshot,+ "CreateDBCluster": _create_db_cluster,+ "DeleteDBCluster": _delete_db_cluster,+ "DescribeDBClusters": _describe_db_clusters,+ "ModifyDBCluster": _modify_db_cluster,+ "StartDBCluster": _start_db_cluster,+ "StopDBCluster": _stop_db_cluster,+ "CreateDBSnapshot": _create_db_snapshot,+ "DeleteDBSnapshot": _delete_db_snapshot,+ "DescribeDBSnapshots": _describe_db_snapshots,+ "CreateDBClusterSnapshot": _create_db_cluster_snapshot,+ "DescribeDBClusterSnapshots": _describe_db_cluster_snapshots,+ "DeleteDBClusterSnapshot": _delete_db_cluster_snapshot,+ "CreateDBSubnetGroup": _create_subnet_group,+ "DeleteDBSubnetGroup": _delete_subnet_group,+ "DescribeDBSubnetGroups": _describe_subnet_groups,+ "ModifyDBSubnetGroup": _modify_subnet_group,+ "CreateDBParameterGroup": _create_param_group,+ "DeleteDBParameterGroup": _delete_param_group,+ "DescribeDBParameterGroups": _describe_param_groups,+ "DescribeDBParameters": _describe_db_parameters,+ "ModifyDBParameterGroup": _modify_param_group,+ "CreateDBClusterParameterGroup": _create_db_cluster_param_group,+ "DescribeDBClusterParameterGroups": _describe_db_cluster_param_groups,+ "DeleteDBClusterParameterGroup": _delete_db_cluster_param_group,+ "DescribeDBClusterParameters": _describe_db_cluster_parameters,+ "ModifyDBClusterParameterGroup": _modify_db_cluster_param_group,+ "CreateOptionGroup": _create_option_group,+ "DeleteOptionGroup": _delete_option_group,+ "DescribeOptionGroups": _describe_option_groups,+ "DescribeOptionGroupOptions": _describe_option_group_options,+ "ListTagsForResource": _list_tags,+ "AddTagsToResource": _add_tags,+ "RemoveTagsFromResource": _remove_tags,+ "DescribeDBEngineVersions": _describe_engine_versions,+ "DescribeOrderableDBInstanceOptions": _describe_orderable_options,+}+++def reset():+ _instances.clear()+ _clusters.clear()+ _subnet_groups.clear()+ _param_groups.clear()+ _snapshots.clear()+ _db_cluster_param_groups.clear()+ _db_cluster_snapshots.clear()+ _option_groups.clear()+ _tags.clear()diff --git a/services/s3.py b/services/s3.pyindex cf73e9a5..cba86447 100644--- a/services/s3.py+++ b/services/s3.py@@ -1,127 +1,441 @@"""-S3 Service Emulator.+S3 Service Emulator – AWS-compatible.Supports: CreateBucket, DeleteBucket, ListBuckets, HeadBucket,PutObject, GetObject, DeleteObject, HeadObject, CopyObject,- ListObjects (v1 & v2), DeleteObjects (batch).-Storage: In-memory (optionally backed by /tmp/localstack-data/s3/).+ ListObjectsV1 (with Marker/NextMarker pagination),+ ListObjectsV2 (with ContinuationToken pagination),+ DeleteObjects (batch),+ Multipart Upload (Create, UploadPart, Complete, Abort, List, ListParts),+ Object Tagging (Get, Put, Delete),+ ListObjectVersions,+ Bucket sub-resources (Policy, Versioning, Encryption, Lifecycle,+ CORS, ACL, Tagging, Notification, Logging, Accelerate, RequestPayment,+ Website),+ Range requests (206 Partial Content),+ Content-MD5 validation, encoding-type=url,+ x-amz-metadata-directive, x-amz-copy-source-if-match preconditions.+Storage: In-memory (optionally backed by S3_DATA_DIR)."""import osimport re+import base64+import hashlib+import jsonimport logging-from datetime import datetime, timezone-from collections import defaultdict+import threading+import time+from urllib.parse import quote as url_quote, unquote as url_unquotefrom xml.etree.ElementTree import Element, SubElement, tostring, fromstring-from core.responses import md5_hash, sha256_hash, now_iso, new_uuid+from core.responses import md5_hash, sha256_hash, now_iso, new_uuid, iso_to_rfc7231logger = logging.getLogger("s3")+S3_NS = "http://s3.amazonaws.com/doc/2006-03-01/"+XML_DECL = b'<?xml version="1.0" encoding="UTF-8"?>'++# ---------------------------------------------------------------------------# In-memory storage-_buckets: dict = {} # bucket_name -> {"created": iso_str, "objects": {key: {"body": bytes, "metadata": dict, "content_type": str, "etag": str, "last_modified": str, "size": int}}}+# ---------------------------------------------------------------------------+_buckets: dict = {}++_bucket_policies: dict = {}+_bucket_notifications: dict = {}+_bucket_tags: dict = {}+_bucket_versioning: dict = {}+_bucket_encryption: dict = {}+_bucket_lifecycle: dict = {}+_bucket_cors: dict = {}+_bucket_acl: dict = {}+_bucket_websites: dict = {}+_bucket_logging_config: dict = {}+_bucket_accelerate_config: dict = {}+_bucket_request_payment_config: dict = {}++_object_tags: dict = {}++_multipart_uploads: dict = {}DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/localstack-data/s3")PERSIST = os.environ.get("S3_PERSIST", "0") == "1"+# Headers preserved from PUT requests and returned on GET/HEAD.+_PRESERVED_HEADERS = (+ "cache-control",+ "content-disposition",+ "content-language",+ "expires",+)-def _ensure_bucket(name):- if name not in _buckets:- return None- return _buckets[name]+# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++_BUCKET_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9.\-]{1,61}[a-z0-9]$")+_IP_RE = re.compile(r"^\d{1,3}(\.\d{1,3}){3}$")+++def _qp(params: dict, key: str, default: str = "") -> str:+ val = params.get(key, [default])+ if isinstance(val, list):+ return val[0] if val else default+ return val+++def _xml_body(root: Element) -> bytes:+ return XML_DECL + b"\n" + tostring(root, encoding="unicode").encode("utf-8")+++def _error(code: str, message: str, status: int, resource: str = "") -> tuple:+ root = Element("Error")+ SubElement(root, "Code").text = code+ SubElement(root, "Message").text = message+ SubElement(root, "Resource").text = resource+ SubElement(root, "RequestId").text = new_uuid()+ return status, {"Content-Type": "application/xml"}, _xml_body(root)+++def _ensure_bucket(name: str):+ return _buckets.get(name)+++def _no_such_bucket(name: str) -> tuple:+ return _error("NoSuchBucket", "The specified bucket does not exist", 404, f"/{name}")+++def _validate_bucket_name(name: str) -> bool:+ if not name or len(name) < 3 or len(name) > 63:+ return False+ if not _BUCKET_NAME_RE.match(name):+ return False+ if ".." in name:+ return False+ if _IP_RE.match(name):+ return False+ return True+++def _url_encode(value: str) -> str:+ return url_quote(value, safe="")def _parse_bucket_key(path: str, headers: dict):- """Extract bucket name and key from path or Host header."""host = headers.get("host", "")-- # Virtual-hosted style: bucket.s3.localhost:4566vhost_match = re.match(r"^([a-zA-Z0-9.\-_]+)\.s3[\.\-]", host)if vhost_match:bucket = vhost_match.group(1)key = path.lstrip("/")return bucket, key-- # Path style: /bucket/keyparts = path.lstrip("/").split("/", 1)bucket = parts[0] if parts else ""key = parts[1] if len(parts) > 1 else ""return bucket, key+def _parse_range(range_header: str, total: int):+ m = re.match(r"bytes=(\d*)-(\d*)", range_header)+ if not m:+ return None+ s, e = m.group(1), m.group(2)+ if s == "" and e == "":+ return None+ if s == "":+ suffix = int(e)+ if suffix == 0:+ return None+ start = max(0, total - suffix)+ return start, total - 1+ start = int(s)+ if start >= total:+ return None+ end = int(e) if e else total - 1+ end = min(end, total - 1)+ if start > end:+ return None+ return start, end+++def _validate_content_md5(headers: dict, body: bytes):+ md5_header = headers.get("content-md5", "")+ if not md5_header:+ return None+ try:+ expected = base64.b64decode(md5_header)+ except Exception:+ return _error("InvalidDigest", "The Content-MD5 you specified is not valid.", 400)+ actual = hashlib.md5(body).digest()+ if expected != actual:+ return _error(+ "BadDigest",+ "The Content-MD5 you specified did not match what we received.",+ 400,+ )+ return None+++def _find_xml_tag(parent, tag_name, ns=S3_NS):+ el = parent.find("{%s}%s" % (ns, tag_name))+ if el is None:+ el = parent.find(tag_name)+ return el+++def _parse_tags_xml(body: bytes) -> dict:+ xml_root = fromstring(body)+ tags = {}+ for tag_el in xml_root.iter():+ local = tag_el.tag.split("}")[-1] if "}" in tag_el.tag else tag_el.tag+ if local == "Tag":+ key_text = val_text = None+ for child in tag_el:+ child_local = child.tag.split("}")[-1] if "}" in child.tag else child.tag+ if child_local == "Key":+ key_text = child.text+ elif child_local == "Value":+ val_text = child.text+ if key_text is not None:+ tags[key_text] = val_text or ""+ return tags+++def _extract_user_metadata(headers: dict) -> dict:+ meta = {}+ for k, v in headers.items():+ if k.lower().startswith("x-amz-meta-"):+ meta[k] = v+ return meta+++def _build_object_record(body: bytes, headers: dict) -> dict:+ content_type = headers.get("content-type", "application/octet-stream")+ content_encoding = headers.get("content-encoding")+ preserved = {}+ for h in _PRESERVED_HEADERS:+ val = headers.get(h)+ if val is not None:+ preserved[h] = val++ return {+ "body": body,+ "content_type": content_type,+ "content_encoding": content_encoding,+ "etag": f'"{md5_hash(body)}"',+ "last_modified": now_iso(),+ "size": len(body),+ "metadata": _extract_user_metadata(headers),+ "preserved_headers": preserved,+ }+++def _object_response_headers(obj: dict) -> dict:+ h = {+ "Content-Type": obj["content_type"],+ "ETag": obj["etag"],+ "Last-Modified": iso_to_rfc7231(obj["last_modified"]),+ "Content-Length": str(obj["size"]),+ "Accept-Ranges": "bytes",+ }+ if obj.get("content_encoding"):+ h["Content-Encoding"] = obj["content_encoding"]+ for key, val in obj.get("preserved_headers", {}).items():+ h[key] = val+ h.update(obj.get("metadata", {}))+ return h+++# ---------------------------------------------------------------------------+# Request router+# ---------------------------------------------------------------------------+async def handle_request(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:- """Route S3 requests to handlers."""bucket, key = _parse_bucket_key(path, headers)- # ListBuckets: GET /- if method == "GET" and not bucket:- return _list_buckets()+ result = _dispatch(method, bucket, key, headers, body, query_params)- # Batch delete: POST /?delete- if method == "POST" and "delete" in query_params:- return _delete_objects(bucket, body)+ status, resp_headers, resp_body = result+ resp_headers.setdefault("x-amz-request-id", new_uuid())+ resp_headers.setdefault("x-amz-id-2", new_uuid())- # ListObjects v2: GET /bucket?list-type=2- if method == "GET" and not key and query_params.get("list-type", [""])[0] == "2":- return _list_objects_v2(bucket, query_params)+ # HEAD responses must not carry a body per HTTP/1.1 spec.+ if method == "HEAD":+ resp_body = b""- # ListObjects v1: GET /bucket- if method == "GET" and not key:+ return status, resp_headers, resp_body+++def _dispatch(method: str, bucket: str, key: str, headers: dict, body: bytes, query_params: dict) -> tuple:+ if method == "GET" and not bucket:+ return _list_buckets()++ # ---- Routes with key ----+ if key:+ if method == "GET":+ if "uploadId" in query_params:+ return _list_parts(bucket, key, query_params)+ if "tagging" in query_params:+ return _get_object_tagging(bucket, key)+ return _get_object(bucket, key, headers)++ if method == "PUT":+ if "partNumber" in query_params and "uploadId" in query_params:+ return _upload_part(bucket, key, body, query_params, headers)+ if "tagging" in query_params:+ return _put_object_tagging(bucket, key, body)+ if "x-amz-copy-source" in headers:+ return _copy_object(bucket, key, headers)+ return _put_object(bucket, key, body, headers)++ if method == "POST":+ if "uploads" in query_params:+ return _create_multipart_upload(bucket, key, headers)+ if "uploadId" in query_params:+ return _complete_multipart_upload(bucket, key, body, query_params)+ return _error("MethodNotAllowed", "The specified method is not allowed against this resource.", 405)++ if method == "HEAD":+ return _head_object(bucket, key)++ if method == "DELETE":+ if "uploadId" in query_params:+ return _abort_multipart_upload(bucket, key, query_params)+ if "tagging" in query_params:+ return _delete_object_tagging(bucket, key)+ return _delete_object(bucket, key)++ return _error("MethodNotAllowed", "The specified method is not allowed against this resource.", 405)++ # ---- Routes without key (bucket-level) ----+ if not bucket:+ return _error("MethodNotAllowed", "The specified method is not allowed against this resource.", 405)++ if method == "GET":+ if "uploads" in query_params:+ return _list_multipart_uploads(bucket, query_params)+ if "versions" in query_params:+ return _list_object_versions(bucket, query_params)+ if "list-type" in query_params and _qp(query_params, "list-type") == "2":+ return _list_objects_v2(bucket, query_params)if "location" in query_params:return _get_bucket_location(bucket)+ if "policy" in query_params:+ return _get_bucket_policy(bucket)+ if "versioning" in query_params:+ return _get_bucket_versioning(bucket)+ if "encryption" in query_params:+ return _get_bucket_encryption(bucket)+ if "logging" in query_params:+ return _get_bucket_logging(bucket)+ if "notification" in query_params:+ return _get_bucket_notification(bucket)+ if "tagging" in query_params:+ return _get_bucket_tagging(bucket)+ if "cors" in query_params:+ return _get_bucket_cors(bucket)+ if "acl" in query_params:+ return _get_bucket_acl(bucket)+ if "lifecycle" in query_params:+ return _get_bucket_lifecycle(bucket)+ if "accelerate" in query_params:+ return _get_bucket_accelerate(bucket)+ if "request-payment" in query_params:+ return _get_bucket_request_payment(bucket)+ if "website" in query_params:+ return _get_bucket_website(bucket)return _list_objects_v1(bucket, query_params)- # CreateBucket: PUT /bucket (no key)- if method == "PUT" and bucket and not key:+ if method == "PUT":+ if "policy" in query_params:+ return _put_bucket_policy(bucket, body)+ if "notification" in query_params:+ return _put_bucket_notification(bucket, body)+ if "tagging" in query_params:+ return _put_bucket_tagging(bucket, body)+ if "versioning" in query_params:+ return _put_bucket_versioning(bucket, body)+ if "encryption" in query_params:+ return _put_bucket_encryption(bucket, body)+ if "lifecycle" in query_params:+ return _put_bucket_lifecycle(bucket, body)+ if "cors" in query_params:+ return _put_bucket_cors(bucket, body)+ if "acl" in query_params:+ return _put_bucket_acl(bucket, body)+ if "website" in query_params:+ return _put_bucket_website(bucket, body)+ if "logging" in query_params:+ return _put_bucket_logging(bucket, body)+ if "accelerate" in query_params:+ return _put_bucket_accelerate(bucket, body)+ if "requestPayment" in query_params:+ return _put_bucket_request_payment(bucket, body)return _create_bucket(bucket, body)- # DeleteBucket: DELETE /bucket (no key)- if method == "DELETE" and bucket and not key:+ if method == "DELETE":+ if "policy" in query_params:+ return _delete_bucket_policy(bucket)+ if "tagging" in query_params:+ return _delete_bucket_tagging(bucket)+ if "cors" in query_params:+ return _delete_bucket_cors(bucket)+ if "lifecycle" in query_params:+ return _delete_bucket_lifecycle(bucket)+ if "encryption" in query_params:+ return _delete_bucket_encryption(bucket)+ if "website" in query_params:+ return _delete_bucket_website(bucket)return _delete_bucket(bucket)- # HeadBucket: HEAD /bucket- if method == "HEAD" and bucket and not key:+ if method == "HEAD":return _head_bucket(bucket)- # PutObject: PUT /bucket/key- if method == "PUT" and key:- # CopyObject: has x-amz-copy-source- if "x-amz-copy-source" in headers:- return _copy_object(bucket, key, headers)- return _put_object(bucket, key, body, headers)-- # GetObject: GET /bucket/key- if method == "GET" and key:- return _get_object(bucket, key, headers)+ if method == "POST":+ if "delete" in query_params:+ return _delete_objects(bucket, body)+ return _error("MethodNotAllowed", "The specified method is not allowed against this resource.", 405)- # HeadObject: HEAD /bucket/key- if method == "HEAD" and key:- return _head_object(bucket, key)+ return _error("MethodNotAllowed", "The specified method is not allowed against this resource.", 405)- # DeleteObject: DELETE /bucket/key- if method == "DELETE" and key:- return _delete_object(bucket, key)-- return _error("MethodNotAllowed", f"Method {method} not supported", 405)+# ---------------------------------------------------------------------------+# Bucket operations+# ---------------------------------------------------------------------------def _list_buckets():- root = Element("ListAllMyBucketsResult", xmlns="http://s3.amazonaws.com/doc/2006-03-01/")+ root = Element("ListAllMyBucketsResult", xmlns=S3_NS)owner = SubElement(root, "Owner")SubElement(owner, "ID").text = "owner-id"- SubElement(owner, "DisplayName").text = "localstack"+ SubElement(owner, "DisplayName").text = "ministack"buckets_el = SubElement(root, "Buckets")- for name, data in _buckets.items():+ for name, data in sorted(_buckets.items()):b = SubElement(buckets_el, "Bucket")SubElement(b, "Name").text = nameSubElement(b, "CreationDate").text = data["created"]- body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")- return 200, {"Content-Type": "application/xml"}, body+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)def _create_bucket(name: str, body: bytes):+ if not _validate_bucket_name(name):+ return _error("InvalidBucketName", "The specified bucket is not valid.", 400, f"/{name}")if name in _buckets:- return _error("BucketAlreadyOwnedByYou", f"Bucket {name} already exists", 409)- _buckets[name] = {"created": now_iso(), "objects": {}}+ return _error(+ "BucketAlreadyOwnedByYou",+ "Your previous request to create the named bucket succeeded and you already own it.",+ 409,+ f"/{name}",+ )++ region = None+ if body:+ try:+ xml_root = fromstring(body)+ loc_el = _find_xml_tag(xml_root, "LocationConstraint")+ if loc_el is not None and loc_el.text:+ region = loc_el.text+ except Exception:+ pass++ _buckets[name] = {"created": now_iso(), "objects": {}, "region": region}if PERSIST:os.makedirs(os.path.join(DATA_DIR, name), exist_ok=True)return 200, {"Content-Type": "application/xml", "Location": f"/{name}"}, b""@@ -130,280 +444,1363 @@ def _create_bucket(name: str, body: bytes):def _delete_bucket(name: str):bucket = _ensure_bucket(name)if bucket is None:- return _error("NoSuchBucket", f"Bucket {name} does not exist", 404)+ return _no_such_bucket(name)if bucket["objects"]:- return _error("BucketNotEmpty", "The bucket is not empty", 409)+ return _error("BucketNotEmpty", "The bucket you tried to delete is not empty", 409, f"/{name}")del _buckets[name]+ _bucket_policies.pop(name, None)+ _bucket_notifications.pop(name, None)+ _bucket_tags.pop(name, None)+ _bucket_versioning.pop(name, None)+ _bucket_encryption.pop(name, None)+ _bucket_lifecycle.pop(name, None)+ _bucket_cors.pop(name, None)+ _bucket_acl.pop(name, None)+ _bucket_websites.pop(name, None)+ _bucket_logging_config.pop(name, None)+ _bucket_accelerate_config.pop(name, None)+ _bucket_request_payment_config.pop(name, None)return 204, {}, b""def _head_bucket(name: str):if name not in _buckets:- return _error("NoSuchBucket", f"Bucket {name} does not exist", 404)- return 200, {"Content-Type": "application/xml"}, b""+ return _no_such_bucket(name)+ return 200, {+ "Content-Type": "application/xml",+ "x-amz-bucket-region": _buckets[name].get("region") or "us-east-1",+ }, b""def _get_bucket_location(name: str):if name not in _buckets:- return _error("NoSuchBucket", f"Bucket {name} does not exist", 404)- root = Element("LocationConstraint", xmlns="http://s3.amazonaws.com/doc/2006-03-01/")- root.text = "us-east-1"- body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")+ return _no_such_bucket(name)+ root = Element("LocationConstraint", xmlns=S3_NS)+ region = _buckets[name].get("region")+ # AWS returns empty LocationConstraint for us-east-1.+ if region and region != "us-east-1":+ root.text = region+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++# ---------------------------------------------------------------------------+# Bucket sub-resources+# ---------------------------------------------------------------------------++def _get_bucket_policy(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ policy = _bucket_policies.get(name)+ if not policy:+ return _error("NoSuchBucketPolicy", "The bucket policy does not exist", 404, f"/{name}")+ return 200, {"Content-Type": "application/json"}, policy.encode("utf-8")+++def _put_bucket_policy(name: str, body: bytes):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_policies[name] = body.decode("utf-8")+ return 204, {}, b""+++def _delete_bucket_policy(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_policies.pop(name, None)+ return 204, {}, b""+++def _get_bucket_versioning(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ root = Element("VersioningConfiguration", xmlns=S3_NS)+ status = _bucket_versioning.get(name)+ if status:+ SubElement(root, "Status").text = status+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++def _put_bucket_versioning(name: str, body: bytes):+ if name not in _buckets:+ return _no_such_bucket(name)+ try:+ xml_root = fromstring(body)+ status_el = _find_xml_tag(xml_root, "Status")+ if status_el is not None and status_el.text:+ _bucket_versioning[name] = status_el.text+ except Exception:+ pass+ return 200, {}, b""+++def _get_bucket_encryption(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ config = _bucket_encryption.get(name)+ if config:+ return 200, {"Content-Type": "application/xml"}, config+ return _error(+ "ServerSideEncryptionConfigurationNotFoundError",+ "The server side encryption configuration was not found",+ 404,+ f"/{name}",+ )+++def _put_bucket_encryption(name: str, body: bytes):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_encryption[name] = body+ return 200, {}, b""+++def _delete_bucket_encryption(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_encryption.pop(name, None)+ return 204, {}, b""+++def _get_bucket_lifecycle(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ config = _bucket_lifecycle.get(name)+ if config:+ return 200, {"Content-Type": "application/xml"}, config+ return _error(+ "NoSuchLifecycleConfiguration",+ "The lifecycle configuration does not exist",+ 404,+ f"/{name}",+ )+++def _put_bucket_lifecycle(name: str, body: bytes):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_lifecycle[name] = body+ return 200, {}, b""+++def _delete_bucket_lifecycle(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_lifecycle.pop(name, None)+ return 204, {}, b""+++def _get_bucket_cors(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ config = _bucket_cors.get(name)+ if config:+ return 200, {"Content-Type": "application/xml"}, config+ return _error("NoSuchCORSConfiguration", "The CORS configuration does not exist", 404, f"/{name}")+++def _put_bucket_cors(name: str, body: bytes):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_cors[name] = body+ return 200, {}, b""+++def _delete_bucket_cors(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_cors.pop(name, None)+ return 204, {}, b""+++def _get_bucket_acl(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ stored = _bucket_acl.get(name)+ if stored:+ return 200, {"Content-Type": "application/xml"}, stored+ body = (+ XML_DECL + b"\n"+ b'<AccessControlPolicy xmlns="' + S3_NS.encode() + b'">'+ b"<Owner><ID>owner-id</ID><DisplayName>ministack</DisplayName></Owner>"+ b"<AccessControlList><Grant>"+ b'<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser">'+ b"<ID>owner-id</ID><DisplayName>ministack</DisplayName></Grantee>"+ b"<Permission>FULL_CONTROL</Permission>"+ b"</Grant></AccessControlList></AccessControlPolicy>"+ )return 200, {"Content-Type": "application/xml"}, body-def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):+def _put_bucket_acl(name: str, body: bytes):+ if name not in _buckets:+ return _no_such_bucket(name)+ if body:+ _bucket_acl[name] = body+ return 200, {}, b""+++def _get_bucket_tagging(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ tags = _bucket_tags.get(name)+ if not tags:+ return _error("NoSuchTagSet", "The TagSet does not exist", 404, f"/{name}")+ root = Element("Tagging", xmlns=S3_NS)+ tag_set = SubElement(root, "TagSet")+ for k, v in tags.items():+ tag = SubElement(tag_set, "Tag")+ SubElement(tag, "Key").text = k+ SubElement(tag, "Value").text = v+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++def _put_bucket_tagging(name: str, body: bytes):+ if name not in _buckets:+ return _no_such_bucket(name)+ try:+ _bucket_tags[name] = _parse_tags_xml(body)+ except Exception:+ return _error("MalformedXML", "The XML you provided was not well-formed", 400)+ return 204, {}, b""+++def _delete_bucket_tagging(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_tags.pop(name, None)+ return 204, {}, b""+++def _get_bucket_notification(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ stored = _bucket_notifications.get(name)+ if stored:+ return 200, {"Content-Type": "application/xml"}, stored+ root = Element("NotificationConfiguration", xmlns=S3_NS)+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++def _put_bucket_notification(name: str, body: bytes):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_notifications[name] = body+ return 200, {}, b""+++def _get_bucket_logging(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ stored = _bucket_logging_config.get(name)+ if stored:+ return 200, {"Content-Type": "application/xml"}, stored+ root = Element("BucketLoggingStatus", xmlns=S3_NS)+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++def _put_bucket_logging(name: str, body: bytes):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_logging_config[name] = body+ return 200, {}, b""+++def _get_bucket_accelerate(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ stored = _bucket_accelerate_config.get(name)+ if stored:+ return 200, {"Content-Type": "application/xml"}, stored+ root = Element("AccelerateConfiguration", xmlns=S3_NS)+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++def _put_bucket_accelerate(name: str, body: bytes):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_accelerate_config[name] = body+ return 200, {}, b""+++def _get_bucket_request_payment(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ stored = _bucket_request_payment_config.get(name)+ if stored:+ return 200, {"Content-Type": "application/xml"}, stored+ root = Element("RequestPaymentConfiguration", xmlns=S3_NS)+ SubElement(root, "Payer").text = "BucketOwner"+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++def _put_bucket_request_payment(name: str, body: bytes):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_request_payment_config[name] = body+ return 200, {}, b""+++def _get_bucket_website(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ stored = _bucket_websites.get(name)+ if stored:+ return 200, {"Content-Type": "application/xml"}, stored+ return _error("NoSuchWebsiteConfiguration",+ "The specified bucket does not have a website configuration", 404, f"/{name}")+++def _put_bucket_website(name: str, body: bytes):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_websites[name] = body+ return 200, {}, b""+++def _delete_bucket_website(name: str):+ if name not in _buckets:+ return _no_such_bucket(name)+ _bucket_websites.pop(name, None)+ return 204, {}, b""+++def _list_object_versions(bucket_name: str, query_params: dict):bucket = _ensure_bucket(bucket_name)if bucket is None:- # Auto-create bucket (LocalStack behavior)- _buckets[bucket_name] = {"created": now_iso(), "objects": {}}- bucket = _buckets[bucket_name]+ return _no_such_bucket(bucket_name)- etag = f'"{md5_hash(body)}"'- content_type = headers.get("content-type", "application/octet-stream")+ prefix = _qp(query_params, "prefix", "")+ key_marker = _qp(query_params, "key-marker", "")+ version_id_marker = _qp(query_params, "version-id-marker", "")+ max_keys = int(_qp(query_params, "max-keys", "1000"))- # Extract user metadata (x-amz-meta-*)- metadata = {}- for k, v in headers.items():- if k.lower().startswith("x-amz-meta-"):- metadata[k] = v+ root = Element("ListVersionsResult", xmlns=S3_NS)+ SubElement(root, "Name").text = bucket_name+ SubElement(root, "Prefix").text = prefix+ SubElement(root, "KeyMarker").text = key_marker+ SubElement(root, "VersionIdMarker").text = version_id_marker+ SubElement(root, "MaxKeys").text = str(max_keys)- obj = {+ keys = sorted(k for k in bucket["objects"] if k.startswith(prefix) and k > key_marker)+ is_truncated = len(keys) > max_keys+ SubElement(root, "IsTruncated").text = "true" if is_truncated else "false"++ for k in keys[:max_keys]:+ obj = bucket["objects"][k]+ ver = SubElement(root, "Version")+ SubElement(ver, "Key").text = k+ SubElement(ver, "VersionId").text = "1"+ SubElement(ver, "IsLatest").text = "true"+ SubElement(ver, "LastModified").text = obj["last_modified"]+ SubElement(ver, "ETag").text = obj["etag"]+ SubElement(ver, "Size").text = str(obj["size"])+ SubElement(ver, "StorageClass").text = "STANDARD"+ owner = SubElement(ver, "Owner")+ SubElement(owner, "ID").text = "owner-id"+ SubElement(owner, "DisplayName").text = "ministack"++ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++# ---------------------------------------------------------------------------+# S3 Event Notifications+# ---------------------------------------------------------------------------++def _parse_notification_config(bucket_name: str) -> list[dict]:+ """Parse the raw notification XML into structured config dicts."""+ raw = _bucket_notifications.get(bucket_name)+ if not raw:+ return []++ try:+ root = fromstring(raw)+ except Exception:+ return []++ configs: list[dict] = []++ _CONFIG_MAP = {+ "QueueConfiguration": ("sqs", ("Queue",)),+ "TopicConfiguration": ("sns", ("Topic",)),+ "CloudFunctionConfiguration": ("lambda", ("CloudFunction", "Function")),+ "LambdaFunctionConfiguration": ("lambda", ("Function", "CloudFunction")),+ }++ for tag_suffix, (target_type, arn_tags) in _CONFIG_MAP.items():+ for cfg_el in list(root.findall(f"{{{S3_NS}}}{tag_suffix}")) + list(root.findall(tag_suffix)):+ arn = ""+ for at in arn_tags:+ el = _find_xml_tag(cfg_el, at)+ if el is not None and el.text:+ arn = el.text.strip()+ break+ if not arn:+ continue++ id_el = _find_xml_tag(cfg_el, "Id")+ config_id = (id_el.text if id_el is not None and id_el.text else new_uuid())++ events: list[str] = []+ for ev_el in list(cfg_el.findall(f"{{{S3_NS}}}Event")) + list(cfg_el.findall("Event")):+ if ev_el.text:+ events.append(ev_el.text.strip())++ filter_prefix = None+ filter_suffix = None+ filter_el = _find_xml_tag(cfg_el, "Filter")+ if filter_el is not None:+ s3key_el = _find_xml_tag(filter_el, "S3Key")+ if s3key_el is not None:+ for rule_el in (list(s3key_el.findall(f"{{{S3_NS}}}FilterRule"))+ + list(s3key_el.findall("FilterRule"))):+ name_el = _find_xml_tag(rule_el, "Name")+ val_el = _find_xml_tag(rule_el, "Value")+ if name_el is not None and name_el.text and val_el is not None:+ rule_name = name_el.text.strip().lower()+ rule_val = val_el.text or ""+ if rule_name == "prefix":+ filter_prefix = rule_val+ elif rule_name == "suffix":+ filter_suffix = rule_val++ configs.append({+ "type": target_type,+ "arn": arn,+ "id": config_id,+ "events": events,+ "filter_prefix": filter_prefix,+ "filter_suffix": filter_suffix,+ })++ return configs+++def _event_matches(event_name: str, patterns: list[str]) -> bool:+ """Check if event_name matches any of the configured event patterns.++ Supports wildcards: ``s3:ObjectCreated:*`` matches ``s3:ObjectCreated:Put``.+ """+ for pat in patterns:+ if pat == event_name:+ return True+ if pat.endswith(":*"):+ prefix = pat[:-1]+ if event_name.startswith(prefix):+ return True+ if pat == "s3:*":+ return True+ return False+++def _key_matches_filter(key: str, prefix: str | None, suffix: str | None) -> bool:+ if prefix is not None and not key.startswith(prefix):+ return False+ if suffix is not None and not key.endswith(suffix):+ return False+ return True+++def _fire_s3_event(bucket_name: str, key: str, event_name: str,+ size: int = 0, etag: str = "") -> None:+ """Build and deliver an S3 event notification. Best-effort — errors are logged."""+ try:+ configs = _parse_notification_config(bucket_name)+ if not configs:+ return++ short_event = event_name.replace("s3:", "", 1)+ event_time = now_iso()+ request_id = new_uuid()+ clean_etag = etag.strip('"')++ event_payload = {+ "Records": [{+ "eventVersion": "2.1",+ "eventSource": "aws:s3",+ "awsRegion": "us-east-1",+ "eventTime": event_time,+ "eventName": short_event,+ "userIdentity": {"principalId": "EXAMPLE"},+ "requestParameters": {"sourceIPAddress": "127.0.0.1"},+ "responseElements": {+ "x-amz-request-id": request_id,+ "x-amz-id-2": "EXAMPLE",+ },+ "s3": {+ "s3SchemaVersion": "1.0",+ "configurationId": "",+ "bucket": {+ "name": bucket_name,+ "ownerIdentity": {"principalId": "EXAMPLE"},+ "arn": f"arn:aws:s3:::{bucket_name}",+ },+ "object": {+ "key": key,+ "size": size,+ "eTag": clean_etag,+ "sequencer": "0",+ },+ },+ }],+ }++ for cfg in configs:+ try:+ if not _event_matches(event_name, cfg["events"]):+ continue+ if not _key_matches_filter(key, cfg["filter_prefix"], cfg["filter_suffix"]):+ continue++ payload = dict(event_payload)+ payload["Records"] = [dict(payload["Records"][0])]+ payload["Records"][0]["s3"] = dict(payload["Records"][0]["s3"])+ payload["Records"][0]["s3"]["configurationId"] = cfg["id"]++ if cfg["type"] == "sqs":+ _deliver_event_to_sqs(cfg["arn"], payload)+ elif cfg["type"] == "sns":+ _deliver_event_to_sns(cfg["arn"], payload)+ elif cfg["type"] == "lambda":+ _deliver_event_to_lambda(cfg["arn"], payload)+ except Exception:+ logger.exception("S3 notification delivery failed for config %s", cfg.get("id"))++ except Exception:+ logger.exception("S3 event notification fire failed for %s/%s", bucket_name, key)+++def _deliver_event_to_sqs(arn: str, event_payload: dict) -> None:+ from services import sqs as _sqs++ queue_name = arn.rsplit(":", 1)[-1]+ queue_url = _sqs._queue_url(queue_name)+ queue = _sqs._queues.get(queue_url)+ if not queue:+ logger.warning("S3 notification: SQS queue %s not found", queue_name)+ return++ body = json.dumps(event_payload)+ now = time.time()+ msg = {+ "id": new_uuid(),"body": body,- "content_type": content_type,- "etag": etag,- "last_modified": now_iso(),- "size": len(body),- "metadata": metadata,+ "md5": hashlib.md5(body.encode()).hexdigest(),+ "receipt_handle": None,+ "sent_at": now,+ "visible_at": now,+ "receive_count": 0,}+ _sqs._ensure_msg_fields(msg)+ queue["messages"].append(msg)+ logger.info("S3 notification → SQS %s", queue_name)+++def _deliver_event_to_sns(arn: str, event_payload: dict) -> None:+ from services import sns as _sns++ topic = _sns._topics.get(arn)+ if not topic:+ logger.warning("S3 notification: SNS topic %s not found", arn)+ return++ message = json.dumps(event_payload)+ msg_id = new_uuid()+ _sns._fanout(arn, msg_id, message, subject="Amazon S3 Notification")+ logger.info("S3 notification → SNS %s", arn)+++def _deliver_event_to_lambda(arn: str, event_payload: dict) -> None:+ from services import lambda_svc as _lambda++ func_name = arn.rsplit(":", 1)[-1]+ if func_name not in _lambda._functions:+ logger.warning("S3 notification: Lambda function %s not found", func_name)+ return++ _lambda._invoke(+ func_name,+ event_payload,+ headers={"x-amz-invocation-type": "Event"},+ )+ logger.info("S3 notification → Lambda %s", func_name)+++def _fire_s3_event_async(bucket_name: str, key: str, event_name: str,+ size: int = 0, etag: str = "") -> None:+ """Fire S3 event notification in a background thread (non-blocking)."""+ if bucket_name not in _bucket_notifications:+ return+ t = threading.Thread(+ target=_fire_s3_event,+ args=(bucket_name, key, event_name, size, etag),+ daemon=True,+ )+ t.start()+++# ---------------------------------------------------------------------------+# Object operations+# ---------------------------------------------------------------------------++def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _no_such_bucket(bucket_name)++ md5_err = _validate_content_md5(headers, body)+ if md5_err:+ return md5_err++ obj = _build_object_record(body, headers)bucket["objects"][key] = objif PERSIST:- _persist_object(bucket_name, key, body)+ _persist_object(bucket_name, key, obj)++ _fire_s3_event_async(bucket_name, key, "s3:ObjectCreated:Put",+ size=obj["size"], etag=obj["etag"])- return 200, {"ETag": etag, "Content-Type": "application/xml"}, b""+ return 200, {"ETag": obj["etag"], "Content-Type": "application/xml"}, b""def _get_object(bucket_name: str, key: str, headers: dict):bucket = _ensure_bucket(bucket_name)if bucket is None:- return _error("NoSuchBucket", f"Bucket {bucket_name} does not exist", 404)+ return _no_such_bucket(bucket_name)if key not in bucket["objects"]:- return _error("NoSuchKey", f"The specified key does not exist: {key}", 404)+ return _error("NoSuchKey", "The specified key does not exist.", 404, f"/{bucket_name}/{key}")obj = bucket["objects"][key]- resp_headers = {- "Content-Type": obj["content_type"],- "ETag": obj["etag"],- "Last-Modified": obj["last_modified"],- "Content-Length": str(obj["size"]),- }- resp_headers.update(obj["metadata"])+ resp_headers = _object_response_headers(obj)++ range_header = headers.get("range", "")+ if range_header:+ rng = _parse_range(range_header, obj["size"])+ if rng is None:+ return (+ 416,+ {"Content-Type": "application/xml", "Content-Range": f"bytes */{obj['size']}"},+ _xml_body(_range_error_xml(bucket_name, key)),+ )+ start, end = rng+ slice_body = obj["body"][start : end + 1]+ resp_headers["Content-Length"] = str(len(slice_body))+ resp_headers["Content-Range"] = f"bytes {start}-{end}/{obj['size']}"+ return 206, resp_headers, slice_body+return 200, resp_headers, obj["body"]+def _range_error_xml(bucket_name: str, key: str) -> Element:+ root = Element("Error")+ SubElement(root, "Code").text = "InvalidRange"+ SubElement(root, "Message").text = "The requested range is not satisfiable"+ SubElement(root, "Resource").text = f"/{bucket_name}/{key}"+ SubElement(root, "RequestId").text = new_uuid()+ return root++def _head_object(bucket_name: str, key: str):bucket = _ensure_bucket(bucket_name)if bucket is None:- return _error("NoSuchBucket", f"Bucket {bucket_name} does not exist", 404)+ return _no_such_bucket(bucket_name)if key not in bucket["objects"]:- return 404, {}, b""+ return _error("NoSuchKey", "The specified key does not exist.", 404, f"/{bucket_name}/{key}")obj = bucket["objects"][key]- resp_headers = {- "Content-Type": obj["content_type"],- "ETag": obj["etag"],- "Last-Modified": obj["last_modified"],- "Content-Length": str(obj["size"]),- }- return 200, resp_headers, b""+ return 200, _object_response_headers(obj), b""def _delete_object(bucket_name: str, key: str):bucket = _ensure_bucket(bucket_name)if bucket is None:- return _error("NoSuchBucket", f"Bucket {bucket_name} does not exist", 404)+ return _no_such_bucket(bucket_name)+ existed = key in bucket["objects"]bucket["objects"].pop(key, None)- return 204, {}, b""+ _object_tags.pop((bucket_name, key), None)++ if existed:+ _fire_s3_event_async(bucket_name, key, "s3:ObjectRemoved:Delete")++ return 204, {"x-amz-delete-marker": "false"}, b""def _copy_object(bucket_name: str, dest_key: str, headers: dict):- source = headers.get("x-amz-copy-source", "").lstrip("/")- src_parts = source.split("/", 1)+ source = url_unquote(headers.get("x-amz-copy-source", "").lstrip("/"))+ src_parts = source.split("?", 1)[0].split("/", 1)if len(src_parts) < 2:- return _error("InvalidArgument", "Invalid copy source", 400)+ return _error(+ "InvalidArgument",+ "Copy Source must mention the source bucket and key: /sourcebucket/sourcekey",+ 400,+ )src_bucket_name, src_key = src_partssrc_bucket = _ensure_bucket(src_bucket_name)- if src_bucket is None or src_key not in src_bucket["objects"]:- return _error("NoSuchKey", "Source object not found", 404)+ if src_bucket is None:+ return _no_such_bucket(src_bucket_name)+ if src_key not in src_bucket["objects"]:+ return _error("NoSuchKey", "The specified key does not exist.", 404, f"/{src_bucket_name}/{src_key}")dest_bucket = _ensure_bucket(bucket_name)if dest_bucket is None:- _buckets[bucket_name] = {"created": now_iso(), "objects": {}}- dest_bucket = _buckets[bucket_name]+ return _no_such_bucket(bucket_name)src_obj = src_bucket["objects"][src_key]++ # Precondition: x-amz-copy-source-if-match+ if_match = headers.get("x-amz-copy-source-if-match", "")+ if if_match and if_match.strip('"') != src_obj["etag"].strip('"'):+ return _error("PreconditionFailed", "At least one of the pre-conditions you specified did not hold", 412)++ # Precondition: x-amz-copy-source-if-none-match — 412 for PUT-like operations.+ if_none_match = headers.get("x-amz-copy-source-if-none-match", "")+ if if_none_match and if_none_match.strip('"') == src_obj["etag"].strip('"'):+ return _error("PreconditionFailed", "At least one of the pre-conditions you specified did not hold", 412)++ directive = headers.get("x-amz-metadata-directive", "COPY").upper()+ if directive == "REPLACE":+ metadata = _extract_user_metadata(headers)+ content_type = headers.get("content-type", src_obj["content_type"])+ content_encoding = headers.get("content-encoding", src_obj.get("content_encoding"))+ preserved = {}+ for h in _PRESERVED_HEADERS:+ val = headers.get(h)+ if val is not None:+ preserved[h] = val+ else:+ metadata = dict(src_obj.get("metadata", {}))+ content_type = src_obj["content_type"]+ content_encoding = src_obj.get("content_encoding")+ preserved = dict(src_obj.get("preserved_headers", {}))+new_etag = src_obj["etag"]- dest_bucket["objects"][dest_key] = {+ last_modified = now_iso()+ dest_obj = {"body": src_obj["body"],- "content_type": src_obj["content_type"],+ "content_type": content_type,+ "content_encoding": content_encoding,"etag": new_etag,- "last_modified": now_iso(),+ "last_modified": last_modified,"size": src_obj["size"],- "metadata": dict(src_obj["metadata"]),+ "metadata": metadata,+ "preserved_headers": preserved,}+ dest_bucket["objects"][dest_key] = dest_obj++ if PERSIST:+ _persist_object(bucket_name, dest_key, dest_obj)- root = Element("CopyObjectResult")- SubElement(root, "LastModified").text = now_iso()+ _fire_s3_event_async(bucket_name, dest_key, "s3:ObjectCreated:Copy",+ size=dest_obj["size"], etag=new_etag)++ root = Element("CopyObjectResult", xmlns=S3_NS)+ SubElement(root, "LastModified").text = last_modifiedSubElement(root, "ETag").text = new_etag- body = tostring(root, encoding="unicode").encode("utf-8")- return 200, {"Content-Type": "application/xml"}, body+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)-def _list_objects_v1(bucket_name: str, query_params: dict):+# ---------------------------------------------------------------------------+# Object tagging+# ---------------------------------------------------------------------------++def _get_object_tagging(bucket_name: str, key: str):bucket = _ensure_bucket(bucket_name)if bucket is None:- return _error("NoSuchBucket", f"Bucket {bucket_name} does not exist", 404)+ return _no_such_bucket(bucket_name)+ if key not in bucket["objects"]:+ return _error("NoSuchKey", "The specified key does not exist.", 404, f"/{bucket_name}/{key}")++ tags = _object_tags.get((bucket_name, key), {})+ root = Element("Tagging", xmlns=S3_NS)+ tag_set = SubElement(root, "TagSet")+ for k, v in tags.items():+ tag = SubElement(tag_set, "Tag")+ SubElement(tag, "Key").text = k+ SubElement(tag, "Value").text = v+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++def _put_object_tagging(bucket_name: str, key: str, body: bytes):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _no_such_bucket(bucket_name)+ if key not in bucket["objects"]:+ return _error("NoSuchKey", "The specified key does not exist.", 404, f"/{bucket_name}/{key}")+ try:+ _object_tags[(bucket_name, key)] = _parse_tags_xml(body)+ except Exception:+ return _error("MalformedXML", "The XML you provided was not well-formed", 400)+ return 200, {"Content-Type": "application/xml"}, b""+++def _delete_object_tagging(bucket_name: str, key: str):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _no_such_bucket(bucket_name)+ if key not in bucket["objects"]:+ return _error("NoSuchKey", "The specified key does not exist.", 404, f"/{bucket_name}/{key}")+ _object_tags.pop((bucket_name, key), None)+ return 204, {}, b""- prefix = _qp(query_params, "prefix", "")- delimiter = _qp(query_params, "delimiter", "")- max_keys = int(_qp(query_params, "max-keys", "1000"))- marker = _qp(query_params, "marker", "")- keys = sorted(k for k in bucket["objects"] if k.startswith(prefix) and k > marker)- common_prefixes = set()- contents = []+# ---------------------------------------------------------------------------+# List objects+# ---------------------------------------------------------------------------++def _collect_list_entries(bucket_objects: dict, prefix: str, delimiter: str, max_keys: int, start_after: str):+ """Walk sorted keys, collecting contents and common prefixes with correct+ pagination. When a key falls under a common-prefix group the iterator+ advances past *all* remaining keys in that group so the next page's+ marker cleanly skips the entire prefix.++ Returns (contents, common_prefixes, is_truncated, next_marker).+ """+ all_keys = sorted(k for k in bucket_objects if k.startswith(prefix) and k > start_after)+ contents: list[str] = []+ common_prefixes: set[str] = set()+ is_truncated = False+ count = 0+ next_marker = ""++ i = 0+ while i < len(all_keys):+ k = all_keys[i]- for k in keys:if delimiter:suffix = k[len(prefix):]- idx = suffix.find(delimiter)- if idx >= 0:- common_prefixes.add(prefix + suffix[:idx + len(delimiter)])+ delim_idx = suffix.find(delimiter)+ if delim_idx >= 0:+ cp = prefix + suffix[: delim_idx + len(delimiter)]+ is_new_prefix = cp not in common_prefixes+ if is_new_prefix:+ if count >= max_keys:+ is_truncated = True+ break+ common_prefixes.add(cp)+ count += 1+ # Advance past every remaining key belonging to this prefix+ # group so the marker lands after the whole group.+ next_marker = k+ i += 1+ while i < len(all_keys) and all_keys[i].startswith(cp):+ next_marker = all_keys[i]+ i += 1continue- if len(contents) >= max_keys:++ if count >= max_keys:+ is_truncated = Truebreakcontents.append(k)+ count += 1+ next_marker = k+ i += 1++ return contents, common_prefixes, is_truncated, next_marker+- root = Element("ListBucketResult", xmlns="http://s3.amazonaws.com/doc/2006-03-01/")+def _list_objects_v1(bucket_name: str, query_params: dict):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _no_such_bucket(bucket_name)++ prefix = _qp(query_params, "prefix", "")+ delimiter = _qp(query_params, "delimiter", "")+ max_keys = int(_qp(query_params, "max-keys", "1000"))+ marker = _qp(query_params, "marker", "")+ encoding_type = _qp(query_params, "encoding-type", "")+ encode = encoding_type == "url"++ contents, common_prefixes, is_truncated, next_marker = _collect_list_entries(+ bucket["objects"], prefix, delimiter, max_keys, marker,+ )++ root = Element("ListBucketResult", xmlns=S3_NS)SubElement(root, "Name").text = bucket_name- SubElement(root, "Prefix").text = prefix+ SubElement(root, "Prefix").text = _url_encode(prefix) if encode and prefix else prefix+ SubElement(root, "Marker").text = _url_encode(marker) if encode and marker else marker+ if delimiter:+ SubElement(root, "Delimiter").text = _url_encode(delimiter) if encode else delimiter+ if encoding_type:+ SubElement(root, "EncodingType").text = encoding_typeSubElement(root, "MaxKeys").text = str(max_keys)- SubElement(root, "IsTruncated").text = "false"+ SubElement(root, "IsTruncated").text = "true" if is_truncated else "false"++ # AWS only returns NextMarker when delimiter is specified.+ if is_truncated and next_marker and delimiter:+ SubElement(root, "NextMarker").text = _url_encode(next_marker) if encode else next_markerfor k in contents:obj = bucket["objects"][k]c = SubElement(root, "Contents")- SubElement(c, "Key").text = k+ SubElement(c, "Key").text = _url_encode(k) if encode else kSubElement(c, "LastModified").text = obj["last_modified"]SubElement(c, "ETag").text = obj["etag"]SubElement(c, "Size").text = str(obj["size"])SubElement(c, "StorageClass").text = "STANDARD"+ owner = SubElement(c, "Owner")+ SubElement(owner, "ID").text = "owner-id"+ SubElement(owner, "DisplayName").text = "ministack"for cp in sorted(common_prefixes):cpe = SubElement(root, "CommonPrefixes")- SubElement(cpe, "Prefix").text = cp+ SubElement(cpe, "Prefix").text = _url_encode(cp) if encode else cp- body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")- return 200, {"Content-Type": "application/xml"}, body+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)def _list_objects_v2(bucket_name: str, query_params: dict):bucket = _ensure_bucket(bucket_name)if bucket is None:- return _error("NoSuchBucket", f"Bucket {bucket_name} does not exist", 404)+ return _no_such_bucket(bucket_name)prefix = _qp(query_params, "prefix", "")delimiter = _qp(query_params, "delimiter", "")max_keys = int(_qp(query_params, "max-keys", "1000"))continuation = _qp(query_params, "continuation-token", "")start_after = _qp(query_params, "start-after", "")-- effective_start = continuation or start_after- keys = sorted(k for k in bucket["objects"] if k.startswith(prefix) and k > effective_start)- common_prefixes = set()- contents = []-- for k in keys:- if delimiter:- suffix = k[len(prefix):]- idx = suffix.find(delimiter)- if idx >= 0:- common_prefixes.add(prefix + suffix[:idx + len(delimiter)])- continue- if len(contents) >= max_keys:- break- contents.append(k)-- root = Element("ListBucketResult", xmlns="http://s3.amazonaws.com/doc/2006-03-01/")+ fetch_owner = _qp(query_params, "fetch-owner", "").lower() == "true"+ encoding_type = _qp(query_params, "encoding-type", "")+ encode = encoding_type == "url"++ if continuation:+ try:+ effective_start = base64.b64decode(continuation).decode("utf-8")+ except Exception:+ effective_start = continuation+ else:+ effective_start = start_after++ contents, common_prefixes, is_truncated, next_marker = _collect_list_entries(+ bucket["objects"], prefix, delimiter, max_keys, effective_start,+ )++ root = Element("ListBucketResult", xmlns=S3_NS)SubElement(root, "Name").text = bucket_name- SubElement(root, "Prefix").text = prefix+ SubElement(root, "Prefix").text = _url_encode(prefix) if encode and prefix else prefix+ if delimiter:+ SubElement(root, "Delimiter").text = _url_encode(delimiter) if encode else delimiter+ if encoding_type:+ SubElement(root, "EncodingType").text = encoding_typeSubElement(root, "MaxKeys").text = str(max_keys)- SubElement(root, "KeyCount").text = str(len(contents))- SubElement(root, "IsTruncated").text = "false"+ SubElement(root, "KeyCount").text = str(len(contents) + len(common_prefixes))+ SubElement(root, "IsTruncated").text = "true" if is_truncated else "false"++ if continuation:+ SubElement(root, "ContinuationToken").text = continuation+ if start_after:+ SubElement(root, "StartAfter").text = _url_encode(start_after) if encode else start_after++ if is_truncated and next_marker:+ token = base64.b64encode(next_marker.encode("utf-8")).decode("utf-8")+ SubElement(root, "NextContinuationToken").text = tokenfor k in contents:obj = bucket["objects"][k]c = SubElement(root, "Contents")- SubElement(c, "Key").text = k+ SubElement(c, "Key").text = _url_encode(k) if encode else kSubElement(c, "LastModified").text = obj["last_modified"]SubElement(c, "ETag").text = obj["etag"]SubElement(c, "Size").text = str(obj["size"])SubElement(c, "StorageClass").text = "STANDARD"+ if fetch_owner:+ owner = SubElement(c, "Owner")+ SubElement(owner, "ID").text = "owner-id"+ SubElement(owner, "DisplayName").text = "ministack"for cp in sorted(common_prefixes):cpe = SubElement(root, "CommonPrefixes")- SubElement(cpe, "Prefix").text = cp+ SubElement(cpe, "Prefix").text = _url_encode(cp) if encode else cp++ return 200, {"Content-Type": "application/xml"}, _xml_body(root)- body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")- return 200, {"Content-Type": "application/xml"}, body+# ---------------------------------------------------------------------------+# Batch delete+# ---------------------------------------------------------------------------def _delete_objects(bucket_name: str, body: bytes):bucket = _ensure_bucket(bucket_name)if bucket is None:- return _error("NoSuchBucket", f"Bucket {bucket_name} does not exist", 404)+ return _no_such_bucket(bucket_name)- root = fromstring(body)- ns = {"s3": "http://s3.amazonaws.com/doc/2006-03-01/"}- deleted = []- for obj_el in root.findall(".//Object", ns) or root.findall(".//Object"):- key_el = obj_el.find("Key", ns) or obj_el.find("Key")+ xml_root = fromstring(body)++ quiet = False+ quiet_el = _find_xml_tag(xml_root, "Quiet")+ if quiet_el is not None and quiet_el.text and quiet_el.text.lower() == "true":+ quiet = True++ deleted_keys: list[str] = []+ for obj_el in list(xml_root.findall("{%s}Object" % S3_NS)) or list(xml_root.findall("Object")):+ key_el = _find_xml_tag(obj_el, "Key")if key_el is not None and key_el.text:- bucket["objects"].pop(key_el.text, None)- deleted.append(key_el.text)+ k = key_el.text+ bucket["objects"].pop(k, None)+ _object_tags.pop((bucket_name, k), None)+ deleted_keys.append(k)++ resp = Element("DeleteResult", xmlns=S3_NS)+ if not quiet:+ for k in deleted_keys:+ d = SubElement(resp, "Deleted")+ SubElement(d, "Key").text = k++ return 200, {"Content-Type": "application/xml"}, _xml_body(resp)+++# ---------------------------------------------------------------------------+# Multipart upload+# ---------------------------------------------------------------------------++def _create_multipart_upload(bucket_name: str, key: str, headers: dict):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _no_such_bucket(bucket_name)++ upload_id = new_uuid()+ content_type = headers.get("content-type", "application/octet-stream")+ content_encoding = headers.get("content-encoding")+ metadata = _extract_user_metadata(headers)+ preserved = {}+ for h in _PRESERVED_HEADERS:+ val = headers.get(h)+ if val is not None:+ preserved[h] = val++ _multipart_uploads[upload_id] = {+ "bucket": bucket_name,+ "key": key,+ "parts": {},+ "metadata": metadata,+ "content_type": content_type,+ "content_encoding": content_encoding,+ "preserved_headers": preserved,+ "created": now_iso(),+ }- resp = Element("DeleteResult", xmlns="http://s3.amazonaws.com/doc/2006-03-01/")- for k in deleted:- d = SubElement(resp, "Deleted")- SubElement(d, "Key").text = k+ root = Element("InitiateMultipartUploadResult", xmlns=S3_NS)+ SubElement(root, "Bucket").text = bucket_name+ SubElement(root, "Key").text = key+ SubElement(root, "UploadId").text = upload_id+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)- body_out = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(resp, encoding="unicode").encode("utf-8")- return 200, {"Content-Type": "application/xml"}, body_out+def _upload_part(bucket_name: str, key: str, body: bytes, query_params: dict, headers: dict):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _no_such_bucket(bucket_name)++ upload_id = _qp(query_params, "uploadId")+ part_number = _qp(query_params, "partNumber")++ if upload_id not in _multipart_uploads:+ return _error("NoSuchUpload", "The specified multipart upload does not exist.", 404, f"/{bucket_name}/{key}")++ upload = _multipart_uploads[upload_id]+ if upload["bucket"] != bucket_name or upload["key"] != key:+ return _error("NoSuchUpload", "The specified multipart upload does not exist.", 404, f"/{bucket_name}/{key}")-def _persist_object(bucket: str, key: str, data: bytes):+ try:+ pn = int(part_number)+ except (ValueError, TypeError):+ return _error("InvalidArgument", "Part number must be an integer between 1 and 10000, inclusive.", 400)+ if pn < 1 or pn > 10000:+ return _error("InvalidArgument", "Part number must be an integer between 1 and 10000, inclusive.", 400)++ md5_err = _validate_content_md5(headers, body)+ if md5_err:+ return md5_err++ etag = f'"{md5_hash(body)}"'+ upload["parts"][pn] = {"body": body, "etag": etag, "size": len(body), "last_modified": now_iso()}+ return 200, {"ETag": etag}, b""+++def _complete_multipart_upload(bucket_name: str, key: str, body: bytes, query_params: dict):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _no_such_bucket(bucket_name)++ upload_id = _qp(query_params, "uploadId")+ if upload_id not in _multipart_uploads:+ return _error("NoSuchUpload", "The specified multipart upload does not exist.", 404, f"/{bucket_name}/{key}")++ upload = _multipart_uploads[upload_id]+ if upload["bucket"] != bucket_name or upload["key"] != key:+ return _error("NoSuchUpload", "The specified multipart upload does not exist.", 404, f"/{bucket_name}/{key}")++ xml_root = fromstring(body)+ ordered_parts: list[tuple[int, str | None]] = []+ for part_el in xml_root.iter():+ local = part_el.tag.split("}")[-1] if "}" in part_el.tag else part_el.tag+ if local == "Part":+ pn_text = etag_text = None+ for child in part_el:+ child_local = child.tag.split("}")[-1] if "}" in child.tag else child.tag+ if child_local == "PartNumber":+ pn_text = child.text+ elif child_local == "ETag":+ etag_text = child.text+ if pn_text is not None:+ ordered_parts.append((int(pn_text), etag_text))++ ordered_parts.sort(key=lambda x: x[0])++ md5_digests = b""+ combined = b""+ for pn, req_etag in ordered_parts:+ if pn not in upload["parts"]:+ return _error("InvalidPart", "One or more of the specified parts could not be found.", 400)+ stored = upload["parts"][pn]+ if req_etag and req_etag.strip('"') != stored["etag"].strip('"'):+ return _error(+ "InvalidPart",+ "One or more of the specified parts could not be found. "+ "The following part numbers are invalid: " + str(pn),+ 400,+ )+ md5_digests += hashlib.md5(stored["body"]).digest()+ combined += stored["body"]++ final_md5 = hashlib.md5(md5_digests).hexdigest()+ final_etag = f'"{final_md5}-{len(ordered_parts)}"'++ obj = {+ "body": combined,+ "content_type": upload["content_type"],+ "content_encoding": upload.get("content_encoding"),+ "etag": final_etag,+ "last_modified": now_iso(),+ "size": len(combined),+ "metadata": upload["metadata"],+ "preserved_headers": upload.get("preserved_headers", {}),+ }+ bucket["objects"][key] = obj++ if PERSIST:+ _persist_object(bucket_name, key, obj)++ del _multipart_uploads[upload_id]++ _fire_s3_event_async(bucket_name, key, "s3:ObjectCreated:CompleteMultipartUpload",+ size=obj["size"], etag=final_etag)++ root = Element("CompleteMultipartUploadResult", xmlns=S3_NS)+ SubElement(root, "Location").text = f"http://s3.amazonaws.com/{bucket_name}/{key}"+ SubElement(root, "Bucket").text = bucket_name+ SubElement(root, "Key").text = key+ SubElement(root, "ETag").text = final_etag+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++def _abort_multipart_upload(bucket_name: str, key: str, query_params: dict):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _no_such_bucket(bucket_name)++ upload_id = _qp(query_params, "uploadId")+ if upload_id not in _multipart_uploads:+ return _error("NoSuchUpload", "The specified multipart upload does not exist.", 404, f"/{bucket_name}/{key}")++ upload = _multipart_uploads[upload_id]+ if upload["bucket"] != bucket_name or upload["key"] != key:+ return _error("NoSuchUpload", "The specified multipart upload does not exist.", 404, f"/{bucket_name}/{key}")++ del _multipart_uploads[upload_id]+ return 204, {}, b""+++def _list_multipart_uploads(bucket_name: str, query_params: dict):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _no_such_bucket(bucket_name)++ prefix = _qp(query_params, "prefix", "")+ delimiter = _qp(query_params, "delimiter", "")+ max_uploads = int(_qp(query_params, "max-uploads", "1000"))+ key_marker = _qp(query_params, "key-marker", "")+ upload_id_marker = _qp(query_params, "upload-id-marker", "")++ root = Element("ListMultipartUploadsResult", xmlns=S3_NS)+ SubElement(root, "Bucket").text = bucket_name+ SubElement(root, "KeyMarker").text = key_marker+ SubElement(root, "UploadIdMarker").text = upload_id_marker+ SubElement(root, "MaxUploads").text = str(max_uploads)+ if prefix:+ SubElement(root, "Prefix").text = prefix+ if delimiter:+ SubElement(root, "Delimiter").text = delimiter++ uploads = []+ for uid, upload in _multipart_uploads.items():+ if upload["bucket"] != bucket_name:+ continue+ if prefix and not upload["key"].startswith(prefix):+ continue+ if key_marker and upload["key"] < key_marker:+ continue+ if key_marker and upload["key"] == key_marker and upload_id_marker and uid <= upload_id_marker:+ continue+ uploads.append((uid, upload))++ uploads.sort(key=lambda x: (x[1]["key"], x[0]))++ is_truncated = len(uploads) > max_uploads+ SubElement(root, "IsTruncated").text = "true" if is_truncated else "false"++ for uid, upload in uploads[:max_uploads]:+ u = SubElement(root, "Upload")+ SubElement(u, "Key").text = upload["key"]+ SubElement(u, "UploadId").text = uid+ initiator = SubElement(u, "Initiator")+ SubElement(initiator, "ID").text = "owner-id"+ SubElement(initiator, "DisplayName").text = "ministack"+ owner = SubElement(u, "Owner")+ SubElement(owner, "ID").text = "owner-id"+ SubElement(owner, "DisplayName").text = "ministack"+ SubElement(u, "StorageClass").text = "STANDARD"+ SubElement(u, "Initiated").text = upload["created"]++ if is_truncated and uploads:+ last = uploads[max_uploads - 1]+ SubElement(root, "NextKeyMarker").text = last[1]["key"]+ SubElement(root, "NextUploadIdMarker").text = last[0]++ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++def _list_parts(bucket_name: str, key: str, query_params: dict):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _no_such_bucket(bucket_name)++ upload_id = _qp(query_params, "uploadId")+ if upload_id not in _multipart_uploads:+ return _error("NoSuchUpload", "The specified multipart upload does not exist.", 404, f"/{bucket_name}/{key}")++ upload = _multipart_uploads[upload_id]+ if upload["bucket"] != bucket_name or upload["key"] != key:+ return _error("NoSuchUpload", "The specified multipart upload does not exist.", 404, f"/{bucket_name}/{key}")++ max_parts = int(_qp(query_params, "max-parts", "1000"))+ part_marker = int(_qp(query_params, "part-number-marker", "0"))++ root = Element("ListPartsResult", xmlns=S3_NS)+ SubElement(root, "Bucket").text = bucket_name+ SubElement(root, "Key").text = key+ SubElement(root, "UploadId").text = upload_id++ initiator = SubElement(root, "Initiator")+ SubElement(initiator, "ID").text = "owner-id"+ SubElement(initiator, "DisplayName").text = "ministack"+ owner = SubElement(root, "Owner")+ SubElement(owner, "ID").text = "owner-id"+ SubElement(owner, "DisplayName").text = "ministack"+ SubElement(root, "StorageClass").text = "STANDARD"+ SubElement(root, "PartNumberMarker").text = str(part_marker)+ SubElement(root, "MaxParts").text = str(max_parts)++ sorted_parts = sorted(pn for pn in upload["parts"] if pn > part_marker)+ is_truncated = len(sorted_parts) > max_parts+ SubElement(root, "IsTruncated").text = "true" if is_truncated else "false"++ for pn in sorted_parts[:max_parts]:+ part = upload["parts"][pn]+ p = SubElement(root, "Part")+ SubElement(p, "PartNumber").text = str(pn)+ SubElement(p, "LastModified").text = part.get("last_modified", now_iso())+ SubElement(p, "ETag").text = part["etag"]+ SubElement(p, "Size").text = str(part["size"])++ if is_truncated and sorted_parts:+ SubElement(root, "NextPartNumberMarker").text = str(sorted_parts[max_parts - 1])++ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++# ---------------------------------------------------------------------------+# Persistence+# ---------------------------------------------------------------------------++def _persist_object(bucket: str, key: str, obj):try:fpath = os.path.join(DATA_DIR, bucket, key)os.makedirs(os.path.dirname(fpath), exist_ok=True)+ data = obj["body"] if isinstance(obj, dict) else objwith open(fpath, "wb") as f:f.write(data)+ if isinstance(obj, dict):+ meta = {+ "content_type": obj.get("content_type", "application/octet-stream"),+ "content_encoding": obj.get("content_encoding"),+ "etag": obj.get("etag", ""),+ "last_modified": obj.get("last_modified", ""),+ "size": obj.get("size", 0),+ "metadata": obj.get("metadata", {}),+ "preserved_headers": obj.get("preserved_headers", {}),+ }+ with open(fpath + ".meta.json", "w") as mf:+ json.dump(meta, mf)except Exception as e:- logger.warning(f"Failed to persist S3 object: {e}")+ logger.warning("Failed to persist S3 object %s/%s: %s", bucket, key, e)-def _error(code: str, message: str, status: int):- root = Element("Error")- SubElement(root, "Code").text = code- SubElement(root, "Message").text = message- SubElement(root, "RequestId").text = new_uuid()- body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")- return status, {"Content-Type": "application/xml"}, body+def _load_persisted_data():+ if not PERSIST or not os.path.isdir(DATA_DIR):+ return+ try:+ for bucket_name in os.listdir(DATA_DIR):+ bucket_path = os.path.join(DATA_DIR, bucket_name)+ if not os.path.isdir(bucket_path):+ continue+ if bucket_name not in _buckets:+ _buckets[bucket_name] = {"created": now_iso(), "objects": {}, "region": None}+ bucket = _buckets[bucket_name]+ for dirpath, _dirnames, filenames in os.walk(bucket_path):+ for fname in filenames:+ if fname.endswith(".meta.json"):+ continue+ abs_path = os.path.join(dirpath, fname)+ key = os.path.relpath(abs_path, bucket_path)+ meta_path = abs_path + ".meta.json"+ with open(abs_path, "rb") as f:+ data = f.read()+ meta = {}+ if os.path.exists(meta_path):+ try:+ with open(meta_path) as mf:+ meta = json.load(mf)+ except Exception:+ pass+ bucket["objects"][key] = {+ "body": data,+ "content_type": meta.get("content_type", "application/octet-stream"),+ "content_encoding": meta.get("content_encoding"),+ "etag": meta.get("etag") or f'"{md5_hash(data)}"',+ "last_modified": meta.get("last_modified") or now_iso(),+ "size": len(data),+ "metadata": meta.get("metadata", {}),+ "preserved_headers": meta.get("preserved_headers", {}),+ }+ logger.info("Loaded persisted S3 data from %s", DATA_DIR)+ except Exception as e:+ logger.warning("Failed to load persisted S3 data: %s", e)-def _qp(params: dict, key: str, default: str = "") -> str:- val = params.get(key, [default])- if isinstance(val, list):- return val[0] if val else default- return val+_load_persisted_data()+++def reset():+ """Wipe all in-memory state (used by /_ministack/reset)."""+ global _buckets, _bucket_policies, _bucket_notifications, _bucket_tags+ global _bucket_versioning, _bucket_encryption, _bucket_lifecycle, _bucket_cors+ global _bucket_acl, _bucket_websites, _bucket_logging_config+ global _bucket_accelerate_config, _bucket_request_payment_config+ global _object_tags, _multipart_uploads+ for d in (_buckets, _bucket_policies, _bucket_notifications, _bucket_tags,+ _bucket_versioning, _bucket_encryption, _bucket_lifecycle, _bucket_cors,+ _bucket_acl, _bucket_websites, _bucket_logging_config,+ _bucket_accelerate_config, _bucket_request_payment_config,+ _object_tags, _multipart_uploads):+ d.clear()diff --git a/services/secretsmanager.py b/services/secretsmanager.pyindex a16b79e1..61728a8d 100644--- a/services/secretsmanager.py+++ b/services/secretsmanager.py@@ -2,12 +2,19 @@SecretsManager Service Emulator.JSON-based API via X-Amz-Target.Supports: CreateSecret, GetSecretValue, ListSecrets, DeleteSecret,- UpdateSecret, DescribeSecret, PutSecretValue.+ RestoreSecret, UpdateSecret, DescribeSecret, PutSecretValue,+ TagResource, UntagResource, ListSecretVersionIds, RotateSecret,+ GetRandomPassword, ReplicateSecretToRegions,+ PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy,+ ValidateResourcePolicy."""import jsonimport time+import string+import secrets as stdlib_secretsimport logging+import base64from core.responses import json_response, error_response_json, new_uuid@@ -16,9 +23,88 @@ logger = logging.getLogger("secretsmanager")ACCOUNT_ID = "000000000000"REGION = "us-east-1"-_secrets: dict = {} # name -> {arn, name, secret_string, secret_binary, version_id, created, updated, versions}+_secrets: dict = {}+_resource_policies: dict = {}+# name -> {+# ARN, Name, Description, Tags: [{Key, Value}],+# CreatedDate, LastChangedDate, LastAccessedDate,+# DeletedDate (scheduled deletion epoch | None),+# RotationEnabled, RotationLambdaARN, RotationRules,+# ReplicationStatus: [{Region, Status, StatusMessage}],+# Versions: { version_id: {SecretString, SecretBinary, CreatedDate, Stages: [str]} }+# }+# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _resolve(secret_id):+ """Look up a secret by name or ARN. Returns (storage_key, record) or (None, None)."""+ if not secret_id:+ return None, None+ if secret_id in _secrets:+ return secret_id, _secrets[secret_id]+ for key, s in _secrets.items():+ if s["ARN"] == secret_id:+ return key, s+ return None, None+++def _find_stage_version(secret, stage):+ """Return (version_id, version_dict) for the version carrying *stage*."""+ for vid, ver in secret["Versions"].items():+ if stage in ver["Stages"]:+ return vid, ver+ return None, None+++def _apply_current_promotion(secret, new_vid):+ """+ Promote *new_vid* to AWSCURRENT.+ * old AWSCURRENT → AWSPREVIOUS+ * old AWSPREVIOUS → removed (version pruned when stageless)+ """+ old_curr_vid = None+ old_prev_vid = None+ for vid, ver in list(secret["Versions"].items()):+ if vid == new_vid:+ continue+ if "AWSCURRENT" in ver["Stages"]:+ old_curr_vid = vid+ if "AWSPREVIOUS" in ver["Stages"]:+ old_prev_vid = vid++ if old_prev_vid and old_prev_vid in secret["Versions"]:+ stages = secret["Versions"][old_prev_vid]["Stages"]+ if "AWSPREVIOUS" in stages:+ stages.remove("AWSPREVIOUS")+ if not stages:+ del secret["Versions"][old_prev_vid]++ if old_curr_vid and old_curr_vid in secret["Versions"]:+ stages = secret["Versions"][old_curr_vid]["Stages"]+ if "AWSCURRENT" in stages:+ stages.remove("AWSCURRENT")+ if "AWSPREVIOUS" not in stages:+ stages.append("AWSPREVIOUS")++ ver = secret["Versions"].get(new_vid)+ if ver:+ if "AWSCURRENT" not in ver["Stages"]:+ ver["Stages"].append("AWSCURRENT")+ if "AWSPENDING" in ver["Stages"]:+ ver["Stages"].remove("AWSPENDING")+++def _vid_to_stages(secret):+ return {vid: list(ver["Stages"]) for vid, ver in secret["Versions"].items() if ver["Stages"]}+++# ---------------------------------------------------------------------------+# Router+# ---------------------------------------------------------------------------+async def handle_request(method, path, headers, body, query_params):target = headers.get("x-amz-target", "")action = target.split(".")[-1] if "." in target else ""@@ -33,9 +119,20 @@ async def handle_request(method, path, headers, body, query_params):"GetSecretValue": _get_secret_value,"ListSecrets": _list_secrets,"DeleteSecret": _delete_secret,+ "RestoreSecret": _restore_secret,"UpdateSecret": _update_secret,"DescribeSecret": _describe_secret,"PutSecretValue": _put_secret_value,+ "TagResource": _tag_resource,+ "UntagResource": _untag_resource,+ "ListSecretVersionIds": _list_secret_version_ids,+ "RotateSecret": _rotate_secret,+ "GetRandomPassword": _get_random_password,+ "ReplicateSecretToRegions": _replicate_secret_to_regions,+ "PutResourcePolicy": _put_resource_policy,+ "GetResourcePolicy": _get_resource_policy,+ "DeleteResourcePolicy": _delete_resource_policy,+ "ValidateResourcePolicy": _validate_resource_policy,}handler = handlers.get(action)@@ -44,112 +141,567 @@ async def handle_request(method, path, headers, body, query_params):return handler(data)+# ---------------------------------------------------------------------------+# Actions+# ---------------------------------------------------------------------------+def _create_secret(data):name = data.get("Name")if not name:- return error_response_json("InvalidParameterException", "Name required", 400)+ return error_response_json("InvalidParameterException", "Name is required.", 400)if name in _secrets:- return error_response_json("ResourceExistsException", f"Secret {name} already exists", 400)+ return error_response_json(+ "ResourceExistsException",+ f"The operation failed because the secret {name} already exists.", 400,+ )arn = f"arn:aws:secretsmanager:{REGION}:{ACCOUNT_ID}:secret:{name}-{new_uuid()[:6]}"- version_id = new_uuid()+ vid = new_uuid()+ now = time.time()+_secrets[name] = {- "ARN": arn, "Name": name,- "SecretString": data.get("SecretString", ""),- "SecretBinary": data.get("SecretBinary"),- "VersionId": version_id,- "CreatedDate": time.time(),- "LastChangedDate": time.time(),- "VersionIdsToStages": {version_id: ["AWSCURRENT"]},+ "ARN": arn,+ "Name": name,"Description": data.get("Description", ""),+ "Tags": list(data.get("Tags", [])),+ "CreatedDate": now,+ "LastChangedDate": now,+ "LastAccessedDate": None,+ "DeletedDate": None,+ "RotationEnabled": False,+ "RotationLambdaARN": data.get("RotationLambdaARN"),+ "RotationRules": data.get("RotationRules"),+ "ReplicationStatus": [],+ "Versions": {+ vid: {+ "SecretString": data.get("SecretString"),+ "SecretBinary": data.get("SecretBinary"),+ "CreatedDate": now,+ "Stages": ["AWSCURRENT"],+ }+ },}- return json_response({"ARN": arn, "Name": name, "VersionId": version_id})+ return json_response({"ARN": arn, "Name": name, "VersionId": vid})def _get_secret_value(data):- name = data.get("SecretId")- secret = _secrets.get(name)- if not secret:- # Try by ARN- for s in _secrets.values():- if s["ARN"] == name:- secret = s- break+ secret_id = data.get("SecretId")+ _, secret = _resolve(secret_id)if not secret:- return error_response_json("ResourceNotFoundException", f"Secret {name} not found", 400)+ return error_response_json(+ "ResourceNotFoundException",+ "Secrets Manager can't find the specified secret.", 400,+ )+ if secret.get("DeletedDate"):+ return error_response_json(+ "InvalidRequestException",+ "You can't perform this operation on the secret because it was marked for deletion.", 400,+ )++ secret["LastAccessedDate"] = time.time()++ req_vid = data.get("VersionId")+ req_stage = data.get("VersionStage", "AWSCURRENT")++ if req_vid:+ ver = secret["Versions"].get(req_vid)+ if not ver:+ return error_response_json(+ "ResourceNotFoundException",+ f"Secrets Manager can't find the specified secret version: {req_vid}.", 400,+ )+ vid = req_vid+ else:+ vid, ver = _find_stage_version(secret, req_stage)+ if not ver:+ return error_response_json(+ "ResourceNotFoundException",+ f"Secrets Manager can't find the specified secret value for staging label: {req_stage}.", 400,+ )result = {- "ARN": secret["ARN"], "Name": secret["Name"],- "VersionId": secret["VersionId"],- "VersionStages": ["AWSCURRENT"],- "CreatedDate": secret["CreatedDate"],+ "ARN": secret["ARN"],+ "Name": secret["Name"],+ "VersionId": vid,+ "VersionStages": list(ver["Stages"]),+ "CreatedDate": ver["CreatedDate"],}- if secret.get("SecretString"):- result["SecretString"] = secret["SecretString"]- if secret.get("SecretBinary"):- result["SecretBinary"] = secret["SecretBinary"]+ if ver.get("SecretString") is not None:+ result["SecretString"] = ver["SecretString"]+ if ver.get("SecretBinary") is not None:+ result["SecretBinary"] = ver["SecretBinary"]return json_response(result)def _list_secrets(data):- secrets_list = []- for s in _secrets.values():- secrets_list.append({- "ARN": s["ARN"], "Name": s["Name"],- "LastChangedDate": s["LastChangedDate"],+ max_results = min(data.get("MaxResults", 100), 100)+ next_token = data.get("NextToken")+ filters = data.get("Filters", [])++ names = sorted(n for n, s in _secrets.items() if not s.get("DeletedDate"))++ for f in filters:+ key = f.get("Key", "")+ values = [v.lower() for v in f.get("Values", [])]+ if key == "name":+ names = [n for n in names if any(v in n.lower() for v in values)]+ elif key == "tag-key":+ names = [n for n in names+ if any(t.get("Key", "").lower() in values for t in _secrets[n].get("Tags", []))]+ elif key == "tag-value":+ names = [n for n in names+ if any(t.get("Value", "").lower() in values for t in _secrets[n].get("Tags", []))]+ elif key == "description":+ names = [n for n in names+ if any(v in _secrets[n].get("Description", "").lower() for v in values)]++ start = 0+ if next_token:+ try:+ start = int(base64.b64decode(next_token))+ except Exception:+ pass++ page = names[start:start + max_results]+ secret_list = []+ for n in page:+ s = _secrets[n]+ secret_list.append({+ "ARN": s["ARN"],+ "Name": s["Name"],"Description": s.get("Description", ""),+ "CreatedDate": s["CreatedDate"],+ "LastChangedDate": s["LastChangedDate"],+ "LastAccessedDate": s.get("LastAccessedDate"),+ "Tags": s.get("Tags", []),+ "SecretVersionsToStages": _vid_to_stages(s),+ "RotationEnabled": s.get("RotationEnabled", False),})- return json_response({"SecretList": secrets_list})++ resp: dict = {"SecretList": secret_list}+ end = start + max_results+ if end < len(names):+ resp["NextToken"] = base64.b64encode(str(end).encode()).decode()+ return json_response(resp)def _delete_secret(data):- name = data.get("SecretId")- secret = _secrets.pop(name, None)+ secret_id = data.get("SecretId")+ key, secret = _resolve(secret_id)if not secret:- return error_response_json("ResourceNotFoundException", f"Secret {name} not found", 400)- return json_response({"ARN": secret["ARN"], "Name": secret["Name"], "DeletionDate": time.time()})+ return error_response_json(+ "ResourceNotFoundException",+ "Secrets Manager can't find the specified secret.", 400,+ )+ if secret.get("DeletedDate"):+ return error_response_json(+ "InvalidRequestException",+ "You can't perform this operation on the secret because it was already scheduled for deletion.", 400,+ )++ force = data.get("ForceDeleteWithoutRecovery", False)+ window = data.get("RecoveryWindowInDays")++ if force and window is not None:+ return error_response_json(+ "InvalidParameterException",+ "You can't use ForceDeleteWithoutRecovery in conjunction with RecoveryWindowInDays.", 400,+ )+ if window is None:+ window = 30+ if not force and not (7 <= window <= 30):+ return error_response_json(+ "InvalidParameterException",+ "RecoveryWindowInDays value must be between 7 and 30 days (inclusive).", 400,+ )++ now = time.time()+ deletion_date = now if force else now + window * 86400++ if force:+ arn, sname = secret["ARN"], secret["Name"]+ del _secrets[key]+ return json_response({"ARN": arn, "Name": sname, "DeletionDate": deletion_date})++ secret["DeletedDate"] = deletion_date+ return json_response({"ARN": secret["ARN"], "Name": secret["Name"], "DeletionDate": deletion_date})+++def _restore_secret(data):+ secret_id = data.get("SecretId")+ _, secret = _resolve(secret_id)+ if not secret:+ return error_response_json(+ "ResourceNotFoundException",+ "Secrets Manager can't find the specified secret.", 400,+ )+ if not secret.get("DeletedDate"):+ return error_response_json(+ "InvalidRequestException",+ "Secret is not scheduled for deletion.", 400,+ )+ secret["DeletedDate"] = None+ return json_response({"ARN": secret["ARN"], "Name": secret["Name"]})def _update_secret(data):- name = data.get("SecretId")- secret = _secrets.get(name)+ secret_id = data.get("SecretId")+ _, secret = _resolve(secret_id)if not secret:- return error_response_json("ResourceNotFoundException", f"Secret {name} not found", 400)- if "SecretString" in data:- secret["SecretString"] = data["SecretString"]- if "SecretBinary" in data:- secret["SecretBinary"] = data["SecretBinary"]- version_id = new_uuid()- secret["VersionId"] = version_id- secret["LastChangedDate"] = time.time()- return json_response({"ARN": secret["ARN"], "Name": name, "VersionId": version_id})+ return error_response_json(+ "ResourceNotFoundException",+ "Secrets Manager can't find the specified secret.", 400,+ )+ if secret.get("DeletedDate"):+ return error_response_json(+ "InvalidRequestException",+ "You can't perform this operation on the secret because it was marked for deletion.", 400,+ )++ if "Description" in data:+ secret["Description"] = data["Description"]++ has_new_value = "SecretString" in data or "SecretBinary" in data+ if not has_new_value:+ secret["LastChangedDate"] = time.time()+ return json_response({"ARN": secret["ARN"], "Name": secret["Name"]})++ vid = new_uuid()+ now = time.time()+ secret["Versions"][vid] = {+ "SecretString": data.get("SecretString"),+ "SecretBinary": data.get("SecretBinary"),+ "CreatedDate": now,+ "Stages": [],+ }+ _apply_current_promotion(secret, vid)+ secret["LastChangedDate"] = now+ return json_response({"ARN": secret["ARN"], "Name": secret["Name"], "VersionId": vid})def _describe_secret(data):- name = data.get("SecretId")- secret = _secrets.get(name)+ secret_id = data.get("SecretId")+ _, secret = _resolve(secret_id)if not secret:- return error_response_json("ResourceNotFoundException", f"Secret {name} not found", 400)- return json_response({- "ARN": secret["ARN"], "Name": secret["Name"],+ return error_response_json(+ "ResourceNotFoundException",+ "Secrets Manager can't find the specified secret.", 400,+ )++ result = {+ "ARN": secret["ARN"],+ "Name": secret["Name"],"Description": secret.get("Description", ""),- "LastChangedDate": secret["LastChangedDate"],"CreatedDate": secret["CreatedDate"],- "VersionIdsToStages": secret["VersionIdsToStages"],- })+ "LastChangedDate": secret["LastChangedDate"],+ "LastAccessedDate": secret.get("LastAccessedDate"),+ "Tags": secret.get("Tags", []),+ "VersionIdsToStages": _vid_to_stages(secret),+ "RotationEnabled": secret.get("RotationEnabled", False),+ }+ if secret.get("DeletedDate"):+ result["DeletedDate"] = secret["DeletedDate"]+ if secret.get("RotationLambdaARN"):+ result["RotationLambdaARN"] = secret["RotationLambdaARN"]+ if secret.get("RotationRules"):+ result["RotationRules"] = secret["RotationRules"]+ if secret.get("ReplicationStatus"):+ result["ReplicationStatus"] = secret["ReplicationStatus"]+ return json_response(result)def _put_secret_value(data):- name = data.get("SecretId")- secret = _secrets.get(name)+ secret_id = data.get("SecretId")+ _, secret = _resolve(secret_id)+ if not secret:+ return error_response_json(+ "ResourceNotFoundException",+ "Secrets Manager can't find the specified secret.", 400,+ )+ if secret.get("DeletedDate"):+ return error_response_json(+ "InvalidRequestException",+ "You can't perform this operation on the secret because it was marked for deletion.", 400,+ )++ vid = data.get("ClientRequestToken", new_uuid())+ stages = data.get("VersionStages", ["AWSCURRENT"])+ now = time.time()++ secret["Versions"][vid] = {+ "SecretString": data.get("SecretString"),+ "SecretBinary": data.get("SecretBinary"),+ "CreatedDate": now,+ "Stages": [],+ }++ if "AWSCURRENT" in stages:+ _apply_current_promotion(secret, vid)+ else:+ secret["Versions"][vid]["Stages"] = list(stages)++ secret["LastChangedDate"] = now+ return json_response({+ "ARN": secret["ARN"],+ "Name": secret["Name"],+ "VersionId": vid,+ "VersionStages": list(secret["Versions"][vid]["Stages"]),+ })+++def _tag_resource(data):+ secret_id = data.get("SecretId")+ _, secret = _resolve(secret_id)+ if not secret:+ return error_response_json(+ "ResourceNotFoundException",+ "Secrets Manager can't find the specified secret.", 400,+ )+ existing = {t["Key"]: t for t in secret.get("Tags", [])}+ for t in data.get("Tags", []):+ existing[t["Key"]] = t+ secret["Tags"] = list(existing.values())+ return json_response({})+++def _untag_resource(data):+ secret_id = data.get("SecretId")+ _, secret = _resolve(secret_id)+ if not secret:+ return error_response_json(+ "ResourceNotFoundException",+ "Secrets Manager can't find the specified secret.", 400,+ )+ keys_to_remove = set(data.get("TagKeys", []))+ secret["Tags"] = [t for t in secret.get("Tags", []) if t["Key"] not in keys_to_remove]+ return json_response({})+++def _list_secret_version_ids(data):+ secret_id = data.get("SecretId")+ _, secret = _resolve(secret_id)+ if not secret:+ return error_response_json(+ "ResourceNotFoundException",+ "Secrets Manager can't find the specified secret.", 400,+ )++ max_results = min(data.get("MaxResults", 100), 100)+ next_token = data.get("NextToken")++ all_vids = sorted(secret["Versions"].keys())+ start = 0+ if next_token:+ try:+ start = int(base64.b64decode(next_token))+ except Exception:+ pass++ page = all_vids[start:start + max_results]+ versions = []+ for vid in page:+ ver = secret["Versions"][vid]+ versions.append({+ "VersionId": vid,+ "VersionStages": list(ver["Stages"]),+ "CreatedDate": ver["CreatedDate"],+ })++ resp: dict = {+ "ARN": secret["ARN"],+ "Name": secret["Name"],+ "Versions": versions,+ }+ end = start + max_results+ if end < len(all_vids):+ resp["NextToken"] = base64.b64encode(str(end).encode()).decode()+ return json_response(resp)+++def _rotate_secret(data):+ secret_id = data.get("SecretId")+ _, secret = _resolve(secret_id)if not secret:- return error_response_json("ResourceNotFoundException", f"Secret {name} not found", 400)- if "SecretString" in data:- secret["SecretString"] = data["SecretString"]- if "SecretBinary" in data:- secret["SecretBinary"] = data["SecretBinary"]- version_id = new_uuid()- secret["VersionId"] = version_id- secret["LastChangedDate"] = time.time()- secret["VersionIdsToStages"][version_id] = ["AWSCURRENT"]- return json_response({"ARN": secret["ARN"], "Name": name, "VersionId": version_id, "VersionStages": ["AWSCURRENT"]})+ return error_response_json(+ "ResourceNotFoundException",+ "Secrets Manager can't find the specified secret.", 400,+ )+ if secret.get("DeletedDate"):+ return error_response_json(+ "InvalidRequestException",+ "You can't perform this operation on the secret because it was marked for deletion.", 400,+ )++ lambda_arn = data.get("RotationLambdaARN") or secret.get("RotationLambdaARN")+ rotation_rules = data.get("RotationRules") or secret.get("RotationRules")++ if lambda_arn:+ secret["RotationLambdaARN"] = lambda_arn+ if rotation_rules:+ secret["RotationRules"] = rotation_rules+ secret["RotationEnabled"] = True++ vid = data.get("ClientRequestToken", new_uuid())+ now = time.time()++ curr_vid, curr_ver = _find_stage_version(secret, "AWSCURRENT")+ secret["Versions"][vid] = {+ "SecretString": curr_ver["SecretString"] if curr_ver else None,+ "SecretBinary": curr_ver["SecretBinary"] if curr_ver else None,+ "CreatedDate": now,+ "Stages": ["AWSPENDING"],+ }++ logger.info("RotateSecret stub for %s (Lambda: %s)", secret["Name"], lambda_arn)++ _apply_current_promotion(secret, vid)+ secret["LastChangedDate"] = now++ return json_response({"ARN": secret["ARN"], "Name": secret["Name"], "VersionId": vid})+++def _get_random_password(data):+ length = data.get("PasswordLength", 32)+ if not (1 <= length <= 4096):+ return error_response_json(+ "InvalidParameterException",+ "PasswordLength must be between 1 and 4096.", 400,+ )++ exclude_chars = set(data.get("ExcludeCharacters", ""))+ exclude_numbers = data.get("ExcludeNumbers", False)+ exclude_punctuation = data.get("ExcludePunctuation", False)+ exclude_upper = data.get("ExcludeUppercase", False)+ exclude_lower = data.get("ExcludeLowercase", False)+ include_space = data.get("IncludeSpace", False)+ require_each = data.get("RequireEachIncludedType", True)++ pools: list[list[str]] = []+ all_chars: list[str] = []++ def _add_pool(chars):+ filtered = [c for c in chars if c not in exclude_chars]+ if filtered:+ pools.append(filtered)+ all_chars.extend(filtered)++ if not exclude_lower:+ _add_pool(string.ascii_lowercase)+ if not exclude_upper:+ _add_pool(string.ascii_uppercase)+ if not exclude_numbers:+ _add_pool(string.digits)+ if not exclude_punctuation:+ _add_pool(string.punctuation)+ if include_space:+ _add_pool([" "])++ if not all_chars:+ return error_response_json(+ "InvalidParameterException",+ "No characters available to generate password.", 400,+ )+ if require_each and len(pools) > length:+ return error_response_json(+ "InvalidParameterException",+ "PasswordLength too short to include required character types.", 400,+ )++ rng = stdlib_secrets.SystemRandom()+ pw: list[str] = []+ if require_each:+ for pool in pools:+ pw.append(stdlib_secrets.choice(pool))+ for _ in range(length - len(pw)):+ pw.append(stdlib_secrets.choice(all_chars))+ rng.shuffle(pw)+ else:+ for _ in range(length):+ pw.append(stdlib_secrets.choice(all_chars))++ return json_response({"RandomPassword": "".join(pw)})+++def _replicate_secret_to_regions(data):+ secret_id = data.get("SecretId")+ _, secret = _resolve(secret_id)+ if not secret:+ return error_response_json(+ "ResourceNotFoundException",+ "Secrets Manager can't find the specified secret.", 400,+ )++ for r in data.get("AddReplicaRegions", []):+ region = r.get("Region")+ secret["ReplicationStatus"].append({+ "Region": region,+ "Status": "InSync",+ "StatusMessage": "Replication succeeded (stub).",+ })++ logger.info(+ "ReplicateSecretToRegions stub for %s, regions=%s",+ secret["Name"],+ [r.get("Region") for r in data.get("AddReplicaRegions", [])],+ )++ return json_response({+ "ARN": secret["ARN"],+ "ReplicationStatus": secret["ReplicationStatus"],+ })+++# ---------------------------------------------------------------------------+# Resource policies+# ---------------------------------------------------------------------------++def _put_resource_policy(data):+ secret_id = data.get("SecretId")+ _, secret = _resolve(secret_id)+ if not secret:+ return error_response_json(+ "ResourceNotFoundException",+ "Secrets Manager can't find the specified secret.", 400,+ )+ policy = data.get("ResourcePolicy", "{}")+ _resource_policies[secret["ARN"]] = policy+ return json_response({"ARN": secret["ARN"], "Name": secret["Name"]})+++def _get_resource_policy(data):+ secret_id = data.get("SecretId")+ _, secret = _resolve(secret_id)+ if not secret:+ return error_response_json(+ "ResourceNotFoundException",+ "Secrets Manager can't find the specified secret.", 400,+ )+ policy = _resource_policies.get(secret["ARN"])+ result = {"ARN": secret["ARN"], "Name": secret["Name"]}+ if policy is not None:+ result["ResourcePolicy"] = policy+ return json_response(result)+++def _delete_resource_policy(data):+ secret_id = data.get("SecretId")+ _, secret = _resolve(secret_id)+ if not secret:+ return error_response_json(+ "ResourceNotFoundException",+ "Secrets Manager can't find the specified secret.", 400,+ )+ _resource_policies.pop(secret["ARN"], None)+ return json_response({"ARN": secret["ARN"], "Name": secret["Name"]})+++def _validate_resource_policy(data):+ return json_response({+ "PolicyValidationPassed": True,+ "ValidationErrors": [],+ })+++def reset():+ _secrets.clear()+ _resource_policies.clear()diff --git a/services/ses.py b/services/ses.pyindex ecee75d9..7d60093b 100644--- a/services/ses.py+++ b/services/ses.py@@ -1,15 +1,37 @@"""-SES (Simple Email Service) Emulator.-Query API (Action=...) via POST form body.-Supports: SendEmail, SendRawEmail, VerifyEmailIdentity, VerifyEmailAddress,- ListIdentities, GetIdentityVerificationAttributes, DeleteIdentity,- GetSendQuota, GetSendStatistics.-All emails are stored in-memory (not actually sent).+SES (Simple Email Service) Emulator — v1 Query API + v2 REST/JSON API.++v1 Query API (Action=...) via POST form body.+v2 JSON API detected via path prefix /v2/ or X-Amz-Target containing "sesv2".++v1 actions: SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail,+ VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity,+ VerifyDomainDkim, ListIdentities, GetIdentityVerificationAttributes,+ DeleteIdentity, GetSendQuota, GetSendStatistics,+ ListVerifiedEmailAddresses, CreateConfigurationSet,+ DeleteConfigurationSet, DescribeConfigurationSet,+ ListConfigurationSets, CreateTemplate, GetTemplate, DeleteTemplate,+ ListTemplates, UpdateTemplate, GetIdentityDkimAttributes,+ SetIdentityNotificationTopic, SetIdentityFeedbackForwardingEnabled.++v2 REST endpoints under /v2/email/:+ outbound-emails, outbound-bulk-emails, identities, configuration-sets,+ templates, account.++All emails stored in-memory for test inspection.+Send statistics aggregated into 15-minute buckets per AWS spec."""-import time+import base64+import hashlib+import jsonimport logging-from urllib.parse import parse_qs+import re+import time+from datetime import datetime, timezone+from email import message_from_bytes+from email.policy import default as default_policy+from urllib.parse import parse_qs, unquotefrom core.responses import new_uuid@@ -18,11 +40,23 @@ logger = logging.getLogger("ses")ACCOUNT_ID = "000000000000"REGION = "us-east-1"-_identities: dict = {} # email/domain -> {verified, type}-_sent_emails: list = [] # log of sent emails+_identities: dict = {}+_sent_emails: list = []+_templates: dict = {}+_configuration_sets: dict = {}+# ---------------------------------------------------------------------------+# Entry point+# ---------------------------------------------------------------------------+async def handle_request(method, path, headers, body, query_params):+ target = headers.get("x-amz-target", "")+ is_v2 = path.startswith("/v2/") or "sesv2" in target.lower()++ if is_v2:+ return _handle_v2(method, path, headers, body)+params = dict(query_params)if method == "POST" and body:form_params = parse_qs(body.decode("utf-8", errors="replace"))@@ -34,14 +68,30 @@ async def handle_request(method, path, headers, body, query_params):handlers = {"SendEmail": _send_email,"SendRawEmail": _send_raw_email,+ "SendTemplatedEmail": _send_templated_email,+ "SendBulkTemplatedEmail": _send_bulk_templated_email,"VerifyEmailIdentity": _verify_email_identity,- "VerifyEmailAddress": _verify_email_identity, # legacy alias+ "VerifyEmailAddress": _verify_email_identity,+ "VerifyDomainIdentity": _verify_domain_identity,+ "VerifyDomainDkim": _verify_domain_dkim,"ListIdentities": _list_identities,"GetIdentityVerificationAttributes": _get_identity_verification_attributes,"DeleteIdentity": _delete_identity,"GetSendQuota": _get_send_quota,"GetSendStatistics": _get_send_statistics,"ListVerifiedEmailAddresses": _list_verified_emails,+ "CreateConfigurationSet": _create_configuration_set,+ "DeleteConfigurationSet": _delete_configuration_set,+ "DescribeConfigurationSet": _describe_configuration_set,+ "ListConfigurationSets": _list_configuration_sets,+ "CreateTemplate": _create_template,+ "GetTemplate": _get_template,+ "DeleteTemplate": _delete_template,+ "ListTemplates": _list_templates,+ "UpdateTemplate": _update_template,+ "GetIdentityDkimAttributes": _get_identity_dkim_attributes,+ "SetIdentityNotificationTopic": _set_identity_notification_topic,+ "SetIdentityFeedbackForwardingEnabled": _set_identity_feedback_forwarding,}handler = handlers.get(action)@@ -50,19 +100,23 @@ async def handle_request(method, path, headers, body, query_params):return handler(params)+# ---------------------------------------------------------------------------+# v1 — Send operations+# ---------------------------------------------------------------------------+def _send_email(params):source = _p(params, "Source")subject = _p(params, "Message.Subject.Data")body_text = _p(params, "Message.Body.Text.Data")body_html = _p(params, "Message.Body.Html.Data")+ config_set = _p(params, "ConfigurationSetName")- # Collect To/CC/BCC addressesto_addrs = _collect_list(params, "Destination.ToAddresses.member")cc_addrs = _collect_list(params, "Destination.CcAddresses.member")bcc_addrs = _collect_list(params, "Destination.BccAddresses.member")msg_id = f"{new_uuid()}@email.amazonses.com"- _sent_emails.append({+ record = {"MessageId": msg_id,"Source": source,"To": to_addrs,@@ -72,27 +126,164 @@ def _send_email(params):"BodyText": body_text,"BodyHtml": body_html,"Timestamp": time.time(),- })+ "Type": "SendEmail",+ }+ if config_set:+ record["ConfigurationSetName"] = config_set+ _sent_emails.append(record)logger.info(f"SES SendEmail: {source} -> {to_addrs} | {subject}")- return _xml(200, "SendEmailResponse", f"<SendEmailResult><MessageId>{msg_id}</MessageId></SendEmailResult>")+ return _xml(200, "SendEmailResponse",+ f"<SendEmailResult><MessageId>{msg_id}</MessageId></SendEmailResult>")def _send_raw_email(params):- raw_message = _p(params, "RawMessage.Data")+ raw_b64 = _p(params, "RawMessage.Data")+ source = _p(params, "Source")msg_id = f"{new_uuid()}@email.amazonses.com"- _sent_emails.append({++ parsed = _parse_raw_mime(raw_b64)++ record = {"MessageId": msg_id,- "RawMessage": raw_message,+ "Source": source or parsed.get("From", ""),+ "RawMessage": raw_b64,+ "Parsed": parsed,"Timestamp": time.time(),- })+ "Type": "SendRawEmail",+ }+ _sent_emails.append(record)logger.info(f"SES SendRawEmail: {msg_id}")- return _xml(200, "SendRawEmailResponse", f"<SendRawEmailResult><MessageId>{msg_id}</MessageId></SendRawEmailResult>")+ return _xml(200, "SendRawEmailResponse",+ f"<SendRawEmailResult><MessageId>{msg_id}</MessageId></SendRawEmailResult>")+def _send_templated_email(params):+ source = _p(params, "Source")+ template_name = _p(params, "Template")+ template_data = _p(params, "TemplateData")+ config_set = _p(params, "ConfigurationSetName")++ to_addrs = _collect_list(params, "Destination.ToAddresses.member")+ cc_addrs = _collect_list(params, "Destination.CcAddresses.member")+ bcc_addrs = _collect_list(params, "Destination.BccAddresses.member")++ if template_name not in _templates:+ return _error("TemplateDoesNotExist",+ f"Template {template_name} does not exist", 400)++ rendered = _render_template(_templates[template_name], template_data)+ msg_id = f"{new_uuid()}@email.amazonses.com"+ record = {+ "MessageId": msg_id,+ "Source": source,+ "To": to_addrs,+ "CC": cc_addrs,+ "BCC": bcc_addrs,+ "Template": template_name,+ "TemplateData": template_data,+ "RenderedSubject": rendered.get("Subject", ""),+ "RenderedBodyText": rendered.get("Text", ""),+ "RenderedBodyHtml": rendered.get("Html", ""),+ "Timestamp": time.time(),+ "Type": "SendTemplatedEmail",+ }+ if config_set:+ record["ConfigurationSetName"] = config_set+ _sent_emails.append(record)+ logger.info(f"SES SendTemplatedEmail: {source} -> {to_addrs} | template={template_name}")+ return _xml(200, "SendTemplatedEmailResponse",+ f"<SendTemplatedEmailResult><MessageId>{msg_id}</MessageId></SendTemplatedEmailResult>")+++def _send_bulk_templated_email(params):+ source = _p(params, "Source")+ template_name = _p(params, "Template")+ default_template_data = _p(params, "DefaultTemplateData")+ config_set = _p(params, "ConfigurationSetName")++ if template_name not in _templates:+ return _error("TemplateDoesNotExist",+ f"Template {template_name} does not exist", 400)++ template = _templates[template_name]+ destinations = []+ i = 1+ while _p(params, f"Destinations.member.{i}.Destination.ToAddresses.member.1"):+ to_addrs = _collect_list(+ params, f"Destinations.member.{i}.Destination.ToAddresses.member")+ replacement = (_p(params, f"Destinations.member.{i}.ReplacementTemplateData")+ or default_template_data)+ destinations.append({"To": to_addrs, "TemplateData": replacement})+ i += 1++ statuses = []+ for dest in destinations:+ msg_id = f"{new_uuid()}@email.amazonses.com"+ rendered = _render_template(template, dest["TemplateData"])+ record = {+ "MessageId": msg_id,+ "Source": source,+ "To": dest["To"],+ "Template": template_name,+ "TemplateData": dest["TemplateData"],+ "RenderedSubject": rendered.get("Subject", ""),+ "Timestamp": time.time(),+ "Type": "SendBulkTemplatedEmail",+ }+ if config_set:+ record["ConfigurationSetName"] = config_set+ _sent_emails.append(record)+ statuses.append(+ f"<member><Status>Success</Status>"+ f"<MessageId>{msg_id}</MessageId></member>")++ logger.info(f"SES SendBulkTemplatedEmail: {source} | template={template_name} | "+ f"{len(destinations)} destinations")+ return _xml(200, "SendBulkTemplatedEmailResponse",+ f"<SendBulkTemplatedEmailResult>"+ f"<Status>{''.join(statuses)}</Status>"+ f"</SendBulkTemplatedEmailResult>")+++# ---------------------------------------------------------------------------+# v1 — Identity operations+# ---------------------------------------------------------------------------+def _verify_email_identity(params):email = _p(params, "EmailAddress")- _identities[email] = {"VerificationStatus": "Success", "Type": "EmailAddress"}- return _xml(200, "VerifyEmailIdentityResponse", "<VerifyEmailIdentityResult/>")+ _identities[email] = _make_identity(email, "EmailAddress")+ return _xml(200, "VerifyEmailIdentityResponse",+ "<VerifyEmailIdentityResult/>")+++def _verify_domain_identity(params):+ domain = _p(params, "Domain")+ _identities[domain] = _make_identity(domain, "Domain")+ token = hashlib.md5(domain.encode()).hexdigest()[:32]+ return _xml(200, "VerifyDomainIdentityResponse",+ f"<VerifyDomainIdentityResult>"+ f"<VerificationToken>{token}</VerificationToken>"+ f"</VerifyDomainIdentityResult>")+++def _verify_domain_dkim(params):+ domain = _p(params, "Domain")+ if domain not in _identities:+ _identities[domain] = _make_identity(domain, "Domain")++ tokens = [+ hashlib.md5(f"{domain}-dkim-{i}".encode()).hexdigest()[:32]+ for i in range(3)+ ]+ _identities[domain]["DkimEnabled"] = True+ _identities[domain]["DkimTokens"] = tokens+ _identities[domain]["DkimVerificationStatus"] = "Success"++ members = "".join(f"<member>{t}</member>" for t in tokens)+ return _xml(200, "VerifyDomainDkimResponse",+ f"<VerifyDomainDkimResult>"+ f"<DkimTokens>{members}</DkimTokens>"+ f"</VerifyDomainDkimResult>")def _list_identities(params):@@ -101,20 +292,25 @@ def _list_identities(params):for identity, info in _identities.items():if not identity_type or info["Type"] == identity_type:members += f"<member>{identity}</member>"- return _xml(200, "ListIdentitiesResponse", f"<ListIdentitiesResult><Identities>{members}</Identities></ListIdentitiesResult>")+ return _xml(200, "ListIdentitiesResponse",+ f"<ListIdentitiesResult>"+ f"<Identities>{members}</Identities>"+ f"</ListIdentitiesResult>")def _get_identity_verification_attributes(params):identities = _collect_list(params, "Identities.member")entries = ""for identity in identities:- info = _identities.get(identity, {"VerificationStatus": "Pending"})- entries += f"""<entry>- <key>{identity}</key>- <value><VerificationStatus>{info['VerificationStatus']}</VerificationStatus></value>- </entry>"""+ info = _identities.get(identity)+ status = info["VerificationStatus"] if info else "Pending"+ entries += (f"<entry><key>{identity}</key>"+ f"<value><VerificationStatus>{status}"+ f"</VerificationStatus></value></entry>")return _xml(200, "GetIdentityVerificationAttributesResponse",- f"<GetIdentityVerificationAttributesResult><VerificationAttributes>{entries}</VerificationAttributes></GetIdentityVerificationAttributesResult>")+ f"<GetIdentityVerificationAttributesResult>"+ f"<VerificationAttributes>{entries}</VerificationAttributes>"+ f"</GetIdentityVerificationAttributesResult>")def _delete_identity(params):@@ -123,34 +319,636 @@ def _delete_identity(params):return _xml(200, "DeleteIdentityResponse", "")+def _list_verified_emails(params):+ members = "".join(+ f"<member>{e}</member>"+ for e, info in _identities.items()+ if info["VerificationStatus"] == "Success" and info["Type"] == "EmailAddress"+ )+ return _xml(200, "ListVerifiedEmailAddressesResponse",+ f"<ListVerifiedEmailAddressesResult>"+ f"<VerifiedEmailAddresses>{members}</VerifiedEmailAddresses>"+ f"</ListVerifiedEmailAddressesResult>")+++def _get_identity_dkim_attributes(params):+ identities = _collect_list(params, "Identities.member")+ entries = ""+ for identity in identities:+ info = _identities.get(identity, {})+ enabled = "true" if info.get("DkimEnabled") else "false"+ status = info.get("DkimVerificationStatus", "NotStarted")+ tokens_xml = "".join(+ f"<member>{t}</member>" for t in info.get("DkimTokens", []))+ entries += (f"<entry><key>{identity}</key><value>"+ f"<DkimEnabled>{enabled}</DkimEnabled>"+ f"<DkimVerificationStatus>{status}</DkimVerificationStatus>"+ f"<DkimTokens>{tokens_xml}</DkimTokens>"+ f"</value></entry>")+ return _xml(200, "GetIdentityDkimAttributesResponse",+ f"<GetIdentityDkimAttributesResult>"+ f"<DkimAttributes>{entries}</DkimAttributes>"+ f"</GetIdentityDkimAttributesResult>")+++def _set_identity_notification_topic(params):+ identity = _p(params, "Identity")+ notification_type = _p(params, "NotificationType")+ sns_topic = _p(params, "SnsTopic")+ if identity in _identities:+ _identities[identity]["NotificationTopics"][notification_type] = sns_topic+ return _xml(200, "SetIdentityNotificationTopicResponse", "")+++def _set_identity_feedback_forwarding(params):+ identity = _p(params, "Identity")+ enabled = _p(params, "ForwardingEnabled").lower() == "true"+ if identity in _identities:+ _identities[identity]["FeedbackForwardingEnabled"] = enabled+ return _xml(200, "SetIdentityFeedbackForwardingEnabledResponse", "")+++# ---------------------------------------------------------------------------+# v1 — Quota / statistics (bugs fixed)+# ---------------------------------------------------------------------------+def _get_send_quota(params):- return _xml(200, "GetSendQuotaResponse", """<GetSendQuotaResult>- <Max24HourSend>50000.0</Max24HourSend>- <MaxSendRate>14.0</MaxSendRate>- <SentLast24Hours>0.0</SentLast24Hours>- </GetSendQuotaResult>""")+ cutoff = time.time() - 86400+ sent_24h = sum(1 for e in _sent_emails if e["Timestamp"] >= cutoff)+ return _xml(200, "GetSendQuotaResponse",+ f"<GetSendQuotaResult>"+ f"<Max24HourSend>50000.0</Max24HourSend>"+ f"<MaxSendRate>14.0</MaxSendRate>"+ f"<SentLast24Hours>{float(sent_24h)}</SentLast24Hours>"+ f"</GetSendQuotaResult>")def _get_send_statistics(params):+ buckets = _aggregate_15min_buckets()members = ""- for email in _sent_emails[-100:]:- members += f"""<member>- <Timestamp>{email['Timestamp']}</Timestamp>- <DeliveryAttempts>1</DeliveryAttempts>- <Bounces>0</Bounces>- <Complaints>0</Complaints>- <Rejects>0</Rejects>- </member>"""- return _xml(200, "GetSendStatisticsResponse", f"<GetSendStatisticsResult><SendDataPoints>{members}</SendDataPoints></GetSendStatisticsResult>")+ for bucket in buckets:+ ts = datetime.fromtimestamp(+ bucket["Timestamp"], tz=timezone.utc+ ).strftime("%Y-%m-%dT%H:%M:%SZ")+ members += (f"<member>"+ f"<Timestamp>{ts}</Timestamp>"+ f"<DeliveryAttempts>{bucket['DeliveryAttempts']}</DeliveryAttempts>"+ f"<Bounces>{bucket['Bounces']}</Bounces>"+ f"<Complaints>{bucket['Complaints']}</Complaints>"+ f"<Rejects>{bucket['Rejects']}</Rejects>"+ f"</member>")+ return _xml(200, "GetSendStatisticsResponse",+ f"<GetSendStatisticsResult>"+ f"<SendDataPoints>{members}</SendDataPoints>"+ f"</GetSendStatisticsResult>")+++# ---------------------------------------------------------------------------+# v1 — Configuration sets+# ---------------------------------------------------------------------------++def _create_configuration_set(params):+ name = _p(params, "ConfigurationSet.Name")+ if not name:+ return _error("ValidationError",+ "ConfigurationSet.Name is required", 400)+ if name in _configuration_sets:+ return _error("ConfigurationSetAlreadyExists",+ f"Configuration set {name} already exists", 400)+ _configuration_sets[name] = {+ "Name": name,+ "CreatedTimestamp": _iso_now(),+ }+ return _xml(200, "CreateConfigurationSetResponse", "<CreateConfigurationSetResult/>")+++def _delete_configuration_set(params):+ name = _p(params, "ConfigurationSetName")+ if name not in _configuration_sets:+ return _error("ConfigurationSetDoesNotExist",+ f"Configuration set {name} does not exist", 400)+ del _configuration_sets[name]+ return _xml(200, "DeleteConfigurationSetResponse", "<DeleteConfigurationSetResult/>")+++def _describe_configuration_set(params):+ name = _p(params, "ConfigurationSetName")+ cs = _configuration_sets.get(name)+ if not cs:+ return _error("ConfigurationSetDoesNotExist",+ f"Configuration set {name} does not exist", 400)+ return _xml(200, "DescribeConfigurationSetResponse",+ f"<DescribeConfigurationSetResult>"+ f"<ConfigurationSet><Name>{cs['Name']}</Name></ConfigurationSet>"+ f"</DescribeConfigurationSetResult>")+++def _list_configuration_sets(params):+ members = "".join(+ f"<member><Name>{cs['Name']}</Name></member>"+ for cs in _configuration_sets.values()+ )+ return _xml(200, "ListConfigurationSetsResponse",+ f"<ListConfigurationSetsResult>"+ f"<ConfigurationSets>{members}</ConfigurationSets>"+ f"</ListConfigurationSetsResult>")+++# ---------------------------------------------------------------------------+# v1 — Templates+# ---------------------------------------------------------------------------++def _create_template(params):+ name = _p(params, "Template.TemplateName")+ if not name:+ return _error("ValidationError",+ "Template.TemplateName is required", 400)+ if name in _templates:+ return _error("AlreadyExists",+ f"Template {name} already exists", 400)+ _templates[name] = {+ "TemplateName": name,+ "SubjectPart": _p(params, "Template.SubjectPart"),+ "TextPart": _p(params, "Template.TextPart"),+ "HtmlPart": _p(params, "Template.HtmlPart"),+ "CreatedTimestamp": _iso_now(),+ }+ return _xml(200, "CreateTemplateResponse", "<CreateTemplateResult/>")+++def _get_template(params):+ name = _p(params, "TemplateName")+ tpl = _templates.get(name)+ if not tpl:+ return _error("TemplateDoesNotExist",+ f"Template {name} does not exist", 400)+ return _xml(200, "GetTemplateResponse",+ f"<GetTemplateResult><Template>"+ f"<TemplateName>{_esc(tpl['TemplateName'])}</TemplateName>"+ f"<SubjectPart>{_esc(tpl['SubjectPart'])}</SubjectPart>"+ f"<TextPart>{_esc(tpl['TextPart'])}</TextPart>"+ f"<HtmlPart>{_esc(tpl['HtmlPart'])}</HtmlPart>"+ f"</Template></GetTemplateResult>")+++def _delete_template(params):+ name = _p(params, "TemplateName")+ _templates.pop(name, None)+ return _xml(200, "DeleteTemplateResponse", "<DeleteTemplateResult/>")+++def _list_templates(params):+ members = "".join(+ f"<member><Name>{_esc(t['TemplateName'])}</Name>"+ f"<CreatedTimestamp>{t['CreatedTimestamp']}</CreatedTimestamp></member>"+ for t in _templates.values()+ )+ return _xml(200, "ListTemplatesResponse",+ f"<ListTemplatesResult>"+ f"<TemplatesMetadata>{members}</TemplatesMetadata>"+ f"</ListTemplatesResult>")+++def _update_template(params):+ name = _p(params, "Template.TemplateName")+ if name not in _templates:+ return _error("TemplateDoesNotExist",+ f"Template {name} does not exist", 400)+ tpl = _templates[name]+ for field, param in [("SubjectPart", "Template.SubjectPart"),+ ("TextPart", "Template.TextPart"),+ ("HtmlPart", "Template.HtmlPart")]:+ val = _p(params, param)+ if val:+ tpl[field] = val+ return _xml(200, "UpdateTemplateResponse", "<UpdateTemplateResult/>")+++# ---------------------------------------------------------------------------+# v2 — REST / JSON dispatcher+# ---------------------------------------------------------------------------++def _handle_v2(method, path, headers, body):+ try:+ raw = body.decode("utf-8", errors="replace") if isinstance(body, bytes) else (body or "")+ data = json.loads(raw) if raw else {}+ except (json.JSONDecodeError, UnicodeDecodeError):+ data = {}++ route = path.rstrip("/")+ if route.startswith("/v2/email"):+ route = route[len("/v2/email"):]++ if method == "POST" and route == "/outbound-emails":+ return _v2_send_email(data)+ if method == "POST" and route == "/outbound-bulk-emails":+ return _v2_send_bulk_email(data)+ if method == "POST" and route == "/identities":+ return _v2_create_identity(data)+ if method == "GET" and route == "/identities":+ return _v2_list_identities()+ if method == "POST" and route == "/configuration-sets":+ return _v2_create_configuration_set(data)+ if method == "GET" and route == "/configuration-sets":+ return _v2_list_configuration_sets()+ if method == "POST" and route == "/templates":+ return _v2_create_template(data)+ if method == "GET" and route == "/templates":+ return _v2_list_templates()+ if method == "GET" and route == "/account":+ return _v2_get_account()++ parts = route.split("/")++ if len(parts) == 3 and parts[1] == "identities":+ identity = unquote(parts[2])+ if method == "GET":+ return _v2_get_identity(identity)+ if method == "DELETE":+ return _v2_delete_identity(identity)++ if len(parts) == 3 and parts[1] == "configuration-sets":+ name = unquote(parts[2])+ if method == "GET":+ return _v2_get_configuration_set(name)+ if method == "DELETE":+ return _v2_delete_configuration_set(name)++ if len(parts) == 3 and parts[1] == "templates":+ name = unquote(parts[2])+ if method == "GET":+ return _v2_get_template(name)+ if method == "PUT":+ return _v2_update_template(name, data)+ if method == "DELETE":+ return _v2_delete_template(name)++ return _json_error("NotFoundException", f"Route not found: {method} {path}", 404)+++# ---------------------------------------------------------------------------+# v2 — Send+# ---------------------------------------------------------------------------++def _v2_send_email(data):+ from_addr = data.get("FromEmailAddress", "")+ dest = data.get("Destination", {})+ to_addrs = dest.get("ToAddresses", [])+ cc_addrs = dest.get("CcAddresses", [])+ bcc_addrs = dest.get("BccAddresses", [])+ content = data.get("Content", {})+ config_set = data.get("ConfigurationSetName", "")++ subject = ""+ body_text = ""+ body_html = ""+ template_name = ""+ template_data = ""++ simple = content.get("Simple", {})+ if simple:+ subject = simple.get("Subject", {}).get("Data", "")+ body_obj = simple.get("Body", {})+ body_text = body_obj.get("Text", {}).get("Data", "")+ body_html = body_obj.get("Html", {}).get("Data", "")++ tpl = content.get("Template", {})+ if tpl:+ template_name = tpl.get("TemplateName", "")+ template_data = tpl.get("TemplateData", "")++ raw = content.get("Raw", {})+ parsed = {}+ if raw:+ parsed = _parse_raw_mime(raw.get("Data", ""))+ msg_id = f"{new_uuid()}@email.amazonses.com"+ record = {+ "MessageId": msg_id,+ "Source": from_addr,+ "To": to_addrs,+ "CC": cc_addrs,+ "BCC": bcc_addrs,+ "Subject": subject,+ "BodyText": body_text,+ "BodyHtml": body_html,+ "Timestamp": time.time(),+ "Type": "v2.SendEmail",+ }+ if template_name:+ record["Template"] = template_name+ record["TemplateData"] = template_data+ if parsed:+ record["Parsed"] = parsed+ if config_set:+ record["ConfigurationSetName"] = config_set+ _sent_emails.append(record)+ logger.info(f"SES v2 SendEmail: {from_addr} -> {to_addrs}")+ return _json_response(200, {"MessageId": msg_id})+++def _v2_send_bulk_email(data):+ from_addr = data.get("FromEmailAddress", "")+ default_content = data.get("DefaultContent", {})+ tpl = default_content.get("Template", {})+ template_name = tpl.get("TemplateName", "")+ default_data = tpl.get("TemplateData", "")+ entries = data.get("BulkEmailEntries", [])+ config_set = data.get("ConfigurationSetName", "")++ results = []+ for entry in entries:+ dest = entry.get("Destination", {})+ to_addrs = dest.get("ToAddresses", [])+ replacement = (+ entry.get("ReplacementEmailContent", {})+ .get("ReplacementTemplate", {})+ .get("ReplacementTemplateData", default_data)+ )+ msg_id = f"{new_uuid()}@email.amazonses.com"+ record = {+ "MessageId": msg_id,+ "Source": from_addr,+ "To": to_addrs,+ "Template": template_name,+ "TemplateData": replacement,+ "Timestamp": time.time(),+ "Type": "v2.SendBulkEmail",+ }+ if config_set:+ record["ConfigurationSetName"] = config_set+ _sent_emails.append(record)+ results.append({"Status": "SUCCESS", "MessageId": msg_id})++ logger.info(f"SES v2 SendBulkEmail: {from_addr} | template={template_name} | "+ f"{len(entries)} entries")+ return _json_response(200, {"BulkEmailEntryResults": results})+++# ---------------------------------------------------------------------------+# v2 — Identity+# ---------------------------------------------------------------------------++def _v2_create_identity(data):+ identity = data.get("EmailIdentity", "")+ id_type = "Domain" if ("." in identity and "@" not in identity) else "EmailAddress"+ _identities[identity] = _make_identity(identity, id_type)+ return _json_response(200, {+ "IdentityType": "DOMAIN" if id_type == "Domain" else "EMAIL_ADDRESS",+ "VerifiedForSendingStatus": True,+ })+++def _v2_list_identities():+ items = []+ for identity, info in _identities.items():+ items.append({+ "IdentityType": "DOMAIN" if info["Type"] == "Domain" else "EMAIL_ADDRESS",+ "IdentityName": identity,+ "SendingEnabled": info["VerificationStatus"] == "Success",+ })+ return _json_response(200, {"EmailIdentities": items})+++def _v2_get_identity(identity):+ info = _identities.get(identity)+ if not info:+ return _json_error("NotFoundException",+ f"Identity {identity} not found", 404)+ return _json_response(200, {+ "IdentityType": "DOMAIN" if info["Type"] == "Domain" else "EMAIL_ADDRESS",+ "VerifiedForSendingStatus": info["VerificationStatus"] == "Success",+ "FeedbackForwardingStatus": info.get("FeedbackForwardingEnabled", True),+ "DkimAttributes": {+ "SigningEnabled": info.get("DkimEnabled", False),+ "Status": info.get("DkimVerificationStatus", "NOT_STARTED"),+ "Tokens": info.get("DkimTokens", []),+ },+ })-def _list_verified_emails(params):- members = "".join(f"<member>{e}</member>" for e in _identities if _identities[e]["Type"] == "EmailAddress")- return _xml(200, "ListVerifiedEmailAddressesResponse",- f"<ListVerifiedEmailAddressesResult><VerifiedEmailAddresses>{members}</VerifiedEmailAddresses></ListVerifiedEmailAddressesResult>")+def _v2_delete_identity(identity):+ _identities.pop(identity, None)+ return _json_response(200, {})+++# ---------------------------------------------------------------------------+# v2 — Configuration sets+# ---------------------------------------------------------------------------++def _v2_create_configuration_set(data):+ name = data.get("ConfigurationSetName", "")+ if not name:+ return _json_error("BadRequestException",+ "ConfigurationSetName is required", 400)+ if name in _configuration_sets:+ return _json_error("AlreadyExistsException",+ f"Configuration set {name} already exists", 409)+ _configuration_sets[name] = {"Name": name, "CreatedTimestamp": _iso_now()}+ return _json_response(200, {})+++def _v2_list_configuration_sets():+ items = [{"Name": cs["Name"]} for cs in _configuration_sets.values()]+ return _json_response(200, {"ConfigurationSets": items})+++def _v2_get_configuration_set(name):+ cs = _configuration_sets.get(name)+ if not cs:+ return _json_error("NotFoundException",+ f"Configuration set {name} not found", 404)+ return _json_response(200, {"ConfigurationSetName": cs["Name"]})+++def _v2_delete_configuration_set(name):+ if name not in _configuration_sets:+ return _json_error("NotFoundException",+ f"Configuration set {name} not found", 404)+ del _configuration_sets[name]+ return _json_response(200, {})+++# ---------------------------------------------------------------------------+# v2 — Templates+# ---------------------------------------------------------------------------++def _v2_create_template(data):+ name = data.get("TemplateName", "")+ content = data.get("TemplateContent", {})+ if not name:+ return _json_error("BadRequestException",+ "TemplateName is required", 400)+ if name in _templates:+ return _json_error("AlreadyExistsException",+ f"Template {name} already exists", 409)+ _templates[name] = {+ "TemplateName": name,+ "SubjectPart": content.get("Subject", ""),+ "TextPart": content.get("Text", ""),+ "HtmlPart": content.get("Html", ""),+ "CreatedTimestamp": _iso_now(),+ }+ return _json_response(200, {})+++def _v2_list_templates():+ items = [+ {"TemplateName": t["TemplateName"],+ "CreatedTimestamp": t["CreatedTimestamp"]}+ for t in _templates.values()+ ]+ return _json_response(200, {"TemplatesMetadata": items})+++def _v2_get_template(name):+ tpl = _templates.get(name)+ if not tpl:+ return _json_error("NotFoundException",+ f"Template {name} not found", 404)+ return _json_response(200, {+ "TemplateName": tpl["TemplateName"],+ "TemplateContent": {+ "Subject": tpl["SubjectPart"],+ "Text": tpl["TextPart"],+ "Html": tpl["HtmlPart"],+ },+ })+++def _v2_update_template(name, data):+ if name not in _templates:+ return _json_error("NotFoundException",+ f"Template {name} not found", 404)+ content = data.get("TemplateContent", {})+ tpl = _templates[name]+ if "Subject" in content:+ tpl["SubjectPart"] = content["Subject"]+ if "Text" in content:+ tpl["TextPart"] = content["Text"]+ if "Html" in content:+ tpl["HtmlPart"] = content["Html"]+ return _json_response(200, {})+++def _v2_delete_template(name):+ _templates.pop(name, None)+ return _json_response(200, {})+++# ---------------------------------------------------------------------------+# v2 — Account+# ---------------------------------------------------------------------------++def _v2_get_account():+ cutoff = time.time() - 86400+ sent_24h = sum(1 for e in _sent_emails if e["Timestamp"] >= cutoff)+ return _json_response(200, {+ "SendQuota": {+ "Max24HourSend": 50000.0,+ "MaxSendRate": 14.0,+ "SentLast24Hours": float(sent_24h),+ },+ "SendingEnabled": True,+ })+++# ---------------------------------------------------------------------------+# Shared helpers+# ---------------------------------------------------------------------------++def _make_identity(identity, identity_type):+ return {+ "VerificationStatus": "Success",+ "Type": identity_type,+ "DkimEnabled": False,+ "DkimTokens": [],+ "DkimVerificationStatus": "NotStarted",+ "NotificationTopics": {"Bounce": "", "Complaint": "", "Delivery": ""},+ "FeedbackForwardingEnabled": True,+ }+++def _aggregate_15min_buckets():+ """Aggregate sent emails into 15-minute (900 s) buckets per the AWS spec."""+ if not _sent_emails:+ return []+ buckets: dict = {}+ for email in _sent_emails:+ ts = email["Timestamp"]+ bucket_ts = ts - (ts % 900)+ if bucket_ts not in buckets:+ buckets[bucket_ts] = {+ "Timestamp": bucket_ts,+ "DeliveryAttempts": 0,+ "Bounces": 0,+ "Complaints": 0,+ "Rejects": 0,+ }+ buckets[bucket_ts]["DeliveryAttempts"] += 1+ return sorted(buckets.values(), key=lambda b: b["Timestamp"])+++def _render_template(template, template_data_json):+ """Replace {{var}} placeholders with values from template data."""+ try:+ data = (json.loads(template_data_json)+ if isinstance(template_data_json, str)+ else (template_data_json or {}))+ except (json.JSONDecodeError, TypeError):+ data = {}++ result = {}+ for out_key, field in [("Subject", "SubjectPart"),+ ("Text", "TextPart"),+ ("Html", "HtmlPart")]:+ text = template.get(field, "")+ for key, val in data.items():+ text = text.replace("{{" + key + "}}", str(val))+ result[out_key] = text+ return result+++def _parse_raw_mime(raw_b64):+ """Best-effort MIME parse of a base64 or raw message."""+ parsed: dict = {}+ try:+ raw_bytes = raw_b64.encode("utf-8") if isinstance(raw_b64, str) else raw_b64+ try:+ decoded = base64.b64decode(raw_bytes)+ except Exception:+ decoded = raw_bytes++ mime_msg = message_from_bytes(decoded, policy=default_policy)+ parsed["From"] = mime_msg.get("From", "")+ parsed["To"] = mime_msg.get("To", "")+ parsed["Subject"] = mime_msg.get("Subject", "")+ parsed["ContentType"] = mime_msg.get_content_type()++ body_parts = []+ if mime_msg.is_multipart():+ for part in mime_msg.walk():+ ct = part.get_content_type()+ if ct in ("text/plain", "text/html"):+ try:+ payload = part.get_content()+ except Exception:+ payload = ""+ body_parts.append({"ContentType": ct, "Data": payload})+ else:+ try:+ payload = mime_msg.get_content()+ except Exception:+ payload = ""+ body_parts.append({+ "ContentType": mime_msg.get_content_type(),+ "Data": payload,+ })+ parsed["BodyParts"] = body_parts+ except Exception as exc:+ parsed["ParseError"] = str(exc)+ return parsed-# --- Helpers ---def _collect_list(params, prefix):result = []@@ -166,19 +964,45 @@ def _p(params, key, default=""):return val[0] if isinstance(val, list) else val+def _esc(text):+ if not text:+ return ""+ return (text.replace("&", "&").replace("<", "<")+ .replace(">", ">").replace('"', """))+++def _iso_now():+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")++def _xml(status, root_tag, inner):- body = f"""<?xml version="1.0" encoding="UTF-8"?>-<{root_tag} xmlns="http://ses.amazonaws.com/doc/2010-12-01/">- {inner}- <ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>-</{root_tag}>""".encode("utf-8")+ body = (f'<?xml version="1.0" encoding="UTF-8"?>'+ f'<{root_tag} xmlns="http://ses.amazonaws.com/doc/2010-12-01/">'+ f'{inner}'+ f'<ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>'+ f'</{root_tag}>').encode("utf-8")return status, {"Content-Type": "application/xml"}, bodydef _error(code, message, status):- body = f"""<?xml version="1.0" encoding="UTF-8"?>-<ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">- <Error><Code>{code}</Code><Message>{message}</Message></Error>- <RequestId>{new_uuid()}</RequestId>-</ErrorResponse>""".encode("utf-8")+ body = (f'<?xml version="1.0" encoding="UTF-8"?>'+ f'<ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">'+ f'<Error><Code>{code}</Code><Message>{_esc(message)}</Message></Error>'+ f'<RequestId>{new_uuid()}</RequestId>'+ f'</ErrorResponse>').encode("utf-8")return status, {"Content-Type": "application/xml"}, body+++def _json_response(status, data):+ return status, {"Content-Type": "application/json"}, json.dumps(data).encode("utf-8")+++def _json_error(code, message, status):+ return _json_response(status, {"__type": code, "message": message})+++def reset():+ _identities.clear()+ _sent_emails.clear()+ _templates.clear()+ _configuration_sets.clear()diff --git a/services/sns.py b/services/sns.pyindex 3e15db63..334b1207 100644--- a/services/sns.py+++ b/services/sns.py@@ -1,23 +1,35 @@"""-SNS Service Emulator.+SNS Service Emulator — AWS-compatible.Supports: CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes,- Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, Publish.+ Subscribe, Unsubscribe, ConfirmSubscription,+ ListSubscriptions, ListSubscriptionsByTopic,+ GetSubscriptionAttributes, SetSubscriptionAttributes,+ Publish, PublishBatch,+ ListTagsForResource, TagResource, UntagResource,+ CreatePlatformApplication, CreatePlatformEndpoint.+SNS → Lambda fanout dispatches via _execute_function (synchronous)."""-import time+import asyncioimport hashlib+import jsonimport logging+import timefrom urllib.parse import parse_qsfrom core.responses import new_uuid+from services import sqs as _sqs+import services.lambda_svc as _lambda_svclogger = logging.getLogger("sns")ACCOUNT_ID = "000000000000"REGION = "us-east-1"-_topics: dict = {} # arn -> {name, attributes, subscriptions: [{arn, protocol, endpoint, confirmed}]}+_topics: dict = {}_sub_arn_to_topic: dict = {}+_platform_applications: dict = {}+_platform_endpoints: dict = {}async def handle_request(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:@@ -35,10 +47,19 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, que"GetTopicAttributes": _get_topic_attributes,"SetTopicAttributes": _set_topic_attributes,"Subscribe": _subscribe,+ "ConfirmSubscription": _confirm_subscription,"Unsubscribe": _unsubscribe,"ListSubscriptions": _list_subscriptions,"ListSubscriptionsByTopic": _list_subscriptions_by_topic,+ "GetSubscriptionAttributes": _get_subscription_attributes,+ "SetSubscriptionAttributes": _set_subscription_attributes,"Publish": _publish,+ "PublishBatch": _publish_batch,+ "ListTagsForResource": _list_tags_for_resource,+ "TagResource": _tag_resource,+ "UntagResource": _untag_resource,+ "CreatePlatformApplication": _create_platform_application,+ "CreatePlatformEndpoint": _create_platform_endpoint,}handler = handlers.get(action)@@ -47,58 +68,113 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, quereturn handler(params)+# ---------------------------------------------------------------------------+# Topic management+# ---------------------------------------------------------------------------+def _create_topic(params):name = _p(params, "Name")if not name:return _error("InvalidParameter", "Name is required", 400)+arn = f"arn:aws:sns:{REGION}:{ACCOUNT_ID}:{name}"if arn not in _topics:+ default_policy = json.dumps({+ "Version": "2008-10-17",+ "Id": "__default_policy_ID",+ "Statement": [{+ "Sid": "__default_statement_ID",+ "Effect": "Allow",+ "Principal": {"AWS": "*"},+ "Action": ["SNS:Publish", "SNS:Subscribe", "SNS:Receive"],+ "Resource": arn,+ "Condition": {"StringEquals": {"AWS:SourceOwner": ACCOUNT_ID}},+ }],+ })_topics[arn] = {- "name": name, "arn": arn,+ "name": name,+ "arn": arn,"attributes": {"TopicArn": arn,"DisplayName": name,+ "Owner": ACCOUNT_ID,+ "Policy": default_policy,"SubscriptionsConfirmed": "0","SubscriptionsPending": "0","SubscriptionsDeleted": "0",+ "EffectiveDeliveryPolicy": json.dumps({+ "http": {+ "defaultHealthyRetryPolicy": {+ "minDelayTarget": 20,+ "maxDelayTarget": 20,+ "numRetries": 3,+ }+ }+ }),},"subscriptions": [],"messages": [],+ "tags": {},}- return _xml(200, "CreateTopicResponse", f"<CreateTopicResult><TopicArn>{arn}</TopicArn></CreateTopicResult>")++ i = 1+ while _p(params, f"Attributes.entry.{i}.key"):+ key = _p(params, f"Attributes.entry.{i}.key")+ val = _p(params, f"Attributes.entry.{i}.value")+ _topics[arn]["attributes"][key] = val+ i += 1++ return _xml(200, "CreateTopicResponse",+ f"<CreateTopicResult><TopicArn>{arn}</TopicArn></CreateTopicResult>")def _delete_topic(params):arn = _p(params, "TopicArn")- _topics.pop(arn, None)+ topic = _topics.pop(arn, None)+ if topic:+ for sub in topic.get("subscriptions", []):+ _sub_arn_to_topic.pop(sub["arn"], None)return _xml(200, "DeleteTopicResponse", "")def _list_topics(params):- members = "".join(f"<member><TopicArn>{arn}</TopicArn></member>" for arn in _topics)- return _xml(200, "ListTopicsResponse", f"<ListTopicsResult><Topics>{members}</Topics></ListTopicsResult>")+ members = "".join(+ f"<member><TopicArn>{arn}</TopicArn></member>" for arn in _topics+ )+ return _xml(200, "ListTopicsResponse",+ f"<ListTopicsResult><Topics>{members}</Topics></ListTopicsResult>")def _get_topic_attributes(params):arn = _p(params, "TopicArn")topic = _topics.get(arn)if not topic:- return _error("NotFound", "Topic not found", 404)- attrs = "".join(f"<entry><key>{k}</key><value>{v}</value></entry>" for k, v in topic["attributes"].items())- return _xml(200, "GetTopicAttributesResponse", f"<GetTopicAttributesResult><Attributes>{attrs}</Attributes></GetTopicAttributesResult>")+ return _error("NotFound", f"Topic does not exist: {arn}", 404)+ _refresh_subscription_counts(topic)+ attrs = "".join(+ f"<entry><key>{k}</key><value>{_xml_escape(v)}</value></entry>"+ for k, v in topic["attributes"].items()+ )+ return _xml(200, "GetTopicAttributesResponse",+ f"<GetTopicAttributesResult><Attributes>{attrs}</Attributes></GetTopicAttributesResult>")def _set_topic_attributes(params):arn = _p(params, "TopicArn")topic = _topics.get(arn)if not topic:- return _error("NotFound", "Topic not found", 404)+ return _error("NotFound", f"Topic does not exist: {arn}", 404)attr_name = _p(params, "AttributeName")attr_val = _p(params, "AttributeValue")- topic["attributes"][attr_name] = attr_val+ if attr_name:+ topic["attributes"][attr_name] = attr_valreturn _xml(200, "SetTopicAttributesResponse", "")+# ---------------------------------------------------------------------------+# Subscriptions+# ---------------------------------------------------------------------------+def _subscribe(params):topic_arn = _p(params, "TopicArn")protocol = _p(params, "Protocol")@@ -106,22 +182,82 @@ def _subscribe(params):topic = _topics.get(topic_arn)if not topic:- return _error("NotFound", "Topic not found", 404)+ return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)++ if not protocol:+ return _error("InvalidParameter", "Protocol is required", 400)++ for existing in topic["subscriptions"]:+ if existing["protocol"] == protocol and existing["endpoint"] == endpoint:+ return _xml(200, "SubscribeResponse",+ f"<SubscribeResult><SubscriptionArn>{existing['arn']}</SubscriptionArn></SubscribeResult>")sub_arn = f"{topic_arn}:{new_uuid()}"- sub = {"arn": sub_arn, "protocol": protocol, "endpoint": endpoint, "confirmed": True, "topic_arn": topic_arn}+ needs_confirmation = protocol in ("http", "https")++ sub = {+ "arn": sub_arn,+ "protocol": protocol,+ "endpoint": endpoint,+ "confirmed": not needs_confirmation,+ "topic_arn": topic_arn,+ "owner": ACCOUNT_ID,+ "token": new_uuid() if needs_confirmation else None,+ "attributes": {+ "SubscriptionArn": sub_arn,+ "TopicArn": topic_arn,+ "Protocol": protocol,+ "Endpoint": endpoint,+ "Owner": ACCOUNT_ID,+ "ConfirmationWasAuthenticated": "true" if not needs_confirmation else "false",+ "PendingConfirmation": "true" if needs_confirmation else "false",+ "RawMessageDelivery": "false",+ },+ }+topic["subscriptions"].append(sub)_sub_arn_to_topic[sub_arn] = topic_arn- topic["attributes"]["SubscriptionsConfirmed"] = str(len([s for s in topic["subscriptions"] if s["confirmed"]]))+ _refresh_subscription_counts(topic)++ if needs_confirmation:+ asyncio.ensure_future(_send_subscription_confirmation(topic_arn, sub))- return _xml(200, "SubscribeResponse", f"<SubscribeResult><SubscriptionArn>{sub_arn}</SubscriptionArn></SubscribeResult>")+ result_arn = "PendingConfirmation" if needs_confirmation else sub_arn+ return _xml(200, "SubscribeResponse",+ f"<SubscribeResult><SubscriptionArn>{result_arn}</SubscriptionArn></SubscribeResult>")+++def _confirm_subscription(params):+ topic_arn = _p(params, "TopicArn")+ token = _p(params, "Token")++ topic = _topics.get(topic_arn)+ if not topic:+ return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)++ if not token:+ return _error("InvalidParameter", "Token is required", 400)++ for sub in topic["subscriptions"]:+ if sub.get("token") == token:+ sub["confirmed"] = True+ sub["token"] = None+ sub["attributes"]["PendingConfirmation"] = "false"+ sub["attributes"]["ConfirmationWasAuthenticated"] = "true"+ _refresh_subscription_counts(topic)+ return _xml(200, "ConfirmSubscriptionResponse",+ f"<ConfirmSubscriptionResult><SubscriptionArn>{sub['arn']}</SubscriptionArn></ConfirmSubscriptionResult>")++ return _error("InvalidParameter", "Invalid token", 400)def _unsubscribe(params):sub_arn = _p(params, "SubscriptionArn")topic_arn = _sub_arn_to_topic.get(sub_arn)if topic_arn and topic_arn in _topics:- _topics[topic_arn]["subscriptions"] = [s for s in _topics[topic_arn]["subscriptions"] if s["arn"] != sub_arn]+ topic = _topics[topic_arn]+ topic["subscriptions"] = [s for s in topic["subscriptions"] if s["arn"] != sub_arn]+ _refresh_subscription_counts(topic)_sub_arn_to_topic.pop(sub_arn, None)return _xml(200, "UnsubscribeResponse", "")@@ -130,99 +266,441 @@ def _list_subscriptions(params):members = ""for topic in _topics.values():for sub in topic["subscriptions"]:- members += f"""<member>- <SubscriptionArn>{sub['arn']}</SubscriptionArn>- <TopicArn>{sub['topic_arn']}</TopicArn>- <Protocol>{sub['protocol']}</Protocol>- <Endpoint>{sub['endpoint']}</Endpoint>- </member>"""- return _xml(200, "ListSubscriptionsResponse", f"<ListSubscriptionsResult><Subscriptions>{members}</Subscriptions></ListSubscriptionsResult>")+ members += (+ "<member>"+ f"<SubscriptionArn>{sub['arn']}</SubscriptionArn>"+ f"<Owner>{sub.get('owner', ACCOUNT_ID)}</Owner>"+ f"<TopicArn>{sub['topic_arn']}</TopicArn>"+ f"<Protocol>{sub['protocol']}</Protocol>"+ f"<Endpoint>{sub['endpoint']}</Endpoint>"+ "</member>"+ )+ return _xml(200, "ListSubscriptionsResponse",+ f"<ListSubscriptionsResult><Subscriptions>{members}</Subscriptions></ListSubscriptionsResult>")def _list_subscriptions_by_topic(params):topic_arn = _p(params, "TopicArn")topic = _topics.get(topic_arn)if not topic:- return _error("NotFound", "Topic not found", 404)+ return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)members = ""for sub in topic["subscriptions"]:- members += f"""<member>- <SubscriptionArn>{sub['arn']}</SubscriptionArn>- <TopicArn>{topic_arn}</TopicArn>- <Protocol>{sub['protocol']}</Protocol>- <Endpoint>{sub['endpoint']}</Endpoint>- </member>"""- return _xml(200, "ListSubscriptionsByTopicResponse", f"<ListSubscriptionsByTopicResult><Subscriptions>{members}</Subscriptions></ListSubscriptionsByTopicResult>")+ members += (+ "<member>"+ f"<SubscriptionArn>{sub['arn']}</SubscriptionArn>"+ f"<Owner>{sub.get('owner', ACCOUNT_ID)}</Owner>"+ f"<TopicArn>{topic_arn}</TopicArn>"+ f"<Protocol>{sub['protocol']}</Protocol>"+ f"<Endpoint>{sub['endpoint']}</Endpoint>"+ "</member>"+ )+ return _xml(200, "ListSubscriptionsByTopicResponse",+ f"<ListSubscriptionsByTopicResult><Subscriptions>{members}</Subscriptions></ListSubscriptionsByTopicResult>")+++def _get_subscription_attributes(params):+ sub_arn = _p(params, "SubscriptionArn")+ topic_arn = _sub_arn_to_topic.get(sub_arn)+ if not topic_arn or topic_arn not in _topics:+ return _error("NotFound", f"Subscription does not exist: {sub_arn}", 404)++ sub = _find_subscription(topic_arn, sub_arn)+ if not sub:+ return _error("NotFound", f"Subscription does not exist: {sub_arn}", 404)++ attrs = "".join(+ f"<entry><key>{k}</key><value>{_xml_escape(v)}</value></entry>"+ for k, v in sub["attributes"].items()+ )+ return _xml(200, "GetSubscriptionAttributesResponse",+ f"<GetSubscriptionAttributesResult><Attributes>{attrs}</Attributes></GetSubscriptionAttributesResult>")+def _set_subscription_attributes(params):+ sub_arn = _p(params, "SubscriptionArn")+ topic_arn = _sub_arn_to_topic.get(sub_arn)+ if not topic_arn or topic_arn not in _topics:+ return _error("NotFound", f"Subscription does not exist: {sub_arn}", 404)++ sub = _find_subscription(topic_arn, sub_arn)+ if not sub:+ return _error("NotFound", f"Subscription does not exist: {sub_arn}", 404)++ attr_name = _p(params, "AttributeName")+ attr_val = _p(params, "AttributeValue")++ allowed = {"DeliveryPolicy", "FilterPolicy", "FilterPolicyScope",+ "RawMessageDelivery", "RedrivePolicy"}+ if attr_name not in allowed:+ return _error("InvalidParameter",+ f"Invalid attribute name: {attr_name}", 400)++ if attr_name == "FilterPolicy" and attr_val:+ try:+ json.loads(attr_val)+ except json.JSONDecodeError:+ return _error("InvalidParameter", "Invalid JSON in FilterPolicy", 400)++ sub["attributes"][attr_name] = attr_val+ return _xml(200, "SetSubscriptionAttributesResponse", "")+++# ---------------------------------------------------------------------------+# Publish+# ---------------------------------------------------------------------------+def _publish(params):topic_arn = _p(params, "TopicArn") or _p(params, "TargetArn")+ phone_number = _p(params, "PhoneNumber")message = _p(params, "Message")subject = _p(params, "Subject")+ message_structure = _p(params, "MessageStructure")++ if phone_number and not topic_arn:+ msg_id = new_uuid()+ logger.info(f"SNS SMS stub to {phone_number}: {message[:80]}")+ return _xml(200, "PublishResponse",+ f"<PublishResult><MessageId>{msg_id}</MessageId></PublishResult>")++ if not topic_arn:+ return _error("InvalidParameter",+ "TopicArn, TargetArn, or PhoneNumber is required", 400)+ if topic_arn not in _topics:+ return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)++ msg_attrs = _parse_message_attributes(params)msg_id = new_uuid()- if topic_arn and topic_arn in _topics:+ _topics[topic_arn]["messages"].append({+ "id": msg_id,+ "message": message,+ "subject": subject,+ "message_structure": message_structure,+ "message_attributes": msg_attrs,+ "timestamp": time.time(),+ })++ _fanout(topic_arn, msg_id, message, subject, message_structure, msg_attrs)+ logger.info(f"SNS publish to {topic_arn}: {message[:100]}")++ return _xml(200, "PublishResponse",+ f"<PublishResult><MessageId>{msg_id}</MessageId></PublishResult>")+++def _publish_batch(params):+ topic_arn = _p(params, "TopicArn")+ if not topic_arn:+ return _error("InvalidParameter", "TopicArn is required", 400)+ if topic_arn not in _topics:+ return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)++ entries = _parse_batch_entries(params)+ if not entries:+ return _error("InvalidParameter",+ "PublishBatchRequestEntries is required", 400)+ if len(entries) > 10:+ return _error("TooManyEntriesInBatchRequest",+ "The batch request contains more entries than permissible", 400)++ ids_seen = set()+ for entry in entries:+ eid = entry.get("id", "")+ if eid in ids_seen:+ return _error("BatchEntryIdsNotDistinct",+ "Batch entry ids must be distinct", 400)+ ids_seen.add(eid)++ successful = ""+ failed = ""+ for entry in entries:+ eid = entry["id"]+ message = entry.get("message", "")+ subject = entry.get("subject", "")+ message_structure = entry.get("message_structure", "")+ msg_attrs = entry.get("message_attributes", {})++ msg_id = new_uuid()_topics[topic_arn]["messages"].append({- "id": msg_id, "message": message, "subject": subject,+ "id": msg_id,+ "message": message,+ "subject": subject,+ "message_structure": message_structure,+ "message_attributes": msg_attrs,"timestamp": time.time(),})- _fanout(topic_arn, msg_id, message, subject)- logger.info(f"SNS publish to {topic_arn}: {message[:100]}")+ _fanout(topic_arn, msg_id, message, subject, message_structure, msg_attrs)++ successful += (+ "<member>"+ f"<Id>{_xml_escape(eid)}</Id>"+ f"<MessageId>{msg_id}</MessageId>"+ "</member>"+ )- return _xml(200, "PublishResponse", f"<PublishResult><MessageId>{msg_id}</MessageId></PublishResult>")+ return _xml(200, "PublishBatchResponse",+ f"<PublishBatchResult>"+ f"<Successful>{successful}</Successful>"+ f"<Failed>{failed}</Failed>"+ f"</PublishBatchResult>")-def _fanout(topic_arn: str, msg_id: str, message: str, subject: str):- """Deliver SNS message to all confirmed subscribers."""- import json as _json- from services import sqs as _sqs+# ---------------------------------------------------------------------------+# Fanout+# ---------------------------------------------------------------------------+def _fanout(topic_arn: str, msg_id: str, message: str, subject: str,+ message_structure: str = "", message_attributes: dict | None = None):topic = _topics.get(topic_arn)if not topic:return- # SNS wraps the message in an envelope when delivering to SQS- envelope = _json.dumps({- "Type": "Notification",- "MessageId": msg_id,- "TopicArn": topic_arn,- "Subject": subject or "",- "Message": message,- "Timestamp": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()),- "SignatureVersion": "1",- "Signature": "FAKE",- "SigningCertURL": "",- "UnsubscribeURL": "",- })-for sub in topic["subscriptions"]:if not sub.get("confirmed"):continue+protocol = sub.get("protocol", "")endpoint = sub.get("endpoint", "")+ if not _matches_filter_policy(sub, message_attributes or {}):+ continue++ effective_message = _resolve_message_for_protocol(+ message, message_structure, protocol+ )++ raw = sub.get("attributes", {}).get("RawMessageDelivery", "false") == "true"+ envelope = _build_envelope(+ topic_arn, msg_id, effective_message, subject,+ message_attributes or {}, raw+ )+if protocol == "sqs":- # endpoint is the SQS queue ARN: arn:aws:sqs:region:account:queue-name- queue_name = endpoint.split(":")[-1]- queue_url = _sqs._queue_url(queue_name)- queue = _sqs._queues.get(queue_url)- if queue:- import hashlib as _hashlib- queue["messages"].append({- "id": new_uuid(),- "body": envelope,- "md5": _hashlib.md5(envelope.encode()).hexdigest(),- "receipt_handle": None,- "sent_at": time.time(),- "visible_at": time.time(),- "receive_count": 0,- "attributes": {},- })- logger.info(f"SNS fanout → SQS {queue_name}")- else:- logger.warning(f"SNS fanout: SQS queue {queue_name} not found")+ _deliver_to_sqs(endpoint, envelope, raw, effective_message)+ elif protocol in ("http", "https"):+ asyncio.ensure_future(+ _deliver_to_http(endpoint, envelope)+ )+ elif protocol == "lambda":+ _deliver_to_lambda(endpoint, envelope, topic_arn, msg_id, effective_message, message_attributes or {})+ elif protocol == "email" or protocol == "email-json":+ logger.info(f"SNS fanout → email {endpoint} (stub)")+ elif protocol == "sms":+ logger.info(f"SNS fanout → SMS {endpoint} (stub)")+ elif protocol == "application":+ logger.info(f"SNS fanout → application {endpoint} (stub)")+++def _deliver_to_sqs(endpoint: str, envelope: str, raw: bool, raw_message: str):+ queue_name = endpoint.split(":")[-1]+ queue_url = _sqs._queue_url(queue_name)+ queue = _sqs._queues.get(queue_url)+ if not queue:+ logger.warning(f"SNS fanout: SQS queue {queue_name} not found")+ return++ body = raw_message if raw else envelope+ now = time.time()+ msg = {+ "id": new_uuid(),+ "body": body,+ "md5": hashlib.md5(body.encode()).hexdigest(),+ "receipt_handle": None,+ "sent_at": now,+ "visible_at": now,+ "receive_count": 0,+ }+ _sqs._ensure_msg_fields(msg)+ queue["messages"].append(msg)+ logger.info(f"SNS fanout → SQS {queue_name}")+++def _deliver_to_lambda(endpoint: str, envelope: str, topic_arn: str, msg_id: str,+ raw_message: str, message_attributes: dict):+ """Invoke a Lambda function with the SNS Records envelope (AWS format)."""+ # endpoint is a Lambda ARN: arn:aws:lambda:region:account:function:name+ func_name = endpoint.split(":")[-1]+ func = _lambda_svc._functions.get(func_name)+ if not func:+ logger.warning(f"SNS fanout: Lambda function {func_name} not found")+ return+ event = {+ "Records": [+ {+ "EventVersion": "1.0",+ "EventSubscriptionArn": f"{topic_arn}:subscription",+ "EventSource": "aws:sns",+ "Sns": json.loads(envelope),+ }+ ]+ }+ try:+ _lambda_svc._execute_function(func, event)+ logger.info(f"SNS fanout → Lambda {func_name}")+ except Exception as exc:+ logger.error(f"SNS fanout → Lambda {func_name} failed: {exc}")+++async def _deliver_to_http(endpoint: str, payload: str):+ try:+ import aiohttp+ timeout = aiohttp.ClientTimeout(total=5)+ async with aiohttp.ClientSession(timeout=timeout) as session:+ async with session.post(+ endpoint,+ data=payload,+ headers={+ "Content-Type": "text/plain; charset=UTF-8",+ "x-amz-sns-message-type": "Notification",+ },+ ) as resp:+ logger.info(f"SNS HTTP delivery to {endpoint}: {resp.status}")+ except ImportError:+ logger.warning("aiohttp not installed — HTTP delivery skipped")+ except Exception as exc:+ logger.warning(f"SNS HTTP delivery to {endpoint} failed: {exc}")+++async def _send_subscription_confirmation(topic_arn: str, sub: dict):+ endpoint = sub.get("endpoint", "")+ token = sub.get("token", "")+ payload = json.dumps({+ "Type": "SubscriptionConfirmation",+ "MessageId": new_uuid(),+ "TopicArn": topic_arn,+ "Token": token,+ "Message": f"You have chosen to subscribe to the topic {topic_arn}. "+ f"To confirm the subscription, visit the SubscribeURL included in this message.",+ "SubscribeURL": f"http://localhost:4566/?Action=ConfirmSubscription&TopicArn={topic_arn}&Token={token}",+ "Timestamp": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()),+ "SignatureVersion": "1",+ "Signature": "FAKE",+ "SigningCertURL": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-fake.pem",+ })+ try:+ import aiohttp+ timeout = aiohttp.ClientTimeout(total=5)+ async with aiohttp.ClientSession(timeout=timeout) as session:+ async with session.post(+ endpoint,+ data=payload,+ headers={+ "Content-Type": "text/plain; charset=UTF-8",+ "x-amz-sns-message-type": "SubscriptionConfirmation",+ },+ ) as resp:+ logger.info(f"SNS SubscriptionConfirmation sent to {endpoint}: {resp.status}")+ except ImportError:+ logger.info(f"aiohttp not installed — subscription confirmation for {endpoint} skipped")+ except Exception as exc:+ logger.warning(f"SNS SubscriptionConfirmation to {endpoint} failed: {exc}")+++# ---------------------------------------------------------------------------+# Tags+# ---------------------------------------------------------------------------++def _list_tags_for_resource(params):+ arn = _p(params, "ResourceArn")+ topic = _topics.get(arn)+ tags_xml = ""+ if topic:+ for k, v in topic.get("tags", {}).items():+ tags_xml += f"<member><Key>{k}</Key><Value>{v}</Value></member>"+ return _xml(200, "ListTagsForResourceResponse",+ f"<ListTagsForResourceResult><Tags>{tags_xml}</Tags></ListTagsForResourceResult>")+++def _tag_resource(params):+ arn = _p(params, "ResourceArn")+ topic = _topics.get(arn)+ if not topic:+ return _error("ResourceNotFoundException", "Resource not found", 404)+ i = 1+ while _p(params, f"Tags.member.{i}.Key"):+ key = _p(params, f"Tags.member.{i}.Key")+ val = _p(params, f"Tags.member.{i}.Value")+ topic["tags"][key] = val+ i += 1+ return _xml(200, "TagResourceResponse", "<TagResourceResult/>")+++def _untag_resource(params):+ arn = _p(params, "ResourceArn")+ topic = _topics.get(arn)+ if topic:+ i = 1+ while _p(params, f"TagKeys.member.{i}"):+ topic.get("tags", {}).pop(_p(params, f"TagKeys.member.{i}"), None)+ i += 1+ return _xml(200, "UntagResourceResponse", "<UntagResourceResult/>")++# ---------------------------------------------------------------------------+# Platform application stubs+# ---------------------------------------------------------------------------++def _create_platform_application(params):+ name = _p(params, "Name")+ platform = _p(params, "Platform")+ if not name or not platform:+ return _error("InvalidParameter", "Name and Platform are required", 400)++ arn = f"arn:aws:sns:{REGION}:{ACCOUNT_ID}:app/{platform}/{name}"+ attrs = {}+ i = 1+ while _p(params, f"Attributes.entry.{i}.key"):+ key = _p(params, f"Attributes.entry.{i}.key")+ val = _p(params, f"Attributes.entry.{i}.value")+ attrs[key] = val+ i += 1++ _platform_applications[arn] = {+ "arn": arn,+ "name": name,+ "platform": platform,+ "attributes": attrs,+ }+ return _xml(200, "CreatePlatformApplicationResponse",+ f"<CreatePlatformApplicationResult>"+ f"<PlatformApplicationArn>{arn}</PlatformApplicationArn>"+ f"</CreatePlatformApplicationResult>")+++def _create_platform_endpoint(params):+ app_arn = _p(params, "PlatformApplicationArn")+ token = _p(params, "Token")++ if app_arn not in _platform_applications:+ return _error("NotFound", f"PlatformApplication does not exist: {app_arn}", 404)+ if not token:+ return _error("InvalidParameter", "Token is required", 400)++ endpoint_arn = f"{app_arn}/{new_uuid()}"++ attrs = {"Enabled": "true", "Token": token}+ i = 1+ while _p(params, f"Attributes.entry.{i}.key"):+ key = _p(params, f"Attributes.entry.{i}.key")+ val = _p(params, f"Attributes.entry.{i}.value")+ attrs[key] = val+ i += 1++ _platform_endpoints[endpoint_arn] = {+ "arn": endpoint_arn,+ "application_arn": app_arn,+ "attributes": attrs,+ }+ return _xml(200, "CreatePlatformEndpointResponse",+ f"<CreatePlatformEndpointResult>"+ f"<EndpointArn>{endpoint_arn}</EndpointArn>"+ f"</CreatePlatformEndpointResult>")+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------def _p(params, key, default=""):val = params.get(key, [default])@@ -230,18 +708,235 @@ def _p(params, key, default=""):def _xml(status, root_tag, inner):- body = f"""<?xml version="1.0" encoding="UTF-8"?>-<{root_tag} xmlns="http://sns.amazonaws.com/doc/2010-03-31/">- {inner}- <ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>-</{root_tag}>""".encode("utf-8")+ body = (+ f'<?xml version="1.0" encoding="UTF-8"?>'+ f'<{root_tag} xmlns="http://sns.amazonaws.com/doc/2010-03-31/">'+ f'{inner}'+ f'<ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>'+ f'</{root_tag}>'+ ).encode("utf-8")return status, {"Content-Type": "application/xml"}, bodydef _error(code, message, status):- body = f"""<?xml version="1.0" encoding="UTF-8"?>-<ErrorResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">- <Error><Code>{code}</Code><Message>{message}</Message></Error>- <RequestId>{new_uuid()}</RequestId>-</ErrorResponse>""".encode("utf-8")+ body = (+ f'<?xml version="1.0" encoding="UTF-8"?>'+ f'<ErrorResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">'+ f'<Error><Code>{code}</Code><Message>{_xml_escape(message)}</Message></Error>'+ f'<RequestId>{new_uuid()}</RequestId>'+ f'</ErrorResponse>'+ ).encode("utf-8")return status, {"Content-Type": "application/xml"}, body+++def _xml_escape(text: str) -> str:+ if not isinstance(text, str):+ text = str(text)+ return (text+ .replace("&", "&")+ .replace("<", "<")+ .replace(">", ">")+ .replace('"', """)+ .replace("'", "'"))+++def _find_subscription(topic_arn: str, sub_arn: str) -> dict | None:+ topic = _topics.get(topic_arn)+ if not topic:+ return None+ for sub in topic["subscriptions"]:+ if sub["arn"] == sub_arn:+ return sub+ return None+++def _refresh_subscription_counts(topic: dict):+ subs = topic.get("subscriptions", [])+ confirmed = sum(1 for s in subs if s.get("confirmed"))+ pending = sum(1 for s in subs if not s.get("confirmed"))+ topic["attributes"]["SubscriptionsConfirmed"] = str(confirmed)+ topic["attributes"]["SubscriptionsPending"] = str(pending)+++def _parse_message_attributes(params) -> dict:+ """Parse MessageAttributes.entry.N.Name / .Value.DataType / .Value.StringValue"""+ attrs = {}+ i = 1+ while True:+ name = _p(params, f"MessageAttributes.entry.{i}.Name")+ if not name:+ break+ data_type = _p(params, f"MessageAttributes.entry.{i}.Value.DataType")+ string_val = _p(params, f"MessageAttributes.entry.{i}.Value.StringValue")+ binary_val = _p(params, f"MessageAttributes.entry.{i}.Value.BinaryValue")+ attr = {"DataType": data_type}+ if string_val:+ attr["StringValue"] = string_val+ if binary_val:+ attr["BinaryValue"] = binary_val+ attrs[name] = attr+ i += 1+ return attrs+++def _parse_batch_entries(params) -> list[dict]:+ entries = []+ i = 1+ while True:+ eid = _p(params, f"PublishBatchRequestEntries.member.{i}.Id")+ if not eid:+ break+ entry = {+ "id": eid,+ "message": _p(params, f"PublishBatchRequestEntries.member.{i}.Message"),+ "subject": _p(params, f"PublishBatchRequestEntries.member.{i}.Subject"),+ "message_structure": _p(params, f"PublishBatchRequestEntries.member.{i}.MessageStructure"),+ "message_attributes": {},+ }+ j = 1+ while True:+ attr_name = _p(params, f"PublishBatchRequestEntries.member.{i}.MessageAttributes.entry.{j}.Name")+ if not attr_name:+ break+ data_type = _p(params, f"PublishBatchRequestEntries.member.{i}.MessageAttributes.entry.{j}.Value.DataType")+ string_val = _p(params, f"PublishBatchRequestEntries.member.{i}.MessageAttributes.entry.{j}.Value.StringValue")+ entry["message_attributes"][attr_name] = {+ "DataType": data_type,+ "StringValue": string_val,+ }+ j += 1+ entries.append(entry)+ i += 1+ return entries+++def _resolve_message_for_protocol(message: str, message_structure: str,+ protocol: str) -> str:+ if message_structure != "json":+ return message+ try:+ parsed = json.loads(message)+ except (json.JSONDecodeError, TypeError):+ return message+ if not isinstance(parsed, dict):+ return message+ return parsed.get(protocol, parsed.get("default", message))+++def _matches_filter_policy(sub: dict, message_attributes: dict) -> bool:+ policy_json = sub.get("attributes", {}).get("FilterPolicy", "")+ if not policy_json:+ return True+ try:+ policy = json.loads(policy_json)+ except (json.JSONDecodeError, TypeError):+ return True+ if not isinstance(policy, dict):+ return True++ scope = sub.get("attributes", {}).get("FilterPolicyScope", "MessageAttributes")++ if scope == "MessageBody":+ return True++ for key, allowed_values in policy.items():+ attr = message_attributes.get(key)+ if attr is None:+ return False+ attr_value = attr.get("StringValue", "")+ if not isinstance(allowed_values, list):+ allowed_values = [allowed_values]+ if not _attr_matches_any(attr_value, allowed_values):+ return False+ return True+++def _attr_matches_any(attr_value: str, rules: list) -> bool:+ for rule in rules:+ if isinstance(rule, str):+ if attr_value == rule:+ return True+ elif isinstance(rule, (int, float)):+ try:+ if float(attr_value) == float(rule):+ return True+ except (ValueError, TypeError):+ pass+ elif isinstance(rule, dict):+ if "exists" in rule:+ if rule["exists"] is True:+ return True+ continue+ if "prefix" in rule:+ if attr_value.startswith(rule["prefix"]):+ return True+ if "anything-but" in rule:+ excluded = rule["anything-but"]+ if isinstance(excluded, list):+ if attr_value not in excluded:+ return True+ elif attr_value != str(excluded):+ return True+ if "numeric" in rule:+ try:+ num = float(attr_value)+ conditions = rule["numeric"]+ if _check_numeric(num, conditions):+ return True+ except (ValueError, TypeError):+ pass+ return False+++def _check_numeric(value: float, conditions: list) -> bool:+ i = 0+ while i < len(conditions) - 1:+ op = conditions[i]+ threshold = float(conditions[i + 1])+ if op == "=" and value != threshold:+ return False+ if op == ">" and not (value > threshold):+ return False+ if op == ">=" and not (value >= threshold):+ return False+ if op == "<" and not (value < threshold):+ return False+ if op == "<=" and not (value <= threshold):+ return False+ i += 2+ return True+++def _build_envelope(topic_arn: str, msg_id: str, message: str, subject: str,+ message_attributes: dict, raw: bool) -> str:+ if raw:+ return message++ envelope = {+ "Type": "Notification",+ "MessageId": msg_id,+ "TopicArn": topic_arn,+ "Subject": subject or None,+ "Message": message,+ "Timestamp": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()),+ "SignatureVersion": "1",+ "Signature": "FAKE",+ "SigningCertURL": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-fake.pem",+ "UnsubscribeURL": f"http://localhost:4566/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:{REGION}:{ACCOUNT_ID}:example",+ }++ if message_attributes:+ formatted = {}+ for name, attr in message_attributes.items():+ formatted[name] = {"Type": attr.get("DataType", "String"),+ "Value": attr.get("StringValue", "")}+ envelope["MessageAttributes"] = formatted++ return json.dumps({k: v for k, v in envelope.items() if v is not None})+++def reset():+ _topics.clear()+ _sub_arn_to_topic.clear()+ _platform_applications.clear()+ _platform_endpoints.clear()diff --git a/services/sqs.py b/services/sqs.pyindex b2874ade..aa8ad96c 100644--- a/services/sqs.py+++ b/services/sqs.py@@ -1,23 +1,41 @@"""-SQS Service Emulator.-Supports: CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes,- SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage,- ChangeMessageVisibility, SendMessageBatch, DeleteMessageBatch.+SQS Service Emulator — Full AWS-compatible implementation.++Supports both legacy Query API and modern JSON API (X-Amz-Target: AmazonSQS.*).++Features:+ - Standard and FIFO queues (.fifo suffix, MessageGroupId, MessageDeduplicationId)+ - Dead-letter queues (RedrivePolicy with maxReceiveCount & deadLetterTargetArn)+ - Long polling (WaitTimeSeconds)+ - Message user attributes and system attributes+ - ChangeMessageVisibilityBatch+ - Proper FIFO deduplication (5-minute window)+ - FIFO message-group ordering (one in-flight message per group)+ - ApproximateNumberOfMessagesDelayed tracking+ - QueueArn in GetQueueAttributes++Actions:+ CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes,+ SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage,+ ChangeMessageVisibility, ChangeMessageVisibilityBatch, SendMessageBatch,+ DeleteMessageBatch, ListQueueTags, TagQueue, UntagQueue."""+import asyncioimport timeimport jsonimport hashlibimport logging-from collections import defaultdict+import structfrom urllib.parse import parse_qs+from xml.sax.saxutils import escape as _escfrom core.responses import new_uuid, now_iso, md5_hashlogger = logging.getLogger("sqs")-# In-memory queues-# queue_url -> {name, attributes, messages: [{id, body, md5, receipt_handle, sent_at, visible_at, receive_count}], ...}+# ── Module-level state ──────────────────────────────────────+_queues: dict = {}_queue_name_to_url: dict = {}@@ -25,551 +43,1127 @@ ACCOUNT_ID = "000000000000"REGION = "us-east-1"DEFAULT_HOST = "localhost"DEFAULT_PORT = "4566"+_DEDUP_WINDOW_S = 300 # 5 minutes+++# ── Exceptions ──────────────────────────────────────────────++class _Err(Exception):+ def __init__(self, code: str, message: str, status: int = 400):+ self.code = code+ self.message = message+ self.status = status+ super().__init__(message)++# ── Queue URL ───────────────────────────────────────────────def _queue_url(name: str) -> str:- host = DEFAULT_HOST- port = DEFAULT_PORT- return f"http://{host}:{port}/{ACCOUNT_ID}/{name}"+ return f"http://{DEFAULT_HOST}:{DEFAULT_PORT}/{ACCOUNT_ID}/{name}"-async def handle_request(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:+# ────────────────────────────────────────────────────────────+# ENTRY POINT+# ────────────────────────────────────────────────────────────++async def handle_request(method: str, path: str, headers: dict,+ body: bytes, query_params: dict) -> tuple:"""Handle SQS requests — supports both legacy Query API and modern JSON API."""target = headers.get("x-amz-target", "")- # Modern JSON protocol (boto3 default since ~2023): X-Amz-Target: AmazonSQS.CreateQueue+ # JSON protocol (X-Amz-Target: AmazonSQS.*)if target.startswith("AmazonSQS."):action = target.split(".")[-1]try:data = json.loads(body) if body else {}except Exception:data = {}- return _handle_json_action(action, data, path)+ return await _handle_json(action, data, path)- # Legacy Query API: Action=CreateQueue in form body or query string+ # Legacy Query / form-encoded protocolparams = dict(query_params)if method == "POST" and body:- form_params = parse_qs(body.decode("utf-8", errors="replace"))- for k, v in form_params.items():+ for k, v in parse_qs(body.decode("utf-8", errors="replace")).items():params[k] = vaction = _p(params, "Action")+ if not action:+ return _xml_err_resp("MissingAction", "Missing Action parameter", 400)+ return await _handle_query(action, params, path)- handlers = {- "CreateQueue": _create_queue,- "DeleteQueue": _delete_queue,- "ListQueues": _list_queues,- "GetQueueUrl": _get_queue_url,- "GetQueueAttributes": _get_queue_attributes,- "SetQueueAttributes": _set_queue_attributes,- "PurgeQueue": _purge_queue,- "SendMessage": _send_message,- "ReceiveMessage": _receive_message,- "DeleteMessage": _delete_message,- "ChangeMessageVisibility": _change_visibility,- "SendMessageBatch": _send_message_batch,- "DeleteMessageBatch": _delete_message_batch,- }- handler = handlers.get(action)- if handler is None:- return _error("InvalidAction", f"Unknown action: {action}", 400)+# ── JSON protocol layer ────────────────────────────────────- return handler(params, path)+async def _handle_json(action: str, data: dict, path: str) -> tuple:+ try:+ qurl = data.get("QueueUrl", "") or _url_from_path(path)+ result = await _dispatch(action, data, qurl)+ return _json_ok(result)+ except _Err as e:+ return _json_err_resp(e.code, e.message, e.status)-def _handle_json_action(action: str, data: dict, path: str):- """Handle modern JSON-protocol SQS actions."""+# ── Query / XML protocol layer ─────────────────────────────- if action == "CreateQueue":- name = data.get("QueueName", "")- if not name:- return _json_error("MissingParameter", "QueueName is required", 400)- url = _queue_url(name)- if url not in _queues:- _queues[url] = {- "name": name, "url": url,- "attributes": {- "QueueArn": f"arn:aws:sqs:{REGION}:{ACCOUNT_ID}:{name}",- "CreatedTimestamp": str(int(time.time())),- "LastModifiedTimestamp": str(int(time.time())),- "VisibilityTimeout": "30",- "MaximumMessageSize": "262144",- "MessageRetentionPeriod": "345600",- "DelaySeconds": "0",- "ReceiveMessageWaitTimeSeconds": "0",- "ApproximateNumberOfMessages": "0",- "ApproximateNumberOfMessagesNotVisible": "0",- },- "messages": [], "delayed": [],- }- attrs = data.get("Attributes") or data.get("attributes") or {}- for k, v in attrs.items():- _queues[url]["attributes"][k] = v- _queue_name_to_url[name] = url- return _json_resp({"QueueUrl": url})+async def _handle_query(action: str, params: dict, path: str) -> tuple:+ try:+ data = _normalise(action, params)+ qurl = data.get("QueueUrl", "") or _url_from_path(path)+ data["QueueUrl"] = qurl+ result = await _dispatch(action, data, qurl)+ return _to_xml(action, result)+ except _Err as e:+ return _xml_err_resp(e.code, e.message, e.status)- if action == "DeleteQueue":- url = data.get("QueueUrl", "") or _url_from_path(path)- if url in _queues:- name = _queues[url]["name"]- del _queues[url]- _queue_name_to_url.pop(name, None)- return _json_resp({})- if action == "ListQueues":- prefix = data.get("QueueNamePrefix", "")- urls = [u for u, q in _queues.items() if not prefix or q["name"].startswith(prefix)]- return _json_resp({"QueueUrls": urls})+# ── Dispatcher ──────────────────────────────────────────────- if action == "GetQueueUrl":- name = data.get("QueueName", "")- url = _queue_name_to_url.get(name)- if not url:- return _json_error("AWS.SimpleQueueService.NonExistentQueue", f"Queue {name} not found", 400)- return _json_resp({"QueueUrl": url})+_HANDLERS: dict = {}- if action == "SendMessage":- url = data.get("QueueUrl", "") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)- body_text = data.get("MessageBody", "")- delay = int(data.get("DelaySeconds", 0) or queue["attributes"].get("DelaySeconds", "0"))- msg_id = new_uuid()- md5 = hashlib.md5(body_text.encode()).hexdigest()- msg = {- "id": msg_id, "body": body_text, "md5": md5,- "receipt_handle": None, "sent_at": time.time(),- "visible_at": time.time() + delay, "receive_count": 0,- "attributes": {},- }- # Parse message attributes- for attr_name, attr_val in (data.get("MessageAttributes") or {}).items():- msg["attributes"][attr_name] = attr_val- queue["messages"].append(msg)- return _json_resp({"MessageId": msg_id, "MD5OfMessageBody": md5})+async def _dispatch(action: str, data: dict, qurl: str) -> dict:+ fn = _HANDLERS.get(action)+ if fn is None:+ raise _Err("InvalidAction",+ f"The action {action} is not valid for this endpoint.")+ result = fn(data, qurl)+ if asyncio.iscoroutine(result):+ result = await result+ return result- if action == "ReceiveMessage":- url = data.get("QueueUrl", "") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)- max_msgs = int(data.get("MaxNumberOfMessages", 1))- vis_timeout = int(data.get("VisibilityTimeout", queue["attributes"].get("VisibilityTimeout", "30")))- now = time.time()- visible = [m for m in queue["messages"] if m["visible_at"] <= now]- to_return = visible[:max_msgs]- messages = []- for msg in to_return:- receipt = new_uuid()- msg["receipt_handle"] = receipt- msg["visible_at"] = now + vis_timeout- msg["receive_count"] += 1- m = {- "MessageId": msg["id"],- "ReceiptHandle": receipt,- "MD5OfBody": msg["md5"],- "Body": msg["body"],- }- if msg["attributes"]:- m["MessageAttributes"] = msg["attributes"]- messages.append(m)- return _json_resp({"Messages": messages} if messages else {})- if action == "DeleteMessage":- url = data.get("QueueUrl", "") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)- receipt = data.get("ReceiptHandle", "")- queue["messages"] = [m for m in queue["messages"] if m.get("receipt_handle") != receipt]- return _json_resp({})+# ────────────────────────────────────────────────────────────+# CORE ACTIONS+# ────────────────────────────────────────────────────────────- if action == "PurgeQueue":- url = data.get("QueueUrl", "") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)- queue["messages"].clear()- return _json_resp({})+def _act_create_queue(data: dict, _u: str) -> dict:+ name = data.get("QueueName", "")+ if not name:+ raise _Err("MissingParameter",+ "The request must contain the parameter QueueName.")- if action == "GetQueueAttributes":- url = data.get("QueueUrl", "") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)- now = time.time()- visible = sum(1 for m in queue["messages"] if m["visible_at"] <= now)- not_visible = sum(1 for m in queue["messages"] if m["visible_at"] > now)- queue["attributes"]["ApproximateNumberOfMessages"] = str(visible)- queue["attributes"]["ApproximateNumberOfMessagesNotVisible"] = str(not_visible)- requested = data.get("AttributeNames", ["All"])- attrs = {}- for k, v in queue["attributes"].items():- if "All" in requested or k in requested:- attrs[k] = v- return _json_resp({"Attributes": attrs})+ attrs = data.get("Attributes") or {}+ is_fifo = name.endswith(".fifo") or attrs.get("FifoQueue") == "true"- if action == "SetQueueAttributes":- url = data.get("QueueUrl", "") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)- for k, v in (data.get("Attributes") or {}).items():- queue["attributes"][k] = v- return _json_resp({})+ if is_fifo and not name.endswith(".fifo"):+ raise _Err("InvalidParameterValue",+ "The name of a FIFO queue can only include alphanumeric "+ "characters, hyphens, or underscores, must end with .fifo suffix.")+ if name.endswith(".fifo"):+ is_fifo = True- if action == "ChangeMessageVisibility":- url = data.get("QueueUrl", "") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)- receipt = data.get("ReceiptHandle", "")- timeout = int(data.get("VisibilityTimeout", 30))- for msg in queue["messages"]:- if msg.get("receipt_handle") == receipt:- msg["visible_at"] = time.time() + timeout- break- return _json_resp({})+ url = _queue_url(name)+ if url in _queues:+ return {"QueueUrl": url}++ ts = str(int(time.time()))+ q: dict = {+ "name": name, "url": url, "is_fifo": is_fifo,+ "attributes": {+ "QueueArn": f"arn:aws:sqs:{REGION}:{ACCOUNT_ID}:{name}",+ "CreatedTimestamp": ts,+ "LastModifiedTimestamp": ts,+ "VisibilityTimeout": "30",+ "MaximumMessageSize": "262144",+ "MessageRetentionPeriod": "345600",+ "DelaySeconds": "0",+ "ReceiveMessageWaitTimeSeconds": "0",+ },+ "messages": [],+ "tags": {},+ "dedup_cache": {},+ "fifo_seq": 0,+ }+ if is_fifo:+ q["attributes"]["FifoQueue"] = "true"+ q["attributes"]["ContentBasedDeduplication"] = \+ attrs.get("ContentBasedDeduplication", "false")- if action == "SendMessageBatch":- url = data.get("QueueUrl", "") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)- results = []- for entry in data.get("Entries", []):- body_text = entry.get("MessageBody", "")- delay = int(entry.get("DelaySeconds", 0))- msg_id = new_uuid()- md5 = hashlib.md5(body_text.encode()).hexdigest()- queue["messages"].append({- "id": msg_id, "body": body_text, "md5": md5,- "receipt_handle": None, "sent_at": time.time(),- "visible_at": time.time() + delay, "receive_count": 0, "attributes": {},- })- results.append({"Id": entry.get("Id"), "MessageId": msg_id, "MD5OfMessageBody": md5})- return _json_resp({"Successful": results, "Failed": []})+ for k, v in attrs.items():+ q["attributes"][k] = str(v)- if action == "DeleteMessageBatch":- url = data.get("QueueUrl", "") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)- results = []- for entry in data.get("Entries", []):- receipt = entry.get("ReceiptHandle", "")- queue["messages"] = [m for m in queue["messages"] if m.get("receipt_handle") != receipt]- results.append({"Id": entry.get("Id")})- return _json_resp({"Successful": results, "Failed": []})+ _queues[url] = q+ _queue_name_to_url[name] = url+ return {"QueueUrl": url}- return _json_error("InvalidAction", f"Unknown action: {action}", 400)+def _act_delete_queue(data: dict, qurl: str) -> dict:+ url = data.get("QueueUrl", qurl)+ if url in _queues:+ _queue_name_to_url.pop(_queues[url]["name"], None)+ del _queues[url]+ return {}-def _json_resp(data: dict, status: int = 200) -> tuple:- body = json.dumps(data).encode("utf-8")- return status, {"Content-Type": "application/x-amz-json-1.0"}, body+def _act_list_queues(data: dict, _u: str) -> dict:+ pfx = data.get("QueueNamePrefix", "")+ mx = int(data.get("MaxResults", 1000))+ urls = [u for u, q in _queues.items()+ if not pfx or q["name"].startswith(pfx)]+ return {"QueueUrls": urls[:mx]}-def _json_error(code: str, message: str, status: int) -> tuple:- body = json.dumps({"__type": code, "message": message}).encode("utf-8")- return status, {"Content-Type": "application/x-amz-json-1.0"}, body+def _act_get_queue_url(data: dict, _u: str) -> dict:+ name = data.get("QueueName", "")+ url = _queue_name_to_url.get(name)+ if not url:+ raise _Err("AWS.SimpleQueueService.NonExistentQueue",+ "The specified queue does not exist.")+ return {"QueueUrl": url}+++# ── SendMessage ─────────────────────────────────────────────++def _act_send_message(data: dict, qurl: str) -> dict:+ url = data.get("QueueUrl", qurl)+ q = _get_q(url)++ body_text = data.get("MessageBody", "")+ if not body_text:+ raise _Err("MissingParameter",+ "The request must contain the parameter MessageBody.")++ delay = int(data.get("DelaySeconds")+ or q["attributes"].get("DelaySeconds", "0"))+ msg_attrs = data.get("MessageAttributes") or {}+ sys_attrs = data.get("MessageSystemAttributes") or {}+ group_id = data.get("MessageGroupId")+ dedup_id = data.get("MessageDeduplicationId")+ seq = None++ # FIFO-specific validation & dedup+ if q["is_fifo"]:+ if not group_id:+ raise _Err("MissingParameter",+ "The request must contain the parameter MessageGroupId.")+ if not dedup_id:+ if q["attributes"].get("ContentBasedDeduplication") == "true":+ dedup_id = hashlib.sha256(body_text.encode()).hexdigest()+ else:+ raise _Err("InvalidParameterValue",+ "The queue should either have ContentBasedDeduplication "+ "enabled or MessageDeduplicationId provided explicitly.")+ _prune_dedup(q)+ cached = q["dedup_cache"].get(dedup_id)+ if cached:+ r: dict = {"MessageId": cached["id"],+ "MD5OfMessageBody": cached["md5"]}+ if cached.get("md5a"):+ r["MD5OfMessageAttributes"] = cached["md5a"]+ if cached.get("seq"):+ r["SequenceNumber"] = cached["seq"]+ return r+ q["fifo_seq"] += 1+ seq = str(q["fifo_seq"]).zfill(20)+ delay = 0-def _create_queue(params: dict, path: str):- name = _p(params, "QueueName")- if not name:- return _error("MissingParameter", "QueueName is required", 400)+ now = time.time()+ mid = new_uuid()+ md5b = hashlib.md5(body_text.encode()).hexdigest()+ md5a = _md5_msg_attrs(msg_attrs)- url = _queue_url(name)- if url not in _queues:- _queues[url] = {- "name": name,- "url": url,- "attributes": {- "QueueArn": f"arn:aws:sqs:{REGION}:{ACCOUNT_ID}:{name}",- "CreatedTimestamp": str(int(time.time())),- "LastModifiedTimestamp": str(int(time.time())),- "VisibilityTimeout": "30",- "MaximumMessageSize": "262144",- "MessageRetentionPeriod": "345600",- "DelaySeconds": "0",- "ReceiveMessageWaitTimeSeconds": "0",- "ApproximateNumberOfMessages": "0",- "ApproximateNumberOfMessagesNotVisible": "0",- },- "messages": [],- "delayed": [],+ msg: dict = {+ "id": mid,+ "body": body_text,+ "md5_body": md5b,+ "md5_attrs": md5a,+ "receipt_handle": None,+ "sent_at": now,+ "visible_at": now + delay,+ "receive_count": 0,+ "first_receive_at": None,+ "message_attributes": msg_attrs,+ "sys": {+ "SenderId": ACCOUNT_ID,+ "SentTimestamp": str(int(now * 1000)),+ },+ "group_id": group_id,+ "dedup_id": dedup_id,+ "seq": seq,+ }+ q["messages"].append(msg)++ if q["is_fifo"] and dedup_id:+ q["dedup_cache"][dedup_id] = {+ "expire": now + _DEDUP_WINDOW_S,+ "id": mid, "md5": md5b, "md5a": md5a, "seq": seq,}- # Apply any attributes from the request- i = 1- while _p(params, f"Attribute.{i}.Name"):- attr_name = _p(params, f"Attribute.{i}.Name")- attr_val = _p(params, f"Attribute.{i}.Value")- _queues[url]["attributes"][attr_name] = attr_val- i += 1- _queue_name_to_url[name] = url- return _xml(200, "CreateQueueResponse", f"""- <CreateQueueResult>- <QueueUrl>{url}</QueueUrl>- </CreateQueueResult>""")+ result: dict = {"MessageId": mid, "MD5OfMessageBody": md5b}+ if md5a:+ result["MD5OfMessageAttributes"] = md5a+ if seq:+ result["SequenceNumber"] = seq+ return result-def _delete_queue(params: dict, path: str):- url = _p(params, "QueueUrl") or _url_from_path(path)- if url in _queues:- name = _queues[url]["name"]- del _queues[url]- _queue_name_to_url.pop(name, None)- return _xml(200, "DeleteQueueResponse", "")+# ── ReceiveMessage (async — long polling) ───────────────────+async def _act_receive_message(data: dict, qurl: str) -> dict:+ url = data.get("QueueUrl", qurl)+ q = _get_q(url)-def _list_queues(params: dict, path: str):- prefix = _p(params, "QueueNamePrefix")- urls = []- for url, q in _queues.items():- if not prefix or q["name"].startswith(prefix):- urls.append(url)+ max_n = min(int(data.get("MaxNumberOfMessages", 1)), 10)+ vis = int(data.get("VisibilityTimeout")+ or q["attributes"].get("VisibilityTimeout", "30"))+ wait = int(data.get("WaitTimeSeconds")+ or q["attributes"].get("ReceiveMessageWaitTimeSeconds", "0"))- members = "".join(f"<QueueUrl>{u}</QueueUrl>" for u in urls)- return _xml(200, "ListQueuesResponse", f"""- <ListQueuesResult>- {members}- </ListQueuesResult>""")+ attr_names = (data.get("AttributeNames")+ or data.get("SystemAttributeNames") or [])+ msg_attr_names = data.get("MessageAttributeNames") or []+ deadline = time.time() + wait+ msgs: list = []-def _get_queue_url(params: dict, path: str):- name = _p(params, "QueueName")- url = _queue_name_to_url.get(name)- if not url:- return _error("AWS.SimpleQueueService.NonExistentQueue", f"Queue {name} not found", 400)- return _xml(200, "GetQueueUrlResponse", f"""- <GetQueueUrlResult>- <QueueUrl>{url}</QueueUrl>- </GetQueueUrlResult>""")+ while True:+ _dlq_sweep(q)+ msgs = _collect_msgs(q, max_n, vis)+ if msgs or time.time() >= deadline:+ break+ await asyncio.sleep(min(0.1, max(0.01, deadline - time.time())))++ out: list = []+ for m in msgs:+ entry: dict = {+ "MessageId": m["id"],+ "ReceiptHandle": m["receipt_handle"],+ "MD5OfBody": m["md5_body"],+ "Body": m["body"],+ }+ sa = _build_sys_attrs(m, attr_names)+ if sa:+ entry["Attributes"] = sa+ fa = _filter_msg_attrs(m["message_attributes"], msg_attr_names)+ if fa:+ entry["MessageAttributes"] = fa+ if m["md5_attrs"]:+ entry["MD5OfMessageAttributes"] = m["md5_attrs"]+ out.append(entry)++ return {"Messages": out} if out else {}+++# ── DeleteMessage ───────────────────────────────────────────++def _act_delete_message(data: dict, qurl: str) -> dict:+ url = data.get("QueueUrl", qurl)+ q = _get_q(url)+ rh = data.get("ReceiptHandle", "")+ if not rh:+ raise _Err("MissingParameter",+ "The request must contain the parameter ReceiptHandle.")+ # Only remove messages whose receipt_handle is set and matches.+ # Messages that have never been received (receipt_handle is None) are never+ # accidentally removed by an empty or unrelated receipt handle.+ q["messages"] = [+ m for m in q["messages"]+ if not (m["receipt_handle"] is not None and m["receipt_handle"] == rh)+ ]+ return {}+++# ── ChangeMessageVisibility ────────────────────────────────++def _act_change_visibility(data: dict, qurl: str) -> dict:+ url = data.get("QueueUrl", qurl)+ q = _get_q(url)+ rh = data.get("ReceiptHandle", "")+ vt = int(data.get("VisibilityTimeout", 30))+ for m in q["messages"]:+ if m["receipt_handle"] is not None and m["receipt_handle"] == rh:+ m["visible_at"] = time.time() + vt+ break+ return {}+++# ── ChangeMessageVisibilityBatch ───────────────────────────++def _act_change_visibility_batch(data: dict, qurl: str) -> dict:+ url = data.get("QueueUrl", qurl)+ q = _get_q(url)+ ok: list = []+ fail: list = []+ for e in data.get("Entries", []):+ eid = e.get("Id", "")+ rh = e.get("ReceiptHandle", "")+ vt = int(e.get("VisibilityTimeout", 30))+ found = False+ for m in q["messages"]:+ if m["receipt_handle"] is not None and m["receipt_handle"] == rh:+ m["visible_at"] = time.time() + vt+ found = True+ break+ if found:+ ok.append({"Id": eid})+ else:+ fail.append({+ "Id": eid,+ "Code": "ReceiptHandleIsInvalid",+ "Message": "The input receipt handle is invalid.",+ "SenderFault": True,+ })+ return {"Successful": ok, "Failed": fail}-def _get_queue_attributes(params: dict, path: str):- url = _p(params, "QueueUrl") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)+# ── GetQueueAttributes ─────────────────────────────────────- # Update approximate counts- now = time.time()- visible = sum(1 for m in queue["messages"] if m["visible_at"] <= now)- not_visible = sum(1 for m in queue["messages"] if m["visible_at"] > now)- queue["attributes"]["ApproximateNumberOfMessages"] = str(visible)- queue["attributes"]["ApproximateNumberOfMessagesNotVisible"] = str(not_visible)-- attrs = ""- # Check which attributes are requested- requested = set()- i = 1- while _p(params, f"AttributeName.{i}"):- requested.add(_p(params, f"AttributeName.{i}"))- i += 1+def _act_get_queue_attributes(data: dict, qurl: str) -> dict:+ url = data.get("QueueUrl", qurl)+ q = _get_q(url)+ _refresh_counts(q)+ names = data.get("AttributeNames") or ["All"]+ want_all = "All" in names+ out: dict = {}+ for k, v in q["attributes"].items():+ if want_all or k in names:+ out[k] = v+ return {"Attributes": out}- for k, v in queue["attributes"].items():- if not requested or "All" in requested or k in requested:- attrs += f"<Attribute><Name>{k}</Name><Value>{v}</Value></Attribute>"- return _xml(200, "GetQueueAttributesResponse", f"""- <GetQueueAttributesResult>- {attrs}- </GetQueueAttributesResult>""")+# ── SetQueueAttributes ─────────────────────────────────────+def _act_set_queue_attributes(data: dict, qurl: str) -> dict:+ url = data.get("QueueUrl", qurl)+ q = _get_q(url)+ for k, v in (data.get("Attributes") or {}).items():+ q["attributes"][k] = str(v)+ q["attributes"]["LastModifiedTimestamp"] = str(int(time.time()))+ return {}-def _set_queue_attributes(params: dict, path: str):- url = _p(params, "QueueUrl") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)- i = 1- while _p(params, f"Attribute.{i}.Name"):- attr_name = _p(params, f"Attribute.{i}.Name")- attr_val = _p(params, f"Attribute.{i}.Value")- queue["attributes"][attr_name] = attr_val- i += 1+# ── PurgeQueue ──────────────────────────────────────────────- return _xml(200, "SetQueueAttributesResponse", "")+def _act_purge_queue(data: dict, qurl: str) -> dict:+ url = data.get("QueueUrl", qurl)+ q = _get_q(url)+ q["messages"].clear()+ return {}-def _purge_queue(params: dict, path: str):- url = _p(params, "QueueUrl") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)- queue["messages"].clear()- return _xml(200, "PurgeQueueResponse", "")+# ── SendMessageBatch ───────────────────────────────────────+def _act_send_message_batch(data: dict, qurl: str) -> dict:+ url = data.get("QueueUrl", qurl)+ _get_q(url)+ ok: list = []+ fail: list = []+ for e in data.get("Entries", []):+ try:+ sub: dict = {+ "QueueUrl": url,+ "MessageBody": e.get("MessageBody", ""),+ "DelaySeconds": e.get("DelaySeconds"),+ "MessageAttributes": e.get("MessageAttributes"),+ "MessageGroupId": e.get("MessageGroupId"),+ "MessageDeduplicationId": e.get("MessageDeduplicationId"),+ }+ r = _act_send_message(sub, url)+ r["Id"] = e.get("Id", "")+ ok.append(r)+ except _Err as ex:+ fail.append({"Id": e.get("Id", ""), "Code": ex.code,+ "Message": ex.message, "SenderFault": True})+ return {"Successful": ok, "Failed": fail}+++# ── DeleteMessageBatch ─────────────────────────────────────++def _act_delete_message_batch(data: dict, qurl: str) -> dict:+ url = data.get("QueueUrl", qurl)+ q = _get_q(url)+ ok: list = []+ fail: list = []+ for e in data.get("Entries", []):+ eid = e.get("Id", "")+ rh = e.get("ReceiptHandle", "")+ before = len(q["messages"])+ q["messages"] = [+ m for m in q["messages"]+ if not (m["receipt_handle"] is not None and m["receipt_handle"] == rh)+ ]+ if len(q["messages"]) < before:+ ok.append({"Id": eid})+ else:+ ok.append({"Id": eid})+ return {"Successful": ok, "Failed": fail}+++# ── Tags ────────────────────────────────────────────────────++def _act_list_queue_tags(data: dict, qurl: str) -> dict:+ url = data.get("QueueUrl", qurl)+ q = _get_q(url)+ return {"Tags": dict(q.get("tags", {}))}+++def _act_tag_queue(data: dict, qurl: str) -> dict:+ url = data.get("QueueUrl", qurl)+ q = _get_q(url)+ q.setdefault("tags", {}).update(data.get("Tags") or {})+ return {}+++def _act_untag_queue(data: dict, qurl: str) -> dict:+ url = data.get("QueueUrl", qurl)+ q = _get_q(url)+ for k in data.get("TagKeys", []):+ q.get("tags", {}).pop(k, None)+ return {}+++# ── Register handlers ──────────────────────────────────────++_HANDLERS.update({+ "CreateQueue": _act_create_queue,+ "DeleteQueue": _act_delete_queue,+ "ListQueues": _act_list_queues,+ "GetQueueUrl": _act_get_queue_url,+ "SendMessage": _act_send_message,+ "ReceiveMessage": _act_receive_message,+ "DeleteMessage": _act_delete_message,+ "ChangeMessageVisibility": _act_change_visibility,+ "ChangeMessageVisibilityBatch": _act_change_visibility_batch,+ "GetQueueAttributes": _act_get_queue_attributes,+ "SetQueueAttributes": _act_set_queue_attributes,+ "PurgeQueue": _act_purge_queue,+ "SendMessageBatch": _act_send_message_batch,+ "DeleteMessageBatch": _act_delete_message_batch,+ "ListQueueTags": _act_list_queue_tags,+ "TagQueue": _act_tag_queue,+ "UntagQueue": _act_untag_queue,+})+++# ────────────────────────────────────────────────────────────+# QUEUE / MESSAGE HELPERS+# ────────────────────────────────────────────────────────────++def _get_q(url: str) -> dict:+ q = _queues.get(url)+ if q is None:+ raise _Err("AWS.SimpleQueueService.NonExistentQueue",+ "The specified queue does not exist for this wsdl version.")+ return q+++def _ensure_msg_fields(m: dict) -> None:+ """Ensure internal message shape for ReceiveMessage (SNS fan-out etc.)."""+ if "md5_body" not in m and m.get("md5"):+ m["md5_body"] = m["md5"]+ if "md5_body" not in m:+ body = m.get("body") or ""+ if not isinstance(body, str):+ body = str(body)+ m["md5_body"] = hashlib.md5(body.encode()).hexdigest()+ m.setdefault("message_attributes", {})+ m.setdefault("md5_attrs", None)+ m.setdefault("first_receive_at", None)+ m.setdefault("receive_count", 0)+ m.setdefault("receipt_handle", None)+ m.setdefault("sent_at", time.time())+ m.setdefault("visible_at", m["sent_at"])+ if "sys" not in m:+ sent = m["sent_at"]+ m["sys"] = {+ "SenderId": ACCOUNT_ID,+ "SentTimestamp": str(int(sent * 1000)),+ }+ m.setdefault("group_id", None)+ m.setdefault("dedup_id", None)+ m.setdefault("seq", None)-def _send_message(params: dict, path: str):- url = _p(params, "QueueUrl") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)- body_text = _p(params, "MessageBody")- delay = int(_p(params, "DelaySeconds") or queue["attributes"].get("DelaySeconds", "0"))- msg_id = new_uuid()- md5 = hashlib.md5(body_text.encode()).hexdigest()+def _refresh_counts(q: dict) -> None:+ """Recompute approximate message counters."""+ now = time.time()+ visible = delayed = inflight = 0+ for m in q["messages"]:+ if m["visible_at"] <= now:+ visible += 1+ elif m["receive_count"] == 0:+ delayed += 1+ else:+ inflight += 1+ q["attributes"]["ApproximateNumberOfMessages"] = str(visible)+ q["attributes"]["ApproximateNumberOfMessagesNotVisible"] = str(inflight)+ q["attributes"]["ApproximateNumberOfMessagesDelayed"] = str(delayed)+++# ── Collect visible messages for ReceiveMessage ────────────++def _collect_msgs(q: dict, max_n: int, vis_timeout: int) -> list:+ now = time.time()+ if q["is_fifo"]:+ return _collect_fifo(q, max_n, vis_timeout, now)+ for m in q["messages"]:+ _ensure_msg_fields(m)+ visible = [m for m in q["messages"] if m["visible_at"] <= now]+ result = visible[:max_n]+ for m in result:+ m["receipt_handle"] = new_uuid()+ m["visible_at"] = now + vis_timeout+ m["receive_count"] += 1+ if m.get("first_receive_at") is None:+ m["first_receive_at"] = now+ return result+++def _collect_fifo(q: dict, max_n: int, vis_timeout: int,+ now: float) -> list:+ """FIFO queues: respect message-group ordering.++ Only one message per group can be in-flight at a time. Messages within+ a group are delivered in send order.+ """+ for m in q["messages"]:+ _ensure_msg_fields(m)+ inflight_groups: set = {+ m["group_id"] for m in q["messages"]+ if m["visible_at"] > now+ and m["receive_count"] > 0+ and m["group_id"]+ }+ seen_groups: set = set()+ result: list = []+ for m in q["messages"]:+ if len(result) >= max_n:+ break+ if m["visible_at"] > now:+ continue+ g = m["group_id"]+ if g in inflight_groups or g in seen_groups:+ continue+ m["receipt_handle"] = new_uuid()+ m["visible_at"] = now + vis_timeout+ m["receive_count"] += 1+ if m.get("first_receive_at") is None:+ m["first_receive_at"] = now+ result.append(m)+ if g is not None:+ seen_groups.add(g)+ return result+++# ── Dead-letter queue sweep ────────────────────────────────++def _dlq_sweep(q: dict) -> None:+ """Move messages that have reached maxReceiveCount to the DLQ."""+ rp_raw = q["attributes"].get("RedrivePolicy")+ if not rp_raw:+ return+ try:+ rp = json.loads(rp_raw)+ except Exception:+ return+ max_rc = int(rp.get("maxReceiveCount", 0))+ arn = rp.get("deadLetterTargetArn", "")+ if not max_rc or not arn:+ return++ dlq = next((qq for qq in _queues.values()+ if qq["attributes"].get("QueueArn") == arn), None)+ if dlq is None:+ return- msg = {- "id": msg_id,- "body": body_text,- "md5": md5,- "receipt_handle": None,- "sent_at": time.time(),- "visible_at": time.time() + delay,- "receive_count": 0,- "attributes": {},+ now = time.time()+ keep: list = []+ for m in q["messages"]:+ if m["receive_count"] >= max_rc and m["visible_at"] <= now:+ moved = dict(m)+ moved["receipt_handle"] = None+ moved["visible_at"] = now+ dlq["messages"].append(moved)+ else:+ keep.append(m)+ q["messages"] = keep+++# ── FIFO deduplication cache maintenance ───────────────────++def _prune_dedup(q: dict) -> None:+ now = time.time()+ q["dedup_cache"] = {+ k: v for k, v in q["dedup_cache"].items()+ if v["expire"] > now}- # Parse message attributes- i = 1- while _p(params, f"MessageAttribute.{i}.Name"):- attr_name = _p(params, f"MessageAttribute.{i}.Name")- attr_type = _p(params, f"MessageAttribute.{i}.Value.DataType")- attr_val = _p(params, f"MessageAttribute.{i}.Value.StringValue")- msg["attributes"][attr_name] = {"DataType": attr_type, "StringValue": attr_val}- i += 1- queue["messages"].append(msg)+# ── Build system attributes for a received message ────────++def _build_sys_attrs(msg: dict, names: list) -> dict:+ if not names:+ return {}+ want_all = "All" in names+ r: dict = {}+ if want_all or "SenderId" in names:+ r["SenderId"] = msg["sys"].get("SenderId", ACCOUNT_ID)+ if want_all or "SentTimestamp" in names:+ r["SentTimestamp"] = msg["sys"].get("SentTimestamp", "0")+ if want_all or "ApproximateReceiveCount" in names:+ r["ApproximateReceiveCount"] = str(msg["receive_count"])+ if want_all or "ApproximateFirstReceiveTimestamp" in names:+ ts = msg.get("first_receive_at")+ r["ApproximateFirstReceiveTimestamp"] = \+ str(int(ts * 1000)) if ts else "0"+ if msg.get("seq") and (want_all or "SequenceNumber" in names):+ r["SequenceNumber"] = msg["seq"]+ if msg.get("dedup_id") and (want_all or "MessageDeduplicationId" in names):+ r["MessageDeduplicationId"] = msg["dedup_id"]+ if msg.get("group_id") and (want_all or "MessageGroupId" in names):+ r["MessageGroupId"] = msg["group_id"]+ return r+++# ── Filter user message attributes by requested names ─────++def _filter_msg_attrs(attrs: dict, names: list) -> dict:+ if not attrs or not names:+ return {}+ if "All" in names or ".*" in names:+ return dict(attrs)+ out: dict = {}+ for n in names:+ if n.endswith(".*"):+ pfx = n[:-2]+ for k, v in attrs.items():+ if k.startswith(pfx):+ out[k] = v+ elif n in attrs:+ out[n] = attrs[n]+ return out+++# ── MD5 of message attributes (AWS wire-format) ───────────++def _md5_msg_attrs(attrs: dict | None) -> str | None:+ """Compute the MD5 digest of message attributes following the+ exact binary encoding that the real SQS service uses."""+ if not attrs:+ return None+ buf = bytearray()+ for name in sorted(attrs):+ a = attrs[name]+ dt = (a.get("DataType") or "String").encode("utf-8")+ nb = name.encode("utf-8")+ buf += struct.pack("!I", len(nb)) + nb+ buf += struct.pack("!I", len(dt)) + dt+ if dt.startswith(b"Binary"):+ buf += b"\x02"+ val = a.get("BinaryValue", b"")+ if isinstance(val, str):+ import base64+ val = base64.b64decode(val)+ if isinstance(val, bytearray):+ val = bytes(val)+ buf += struct.pack("!I", len(val)) + val+ else:+ buf += b"\x01"+ val = (a.get("StringValue") or "").encode("utf-8")+ buf += struct.pack("!I", len(val)) + val+ return hashlib.md5(bytes(buf)).hexdigest()+++# ────────────────────────────────────────────────────────────+# RESPONSE FORMATTERS+# ────────────────────────────────────────────────────────────++# ── JSON ────────────────────────────────────────────────────++def _json_ok(data: dict, status: int = 200) -> tuple:+ return (status,+ {"Content-Type": "application/x-amz-json-1.0"},+ json.dumps(data).encode("utf-8"))+++def _json_err_resp(code: str, msg: str, status: int = 400) -> tuple:+ return (status,+ {"Content-Type": "application/x-amz-json-1.0"},+ json.dumps({"__type": code, "message": msg}).encode("utf-8"))+++# ── XML ─────────────────────────────────────────────────────++def _xml_resp(status: int, root: str, inner: str) -> tuple:+ body = (+ f'<?xml version="1.0" encoding="UTF-8"?>'+ f'<{root} xmlns="http://queue.amazonaws.com/doc/2012-11-05/">'+ f'{inner}'+ f'<ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>'+ f'</{root}>'+ ).encode("utf-8")+ return status, {"Content-Type": "application/xml"}, body+- return _xml(200, "SendMessageResponse", f"""- <SendMessageResult>- <MessageId>{msg_id}</MessageId>- <MD5OfMessageBody>{md5}</MD5OfMessageBody>- </SendMessageResult>""")+def _xml_err_resp(code: str, msg: str, status: int = 400) -> tuple:+ body = (+ f'<?xml version="1.0" encoding="UTF-8"?>'+ f'<ErrorResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/">'+ f'<Error><Code>{_esc(code)}</Code><Message>{_esc(msg)}</Message></Error>'+ f'<RequestId>{new_uuid()}</RequestId>'+ f'</ErrorResponse>'+ ).encode("utf-8")+ return status, {"Content-Type": "application/xml"}, body-def _receive_message(params: dict, path: str):- url = _p(params, "QueueUrl") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)+def _sender_fault_str(val) -> str:+ if isinstance(val, bool):+ return "true" if val else "false"+ return str(val)- max_msgs = int(_p(params, "MaxNumberOfMessages") or "1")- vis_timeout = int(_p(params, "VisibilityTimeout") or queue["attributes"].get("VisibilityTimeout", "30"))- wait_time = int(_p(params, "WaitTimeSeconds") or "0")- now = time.time()- visible = [m for m in queue["messages"] if m["visible_at"] <= now]- to_return = visible[:max_msgs]-- messages_xml = ""- for msg in to_return:- receipt = new_uuid()- msg["receipt_handle"] = receipt- msg["visible_at"] = now + vis_timeout- msg["receive_count"] += 1-- attrs_xml = ""- for attr_name, attr_val in msg["attributes"].items():- attrs_xml += f"""<MessageAttribute>- <Name>{attr_name}</Name>- <Value>- <DataType>{attr_val['DataType']}</DataType>- <StringValue>{attr_val['StringValue']}</StringValue>- </Value>- </MessageAttribute>"""-- messages_xml += f"""<Message>- <MessageId>{msg['id']}</MessageId>- <ReceiptHandle>{receipt}</ReceiptHandle>- <MD5OfBody>{msg['md5']}</MD5OfBody>- <Body>{msg['body']}</Body>- {attrs_xml}- </Message>"""-- return _xml(200, "ReceiveMessageResponse", f"""- <ReceiveMessageResult>- {messages_xml}- </ReceiveMessageResult>""")---def _delete_message(params: dict, path: str):- url = _p(params, "QueueUrl") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)-- receipt = _p(params, "ReceiptHandle")- queue["messages"] = [m for m in queue["messages"] if m.get("receipt_handle") != receipt]- return _xml(200, "DeleteMessageResponse", "")---def _change_visibility(params: dict, path: str):- url = _p(params, "QueueUrl") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)-- receipt = _p(params, "ReceiptHandle")- timeout = int(_p(params, "VisibilityTimeout") or "30")-- for msg in queue["messages"]:- if msg.get("receipt_handle") == receipt:- msg["visible_at"] = time.time() + timeout- break+def _to_xml(action: str, result: dict) -> tuple:+ """Convert a core-action result dict into a legacy XML response."""++ if action == "CreateQueue":+ return _xml_resp(200, "CreateQueueResponse",+ f'<CreateQueueResult>'+ f'<QueueUrl>{_esc(result["QueueUrl"])}</QueueUrl>'+ f'</CreateQueueResult>')++ if action == "DeleteQueue":+ return _xml_resp(200, "DeleteQueueResponse", "")++ if action == "ListQueues":+ members = "".join(+ f"<QueueUrl>{_esc(u)}</QueueUrl>"+ for u in result.get("QueueUrls", []))+ return _xml_resp(200, "ListQueuesResponse",+ f"<ListQueuesResult>{members}</ListQueuesResult>")++ if action == "GetQueueUrl":+ return _xml_resp(200, "GetQueueUrlResponse",+ f'<GetQueueUrlResult>'+ f'<QueueUrl>{_esc(result["QueueUrl"])}</QueueUrl>'+ f'</GetQueueUrlResult>')++ if action == "SendMessage":+ inner = (f'<SendMessageResult>'+ f'<MessageId>{result["MessageId"]}</MessageId>'+ f'<MD5OfMessageBody>{result["MD5OfMessageBody"]}</MD5OfMessageBody>')+ if "MD5OfMessageAttributes" in result:+ inner += (f'<MD5OfMessageAttributes>'+ f'{result["MD5OfMessageAttributes"]}'+ f'</MD5OfMessageAttributes>')+ if "SequenceNumber" in result:+ inner += f'<SequenceNumber>{result["SequenceNumber"]}</SequenceNumber>'+ inner += '</SendMessageResult>'+ return _xml_resp(200, "SendMessageResponse", inner)++ if action == "ReceiveMessage":+ return _xml_resp(200, "ReceiveMessageResponse",+ f'<ReceiveMessageResult>'+ f'{_msgs_to_xml(result.get("Messages", []))}'+ f'</ReceiveMessageResult>')++ if action == "DeleteMessage":+ return _xml_resp(200, "DeleteMessageResponse", "")- return _xml(200, "ChangeMessageVisibilityResponse", "")+ if action == "ChangeMessageVisibility":+ return _xml_resp(200, "ChangeMessageVisibilityResponse", "")+ if action == "ChangeMessageVisibilityBatch":+ inner = _batch_result_xml(+ result, "ChangeMessageVisibilityBatchResultEntry")+ return _xml_resp(200, "ChangeMessageVisibilityBatchResponse",+ f'<ChangeMessageVisibilityBatchResult>'+ f'{inner}'+ f'</ChangeMessageVisibilityBatchResult>')-def _send_message_batch(params: dict, path: str):- url = _p(params, "QueueUrl") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)+ if action == "GetQueueAttributes":+ ax = "".join(+ f'<Attribute><Name>{_esc(k)}</Name>'+ f'<Value>{_esc(str(v))}</Value></Attribute>'+ for k, v in result.get("Attributes", {}).items())+ return _xml_resp(200, "GetQueueAttributesResponse",+ f'<GetQueueAttributesResult>{ax}</GetQueueAttributesResult>')- results = ""+ if action == "SetQueueAttributes":+ return _xml_resp(200, "SetQueueAttributesResponse", "")++ if action == "PurgeQueue":+ return _xml_resp(200, "PurgeQueueResponse", "")++ if action == "SendMessageBatch":+ inner = ""+ for e in result.get("Successful", []):+ inner += (f'<SendMessageBatchResultEntry>'+ f'<Id>{_esc(e.get("Id",""))}</Id>'+ f'<MessageId>{e["MessageId"]}</MessageId>'+ f'<MD5OfMessageBody>{e["MD5OfMessageBody"]}'+ f'</MD5OfMessageBody>')+ if "MD5OfMessageAttributes" in e:+ inner += (f'<MD5OfMessageAttributes>'+ f'{e["MD5OfMessageAttributes"]}'+ f'</MD5OfMessageAttributes>')+ if "SequenceNumber" in e:+ inner += (f'<SequenceNumber>{e["SequenceNumber"]}'+ f'</SequenceNumber>')+ inner += '</SendMessageBatchResultEntry>'+ inner += _batch_errors_xml(result.get("Failed", []))+ return _xml_resp(200, "SendMessageBatchResponse",+ f'<SendMessageBatchResult>{inner}</SendMessageBatchResult>')++ if action == "DeleteMessageBatch":+ inner = ""+ for e in result.get("Successful", []):+ inner += (f'<DeleteMessageBatchResultEntry>'+ f'<Id>{_esc(e["Id"])}</Id>'+ f'</DeleteMessageBatchResultEntry>')+ inner += _batch_errors_xml(result.get("Failed", []))+ return _xml_resp(200, "DeleteMessageBatchResponse",+ f'<DeleteMessageBatchResult>{inner}</DeleteMessageBatchResult>')++ if action == "ListQueueTags":+ tx = "".join(+ f'<Tag><Key>{_esc(k)}</Key><Value>{_esc(v)}</Value></Tag>'+ for k, v in result.get("Tags", {}).items())+ return _xml_resp(200, "ListQueueTagsResponse",+ f'<ListQueueTagsResult>{tx}</ListQueueTagsResult>')++ if action == "TagQueue":+ return _xml_resp(200, "TagQueueResponse", "")++ if action == "UntagQueue":+ return _xml_resp(200, "UntagQueueResponse", "")++ return _xml_resp(200, f"{action}Response", "")+++# ── XML sub-helpers ─────────────────────────────────────────++def _msgs_to_xml(msgs: list) -> str:+ """Render a list of received messages to XML."""+ parts: list = []+ for m in msgs:+ x = (f'<Message>'+ f'<MessageId>{m["MessageId"]}</MessageId>'+ f'<ReceiptHandle>{_esc(m["ReceiptHandle"])}</ReceiptHandle>'+ f'<MD5OfBody>{m["MD5OfBody"]}</MD5OfBody>'+ f'<Body>{_esc(m["Body"])}</Body>')++ # System attributes → <Attribute>+ for ak, av in m.get("Attributes", {}).items():+ x += (f'<Attribute>'+ f'<Name>{_esc(ak)}</Name>'+ f'<Value>{_esc(str(av))}</Value>'+ f'</Attribute>')++ # User message attributes → <MessageAttribute>+ for ak, av in m.get("MessageAttributes", {}).items():+ x += (f'<MessageAttribute>'+ f'<Name>{_esc(ak)}</Name><Value>'+ f'<DataType>{_esc(av.get("DataType","String"))}</DataType>')+ if "StringValue" in av:+ x += f'<StringValue>{_esc(av["StringValue"])}</StringValue>'+ if "BinaryValue" in av:+ x += (f'<BinaryValue>'+ f'{_esc(str(av["BinaryValue"]))}'+ f'</BinaryValue>')+ x += '</Value></MessageAttribute>'++ if "MD5OfMessageAttributes" in m:+ x += (f'<MD5OfMessageAttributes>'+ f'{m["MD5OfMessageAttributes"]}'+ f'</MD5OfMessageAttributes>')++ x += '</Message>'+ parts.append(x)+ return "".join(parts)+++def _batch_result_xml(result: dict, entry_tag: str) -> str:+ inner = ""+ for e in result.get("Successful", []):+ inner += f'<{entry_tag}><Id>{_esc(e["Id"])}</Id></{entry_tag}>'+ inner += _batch_errors_xml(result.get("Failed", []))+ return inner+++def _batch_errors_xml(failed: list) -> str:+ x = ""+ for e in failed:+ x += (f'<BatchResultErrorEntry>'+ f'<Id>{_esc(e.get("Id",""))}</Id>'+ f'<Code>{_esc(e.get("Code",""))}</Code>'+ f'<Message>{_esc(e.get("Message",""))}</Message>'+ f'<SenderFault>{_sender_fault_str(e.get("SenderFault", True))}</SenderFault>'+ f'</BatchResultErrorEntry>')+ return x+++# ────────────────────────────────────────────────────────────+# QUERY-PARAM NORMALISATION (indexed form → flat dict)+# ────────────────────────────────────────────────────────────++def _normalise(action: str, params: dict) -> dict:+ """Convert indexed query params to the same dict shape the JSON API uses."""+ d: dict = {}++ # Scalar params+ for key in ("QueueName", "QueueUrl", "MessageBody", "ReceiptHandle",+ "VisibilityTimeout", "DelaySeconds", "WaitTimeSeconds",+ "MaxNumberOfMessages", "MaxResults", "QueueNamePrefix",+ "MessageGroupId", "MessageDeduplicationId",+ "ReceiveRequestAttemptId"):+ v = _p(params, key)+ if v:+ d[key] = v++ # Attribute.N.Name / .Value → Attributes dict+ attrs: dict = {}i = 1- while _p(params, f"SendMessageBatchRequestEntry.{i}.Id"):- entry_id = _p(params, f"SendMessageBatchRequestEntry.{i}.Id")- body_text = _p(params, f"SendMessageBatchRequestEntry.{i}.MessageBody")- delay = int(_p(params, f"SendMessageBatchRequestEntry.{i}.DelaySeconds") or "0")- msg_id = new_uuid()- md5 = hashlib.md5(body_text.encode()).hexdigest()-- queue["messages"].append({- "id": msg_id, "body": body_text, "md5": md5,- "receipt_handle": None, "sent_at": time.time(),- "visible_at": time.time() + delay, "receive_count": 0, "attributes": {},- })- results += f"""<SendMessageBatchResultEntry>- <Id>{entry_id}</Id><MessageId>{msg_id}</MessageId>- <MD5OfMessageBody>{md5}</MD5OfMessageBody>- </SendMessageBatchResultEntry>"""+ while _p(params, f"Attribute.{i}.Name"):+ attrs[_p(params, f"Attribute.{i}.Name")] = \+ _p(params, f"Attribute.{i}.Value")i += 1+ if attrs:+ d["Attributes"] = attrs- return _xml(200, "SendMessageBatchResponse", f"<SendMessageBatchResult>{results}</SendMessageBatchResult>")+ # AttributeName.N → AttributeNames list+ an: list = []+ i = 1+ while _p(params, f"AttributeName.{i}"):+ an.append(_p(params, f"AttributeName.{i}"))+ i += 1+ if an:+ d["AttributeNames"] = an+ # MessageAttributeName.N+ man: list = []+ i = 1+ while _p(params, f"MessageAttributeName.{i}"):+ man.append(_p(params, f"MessageAttributeName.{i}"))+ i += 1+ if man:+ d["MessageAttributeNames"] = man++ # MessageAttribute.N.Name / .Value.*+ ma: dict = {}+ i = 1+ while _p(params, f"MessageAttribute.{i}.Name"):+ nm = _p(params, f"MessageAttribute.{i}.Name")+ a: dict = {+ "DataType": _p(params,+ f"MessageAttribute.{i}.Value.DataType") or "String",+ }+ sv = _p(params, f"MessageAttribute.{i}.Value.StringValue")+ bv = _p(params, f"MessageAttribute.{i}.Value.BinaryValue")+ if sv:+ a["StringValue"] = sv+ if bv:+ a["BinaryValue"] = bv+ ma[nm] = a+ i += 1+ if ma:+ d["MessageAttributes"] = ma-def _delete_message_batch(params: dict, path: str):- url = _p(params, "QueueUrl") or _url_from_path(path)- queue = _queues.get(url)- if not queue:- return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)+ # Tag.N.Key / .Value+ tags: dict = {}+ i = 1+ while _p(params, f"Tag.{i}.Key"):+ tags[_p(params, f"Tag.{i}.Key")] = _p(params, f"Tag.{i}.Value")+ i += 1+ if tags:+ d["Tags"] = tags- results = ""+ # TagKey.N+ tk: list = []i = 1- while _p(params, f"DeleteMessageBatchRequestEntry.{i}.Id"):- entry_id = _p(params, f"DeleteMessageBatchRequestEntry.{i}.Id")- receipt = _p(params, f"DeleteMessageBatchRequestEntry.{i}.ReceiptHandle")- queue["messages"] = [m for m in queue["messages"] if m.get("receipt_handle") != receipt]- results += f"<DeleteMessageBatchResultEntry><Id>{entry_id}</Id></DeleteMessageBatchResultEntry>"+ while _p(params, f"TagKey.{i}"):+ tk.append(_p(params, f"TagKey.{i}"))i += 1+ if tk:+ d["TagKeys"] = tk- return _xml(200, "DeleteMessageBatchResponse", f"<DeleteMessageBatchResult>{results}</DeleteMessageBatchResult>")+ # ── Batch entries ───────────────────────────────────────+ if action == "SendMessageBatch":+ d["Entries"] = _parse_send_batch_entries(params)-# --- Helpers ---+ if action == "DeleteMessageBatch":+ entries: list = []+ i = 1+ pfx = "DeleteMessageBatchRequestEntry"+ while _p(params, f"{pfx}.{i}.Id"):+ entries.append({+ "Id": _p(params, f"{pfx}.{i}.Id"),+ "ReceiptHandle": _p(params, f"{pfx}.{i}.ReceiptHandle"),+ })+ i += 1+ d["Entries"] = entries++ if action == "ChangeMessageVisibilityBatch":+ entries = []+ i = 1+ pfx = "ChangeMessageVisibilityBatchRequestEntry"+ while _p(params, f"{pfx}.{i}.Id"):+ entries.append({+ "Id": _p(params, f"{pfx}.{i}.Id"),+ "ReceiptHandle": _p(params, f"{pfx}.{i}.ReceiptHandle"),+ "VisibilityTimeout":+ _p(params, f"{pfx}.{i}.VisibilityTimeout"),+ })+ i += 1+ d["Entries"] = entries++ return d+++def _parse_send_batch_entries(params: dict) -> list:+ entries: list = []+ i = 1+ pfx = "SendMessageBatchRequestEntry"+ while _p(params, f"{pfx}.{i}.Id"):+ e: dict = {+ "Id": _p(params, f"{pfx}.{i}.Id"),+ "MessageBody": _p(params, f"{pfx}.{i}.MessageBody"),+ }+ ds = _p(params, f"{pfx}.{i}.DelaySeconds")+ if ds:+ e["DelaySeconds"] = ds+ gid = _p(params, f"{pfx}.{i}.MessageGroupId")+ if gid:+ e["MessageGroupId"] = gid+ did = _p(params, f"{pfx}.{i}.MessageDeduplicationId")+ if did:+ e["MessageDeduplicationId"] = did++ # Per-entry message attributes+ ema: dict = {}+ j = 1+ while _p(params, f"{pfx}.{i}.MessageAttribute.{j}.Name"):+ anm = _p(params, f"{pfx}.{i}.MessageAttribute.{j}.Name")+ a: dict = {+ "DataType": _p(+ params,+ f"{pfx}.{i}.MessageAttribute.{j}.Value.DataType"+ ) or "String",+ }+ sv = _p(params,+ f"{pfx}.{i}.MessageAttribute.{j}.Value.StringValue")+ bv = _p(params,+ f"{pfx}.{i}.MessageAttribute.{j}.Value.BinaryValue")+ if sv:+ a["StringValue"] = sv+ if bv:+ a["BinaryValue"] = bv+ ema[anm] = a+ j += 1+ if ema:+ e["MessageAttributes"] = ema++ entries.append(e)+ i += 1+ return entries+++# ────────────────────────────────────────────────────────────+# LOW-LEVEL HELPERS+# ────────────────────────────────────────────────────────────def _p(params: dict, key: str, default: str = "") -> str:+ """Extract a scalar value from *params* which may hold strings or lists+ (``parse_qs`` returns lists)."""val = params.get(key, [default])if isinstance(val, list):return val[0] if val else default@@ -577,27 +1171,13 @@ def _p(params: dict, key: str, default: str = "") -> str:def _url_from_path(path: str) -> str:- """Extract queue URL from path like /000000000000/queue-name."""+ """Derive a queue URL from a request path like ``/000000000000/my-queue``."""parts = path.strip("/").split("/")if len(parts) >= 2:- name = parts[-1]- return _queue_url(name)+ return _queue_url(parts[-1])return ""-def _xml(status: int, root_tag: str, inner: str) -> tuple:- body = f"""<?xml version="1.0" encoding="UTF-8"?>-<{root_tag} xmlns="http://queue.amazonaws.com/doc/2012-11-05/">- {inner}- <ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>-</{root_tag}>""".encode("utf-8")- return status, {"Content-Type": "application/xml"}, body---def _error(code: str, message: str, status: int) -> tuple:- body = f"""<?xml version="1.0" encoding="UTF-8"?>-<ErrorResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/">- <Error><Code>{code}</Code><Message>{message}</Message></Error>- <RequestId>{new_uuid()}</RequestId>-</ErrorResponse>""".encode("utf-8")- return status, {"Content-Type": "application/xml"}, body+def reset():+ _queues.clear()+ _queue_name_to_url.clear()diff --git a/services/ssm.py b/services/ssm.pyindex a4597ce3..265fdf62 100644--- a/services/ssm.py+++ b/services/ssm.py@@ -2,12 +2,16 @@SSM Parameter Store Emulator.JSON-based API via X-Amz-Target (AmazonSSM).Supports: PutParameter, GetParameter, GetParameters, GetParametersByPath,- DeleteParameter, DeleteParameters, DescribeParameters.+ DeleteParameter, DeleteParameters, DescribeParameters,+ GetParameterHistory, LabelParameterVersion,+ AddTagsToResource, RemoveTagsFromResource, ListTagsForResource."""import jsonimport timeimport logging+import base64+from datetime import datetime, timezonefrom core.responses import json_response, error_response_json, new_uuid@@ -15,8 +19,34 @@ logger = logging.getLogger("ssm")ACCOUNT_ID = "000000000000"REGION = "us-east-1"+DEFAULT_PAGE_SIZE = 10-_parameters: dict = {} # name -> {Name, Value, Type, Version, ARN, LastModifiedDate, DataType}+_parameters: dict = {}+_parameter_history: dict = {}+_tags: dict = {}+++def _now_iso() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+++def _now_epoch() -> float:+ return datetime.now(timezone.utc).timestamp()+++def _param_arn(name: str) -> str:+ return f"arn:aws:ssm:{REGION}:{ACCOUNT_ID}:parameter{name}"+++def _encode_next_token(index: int) -> str:+ return base64.b64encode(str(index).encode()).decode()+++def _decode_next_token(token: str) -> int:+ try:+ return int(base64.b64decode(token).decode())+ except Exception:+ return 0async def handle_request(method, path, headers, body, query_params):@@ -37,6 +67,10 @@ async def handle_request(method, path, headers, body, query_params):"DeleteParameters": _delete_parameters,"DescribeParameters": _describe_parameters,"GetParameterHistory": _get_parameter_history,+ "LabelParameterVersion": _label_parameter_version,+ "AddTagsToResource": _add_tags_to_resource,+ "RemoveTagsFromResource": _remove_tags_from_resource,+ "ListTagsForResource": _list_tags_for_resource,}handler = handlers.get(action)@@ -50,24 +84,70 @@ def _put_parameter(data):if not name:return error_response_json("ValidationException", "Name is required", 400)+ param_type = data.get("Type", "String")+ value = data.get("Value", "")overwrite = data.get("Overwrite", False)+if name in _parameters and not overwrite:- return error_response_json("ParameterAlreadyExists", f"Parameter {name} already exists", 400)+ return error_response_json(+ "ParameterAlreadyExists",+ f"The parameter already exists. To overwrite this value, set the overwrite option in the request to true.",+ 400,+ )version = (_parameters[name]["Version"] + 1) if name in _parameters else 1- arn = f"arn:aws:ssm:{REGION}:{ACCOUNT_ID}:parameter{name}"- _parameters[name] = {+ arn = _param_arn(name)+ now = _now_epoch()++ stored_value = value+ if param_type == "SecureString":+ key_id = data.get("KeyId", "alias/aws/ssm")+ stored_value = f"ENCRYPTED:{base64.b64encode(value.encode()).decode()}"+ else:+ key_id = ""++ record = {"Name": name,- "Value": data.get("Value", ""),- "Type": data.get("Type", "String"),+ "Value": stored_value,+ "OriginalValue": value,+ "Type": param_type,+ "KeyId": key_id,"Version": version,"ARN": arn,- "LastModifiedDate": time.time(),+ "LastModifiedDate": now,"DataType": data.get("DataType", "text"),- "Description": data.get("Description", ""),+ "Description": data.get("Description", _parameters.get(name, {}).get("Description", "")),"Tier": data.get("Tier", "Standard"),+ "AllowedPattern": data.get("AllowedPattern", ""),+ "Policies": data.get("Policies", []),+ "Labels": [],+ }++ _parameters[name] = record++ history_entry = {+ "Name": name,+ "Value": stored_value,+ "OriginalValue": value,+ "Type": param_type,+ "KeyId": key_id,+ "Version": version,+ "LastModifiedDate": now,+ "LastModifiedUser": f"arn:aws:iam::{ACCOUNT_ID}:root",+ "Description": record["Description"],+ "AllowedPattern": record["AllowedPattern"],+ "Tier": record["Tier"],+ "Policies": record["Policies"],+ "DataType": record["DataType"],+ "Labels": [],}- return json_response({"Version": version, "Tier": "Standard"})++ if name not in _parameter_history:+ _parameter_history[name] = []+ _parameter_history[name].append(history_entry)++ logger.info(f"SSM PutParameter: {name} v{version} type={param_type}")+ return json_response({"Version": version, "Tier": record["Tier"]})def _get_parameter(data):@@ -75,17 +155,19 @@ def _get_parameter(data):param = _parameters.get(name)if not param:return error_response_json("ParameterNotFound", f"Parameter {name} not found", 400)- return json_response({"Parameter": _param_out(param)})+ with_decryption = data.get("WithDecryption", False)+ return json_response({"Parameter": _param_out(param, with_decryption)})def _get_parameters(data):names = data.get("Names", [])+ with_decryption = data.get("WithDecryption", False)params = []invalid = []for name in names:p = _parameters.get(name)if p:- params.append(_param_out(p))+ params.append(_param_out(p, with_decryption))else:invalid.append(name)return json_response({"Parameters": params, "InvalidParameters": invalid})@@ -94,18 +176,42 @@ def _get_parameters(data):def _get_parameters_by_path(data):path = data.get("Path", "/")recursive = data.get("Recursive", False)- results = []- for name, param in _parameters.items():- if recursive:- if name.startswith(path):- results.append(_param_out(param))+ with_decryption = data.get("WithDecryption", False)+ max_results = data.get("MaxResults", DEFAULT_PAGE_SIZE)+ next_token = data.get("NextToken")++ if not path.endswith("/"):+ path_prefix = path + "/"+ else:+ path_prefix = path++ all_results = []+ for name, param in sorted(_parameters.items()):+ if name == path:+ continue+ if not name.startswith(path_prefix) and not (name.startswith(path) and path == "/"):+ continue+ if path == "/":+ matches = True+ elif recursive:+ matches = Trueelse:- # Non-recursive: only direct children (no further slashes after path)- if name.startswith(path):- suffix = name[len(path):]- if "/" not in suffix.lstrip("/"):- results.append(_param_out(param))- return json_response({"Parameters": results})+ suffix = name[len(path_prefix):]+ matches = "/" not in suffix+ if matches:+ all_results.append(param)++ start = 0+ if next_token:+ start = _decode_next_token(next_token)++ page = all_results[start:start + max_results]+ out = [_param_out(p, with_decryption) for p in page]++ resp = {"Parameters": out}+ if start + max_results < len(all_results):+ resp["NextToken"] = _encode_next_token(start + max_results)+ return json_response(resp)def _delete_parameter(data):@@ -113,6 +219,9 @@ def _delete_parameter(data):if name not in _parameters:return error_response_json("ParameterNotFound", f"Parameter {name} not found", 400)del _parameters[name]+ _parameter_history.pop(name, None)+ arn = _param_arn(name)+ _tags.pop(arn, None)return json_response({})@@ -123,6 +232,8 @@ def _delete_parameters(data):for name in names:if name in _parameters:del _parameters[name]+ _parameter_history.pop(name, None)+ _tags.pop(_param_arn(name), None)deleted.append(name)else:invalid.append(name)@@ -131,34 +242,252 @@ def _delete_parameters(data):def _describe_parameters(data):filters = data.get("ParameterFilters", [])+ string_filters = data.get("Filters", [])+ max_results = data.get("MaxResults", DEFAULT_PAGE_SIZE)+ next_token = data.get("NextToken")++ candidates = list(_parameters.values())++ for f in filters:+ key = f.get("Key", "")+ option = f.get("Option", "Equals")+ values = f.get("Values", [])+ candidates = [p for p in candidates if _apply_filter(p, key, option, values)]++ for f in string_filters:+ key = f.get("Key", "")+ values = f.get("Values", [])+ if key == "Name" and values:+ candidates = [p for p in candidates if p["Name"] in values]+ elif key == "Type" and values:+ candidates = [p for p in candidates if p["Type"] in values]++ candidates.sort(key=lambda p: p["Name"])++ start = 0+ if next_token:+ start = _decode_next_token(next_token)++ page = candidates[start:start + max_results]results = []- for name, param in _parameters.items():- results.append({+ for param in page:+ desc = {"Name": param["Name"],"Type": param["Type"],"Version": param["Version"],"LastModifiedDate": param["LastModifiedDate"],+ "LastModifiedUser": f"arn:aws:iam::{ACCOUNT_ID}:root","ARN": param["ARN"],"DataType": param["DataType"],- })- return json_response({"Parameters": results})+ "Description": param.get("Description", ""),+ "Tier": param.get("Tier", "Standard"),+ "AllowedPattern": param.get("AllowedPattern", ""),+ }+ if param.get("Policies"):+ desc["Policies"] = param["Policies"]+ results.append(desc)++ resp = {"Parameters": results}+ if start + max_results < len(candidates):+ resp["NextToken"] = _encode_next_token(start + max_results)+ return json_response(resp)+++def _apply_filter(param, key, option, values):+ if not values:+ return True++ if key == "Name":+ target = param["Name"]+ if option == "Equals":+ return target in values+ elif option == "Contains":+ return any(v in target for v in values)+ elif option == "BeginsWith":+ return any(target.startswith(v) for v in values)+ elif key == "Type":+ return param["Type"] in values+ elif key == "KeyId":+ return param.get("KeyId", "") in values+ elif key == "Path":+ name = param["Name"]+ for v in values:+ prefix = v if v.endswith("/") else v + "/"+ if name.startswith(prefix):+ return True+ return False+ elif key == "DataType":+ return param.get("DataType", "text") in values+ elif key == "Tier":+ return param.get("Tier", "Standard") in values+ elif key == "Label":+ labels = param.get("Labels", [])+ return any(v in labels for v in values)++ return Truedef _get_parameter_history(data):name = data.get("Name")- param = _parameters.get(name)- if not param:+ if name not in _parameter_history:+ return error_response_json("ParameterNotFound", f"Parameter {name} not found", 400)++ with_decryption = data.get("WithDecryption", False)+ max_results = data.get("MaxResults", 50)+ next_token = data.get("NextToken")++ history = _parameter_history[name]++ start = 0+ if next_token:+ start = _decode_next_token(next_token)++ page = history[start:start + max_results]+ results = []+ for entry in page:+ out = {+ "Name": entry["Name"],+ "Type": entry["Type"],+ "Version": entry["Version"],+ "LastModifiedDate": entry["LastModifiedDate"],+ "LastModifiedUser": entry.get("LastModifiedUser", f"arn:aws:iam::{ACCOUNT_ID}:root"),+ "Description": entry.get("Description", ""),+ "DataType": entry.get("DataType", "text"),+ "Tier": entry.get("Tier", "Standard"),+ "Labels": entry.get("Labels", []),+ "Policies": entry.get("Policies", []),+ }+ if with_decryption or entry["Type"] != "SecureString":+ out["Value"] = entry.get("OriginalValue", entry["Value"])+ else:+ out["Value"] = entry["Value"]+ results.append(out)++ resp = {"Parameters": results}+ if start + max_results < len(history):+ resp["NextToken"] = _encode_next_token(start + max_results)+ return json_response(resp)+++def _label_parameter_version(data):+ name = data.get("Name")+ version = data.get("ParameterVersion")+ labels = data.get("Labels", [])++ if name not in _parameter_history:return error_response_json("ParameterNotFound", f"Parameter {name} not found", 400)- return json_response({"Parameters": [_param_out(param)]})+ history = _parameter_history[name]+ if version is None:+ version = _parameters[name]["Version"]++ target = None+ for entry in history:+ if entry["Version"] == version:+ target = entry+ break++ if target is None:+ return error_response_json(+ "ParameterVersionNotFound",+ f"Version {version} of parameter {name} not found",+ 400,+ )++ invalid_labels = []+ for label in labels:+ if len(label) > 100 or label.startswith("aws:") or label.startswith("ssm:"):+ invalid_labels.append(label)+ continue+ for entry in history:+ if label in entry.get("Labels", []) and entry["Version"] != version:+ entry["Labels"].remove(label)+ if label not in target.get("Labels", []):+ target.setdefault("Labels", []).append(label)++ if version == _parameters[name]["Version"]:+ _parameters[name]["Labels"] = target.get("Labels", [])++ return json_response({"InvalidLabels": invalid_labels, "ParameterVersion": version})+++def _add_tags_to_resource(data):+ resource_type = data.get("ResourceType", "Parameter")+ resource_id = data.get("ResourceId", "")+ new_tags = data.get("Tags", [])-def _param_out(param):- return {+ if resource_type == "Parameter":+ if not resource_id.startswith("/"):+ resource_id = "/" + resource_id+ arn = _param_arn(resource_id)+ else:+ arn = resource_id++ if arn not in _tags:+ _tags[arn] = {}+ for tag in new_tags:+ _tags[arn][tag["Key"]] = tag["Value"]++ return json_response({})+++def _remove_tags_from_resource(data):+ resource_type = data.get("ResourceType", "Parameter")+ resource_id = data.get("ResourceId", "")+ tag_keys = data.get("TagKeys", [])++ if resource_type == "Parameter":+ if not resource_id.startswith("/"):+ resource_id = "/" + resource_id+ arn = _param_arn(resource_id)+ else:+ arn = resource_id++ if arn in _tags:+ for key in tag_keys:+ _tags[arn].pop(key, None)++ return json_response({})+++def _list_tags_for_resource(data):+ resource_type = data.get("ResourceType", "Parameter")+ resource_id = data.get("ResourceId", "")++ if resource_type == "Parameter":+ if not resource_id.startswith("/"):+ resource_id = "/" + resource_id+ arn = _param_arn(resource_id)+ else:+ arn = resource_id++ tag_dict = _tags.get(arn, {})+ tag_list = [{"Key": k, "Value": v} for k, v in tag_dict.items()]++ return json_response({"TagList": tag_list})+++def _param_out(param, with_decryption=False):+ if with_decryption or param["Type"] != "SecureString":+ value = param.get("OriginalValue", param["Value"])+ else:+ value = param["Value"]++ out = {"Name": param["Name"],"Type": param["Type"],- "Value": param["Value"],+ "Value": value,"Version": param["Version"],"ARN": param["ARN"],"LastModifiedDate": param["LastModifiedDate"],- "DataType": param["DataType"],+ "DataType": param.get("DataType", "text"),}+ if param.get("Selector"):+ out["Selector"] = param["Selector"]+ return out+++def reset():+ _parameters.clear()+ _parameter_history.clear()+ _tags.clear()diff --git a/services/stepfunctions.py b/services/stepfunctions.pyindex ff09d330..74eaadf9 100644--- a/services/stepfunctions.py+++ b/services/stepfunctions.py@@ -1,27 +1,47 @@"""-Step Functions Service Emulator.+Step Functions Service Emulator with ASL execution engine.JSON-based API via X-Amz-Target (AWSStepFunctions).-Supports: CreateStateMachine, DeleteStateMachine, DescribeStateMachine, ListStateMachines,- StartExecution, StopExecution, DescribeExecution, ListExecutions,- GetExecutionHistory.-Executions are stored in-memory; no actual state machine logic is run.++Supports: CreateStateMachine, DeleteStateMachine, DescribeStateMachine,+ UpdateStateMachine, ListStateMachines,+ StartExecution, StartSyncExecution, StopExecution,+ DescribeExecution, DescribeStateMachineForExecution, ListExecutions,+ GetExecutionHistory,+ SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat,+ TagResource, UntagResource, ListTagsForResource.++ASL state types: Pass, Task, Choice, Wait, Succeed, Fail, Parallel, Map.+Task states invoke Lambda functions via services.lambda_svc when available.+Executions run in background threads and transition through RUNNING ->+SUCCEEDED / FAILED / TIMED_OUT / ABORTED."""+import copyimport json-import timeimport logging+import re+import threading+import time+from concurrent.futures import ThreadPoolExecutor, wait as futures_wait+from datetime import datetime, timezone-from core.responses import json_response, error_response_json, new_uuid+from core.responses import json_response, error_response_json, new_uuid, now_isologger = logging.getLogger("states")ACCOUNT_ID = "000000000000"REGION = "us-east-1"-_state_machines: dict = {} # arn -> state machine dict-_executions: dict = {} # arn -> execution dict+_state_machines: dict = {}+_executions: dict = {}+_task_tokens: dict = {}+_tags: dict = {}+# ---------------------------------------------------------------------------+# Entry point+# ---------------------------------------------------------------------------+async def handle_request(method, path, headers, body, query_params):target = headers.get("x-amz-target", "")action = target.split(".")[-1] if "." in target else ""@@ -42,6 +62,14 @@ async def handle_request(method, path, headers, body, query_params):"DescribeExecution": _describe_execution,"ListExecutions": _list_executions,"GetExecutionHistory": _get_execution_history,+ "SendTaskSuccess": _send_task_success,+ "SendTaskFailure": _send_task_failure,+ "SendTaskHeartbeat": _send_task_heartbeat,+ "TagResource": _tag_resource,+ "UntagResource": _untag_resource,+ "ListTagsForResource": _list_tags_for_resource,+ "StartSyncExecution": _start_sync_execution,+ "DescribeStateMachineForExecution": _describe_state_machine_for_execution,}handler = handlers.get(action)@@ -50,6 +78,10 @@ async def handle_request(method, path, headers, body, query_params):return handler(data)+# ---------------------------------------------------------------------------+# State machine CRUD+# ---------------------------------------------------------------------------+def _create_state_machine(data):name = data.get("name")if not name:@@ -57,27 +89,40 @@ def _create_state_machine(data):arn = f"arn:aws:states:{REGION}:{ACCOUNT_ID}:stateMachine:{name}"if arn in _state_machines:- return error_response_json("StateMachineAlreadyExists", f"State machine {name} already exists", 400)+ return error_response_json(+ "StateMachineAlreadyExists",+ f"State machine {name} already exists", 400)+ ts = now_iso()_state_machines[arn] = {"stateMachineArn": arn,"name": name,"definition": data.get("definition", "{}"),- "roleArn": data.get("roleArn", f"arn:aws:iam::{ACCOUNT_ID}:role/StepFunctionsRole"),+ "roleArn": data.get("roleArn",+ f"arn:aws:iam::{ACCOUNT_ID}:role/StepFunctionsRole"),"type": data.get("type", "STANDARD"),- "creationDate": time.time(),+ "creationDate": ts,"status": "ACTIVE",- "loggingConfiguration": data.get("loggingConfiguration", {"level": "OFF", "includeExecutionData": False}),- "tags": data.get("tags", []),+ "loggingConfiguration": data.get(+ "loggingConfiguration",+ {"level": "OFF", "includeExecutionData": False}),}- return json_response({"stateMachineArn": arn, "creationDate": time.time()})++ tags = data.get("tags", [])+ if tags:+ _tags[arn] = list(tags)++ return json_response({"stateMachineArn": arn, "creationDate": ts})def _delete_state_machine(data):arn = data.get("stateMachineArn")if arn not in _state_machines:- return error_response_json("StateMachineDoesNotExist", f"State machine {arn} not found", 400)+ return error_response_json(+ "StateMachineDoesNotExist",+ f"State machine {arn} not found", 400)del _state_machines[arn]+ _tags.pop(arn, None)return json_response({})@@ -85,7 +130,9 @@ def _describe_state_machine(data):arn = data.get("stateMachineArn")sm = _state_machines.get(arn)if not sm:- return error_response_json("StateMachineDoesNotExist", f"State machine {arn} not found", 400)+ return error_response_json(+ "StateMachineDoesNotExist",+ f"State machine {arn} not found", 400)return json_response(sm)@@ -93,12 +140,16 @@ def _update_state_machine(data):arn = data.get("stateMachineArn")sm = _state_machines.get(arn)if not sm:- return error_response_json("StateMachineDoesNotExist", f"State machine {arn} not found", 400)+ return error_response_json(+ "StateMachineDoesNotExist",+ f"State machine {arn} not found", 400)if "definition" in data:sm["definition"] = data["definition"]if "roleArn" in data:sm["roleArn"] = data["roleArn"]- return json_response({"updateDate": time.time()})+ if "loggingConfiguration" in data:+ sm["loggingConfiguration"] = data["loggingConfiguration"]+ return json_response({"updateDate": now_iso()})def _list_state_machines(data):@@ -110,58 +161,92 @@ def _list_state_machines(data):return json_response({"stateMachines": machines})+# ---------------------------------------------------------------------------+# Execution lifecycle+# ---------------------------------------------------------------------------+def _start_execution(data):sm_arn = data.get("stateMachineArn")if sm_arn not in _state_machines:- return error_response_json("StateMachineDoesNotExist", f"State machine {sm_arn} not found", 400)+ return error_response_json(+ "StateMachineDoesNotExist",+ f"State machine {sm_arn} not found", 400)+ sm = _state_machines[sm_arn]name = data.get("name") or new_uuid()- exec_arn = f"arn:aws:states:{REGION}:{ACCOUNT_ID}:execution:{_state_machines[sm_arn]['name']}:{name}"+ exec_arn = (f"arn:aws:states:{REGION}:{ACCOUNT_ID}"+ f":execution:{sm['name']}:{name}")++ start_date = now_iso()+ input_str = data.get("input", "{}")_executions[exec_arn] = {"executionArn": exec_arn,"stateMachineArn": sm_arn,"name": name,"status": "RUNNING",- "startDate": time.time(),+ "startDate": start_date,"stopDate": None,- "input": data.get("input", "{}"),+ "input": input_str,+ "inputDetails": {"included": True},"output": None,+ "outputDetails": {"included": True},"events": [- {"id": 1, "type": "ExecutionStarted", "timestamp": time.time(),- "executionStartedEventDetails": {"input": data.get("input", "{}")}},+ {"id": 1, "type": "ExecutionStarted", "timestamp": start_date,+ "executionStartedEventDetails": {+ "input": input_str, "roleArn": sm["roleArn"]}},],}++ threading.Thread(+ target=_run_execution, args=(exec_arn,), daemon=True).start()+logger.info(f"Step Functions execution started: {exec_arn}")- return json_response({"executionArn": exec_arn, "startDate": time.time()})+ return json_response({"executionArn": exec_arn, "startDate": start_date})def _stop_execution(data):exec_arn = data.get("executionArn")execution = _executions.get(exec_arn)if not execution:- return error_response_json("ExecutionDoesNotExist", f"Execution {exec_arn} not found", 400)+ return error_response_json(+ "ExecutionDoesNotExist",+ f"Execution {exec_arn} not found", 400)+ if execution["status"] != "RUNNING":+ return error_response_json(+ "ValidationException", "Execution is not running", 400)++ stop_date = now_iso()execution["status"] = "ABORTED"- execution["stopDate"] = time.time()- execution["events"].append({- "id": len(execution["events"]) + 1,- "type": "ExecutionAborted",- "timestamp": time.time(),+ execution["stopDate"] = stop_date+ _add_event(execution, "ExecutionAborted", {"executionAbortedEventDetails": {"error": data.get("error", ""),"cause": data.get("cause", ""),},})- return json_response({"stopDate": execution["stopDate"]})+ return json_response({"stopDate": stop_date})def _describe_execution(data):exec_arn = data.get("executionArn")execution = _executions.get(exec_arn)if not execution:- return error_response_json("ExecutionDoesNotExist", f"Execution {exec_arn} not found", 400)- result = dict(execution)- result.pop("events", None)+ return error_response_json(+ "ExecutionDoesNotExist",+ f"Execution {exec_arn} not found", 400)+ result = {+ "executionArn": execution["executionArn"],+ "stateMachineArn": execution["stateMachineArn"],+ "name": execution["name"],+ "status": execution["status"],+ "startDate": execution["startDate"],+ "stopDate": execution["stopDate"],+ "input": execution["input"],+ "inputDetails": execution.get("inputDetails", {"included": True}),+ "output": execution["output"],+ "outputDetails": execution.get("outputDetails", {"included": True}),+ }return json_response(result)@@ -169,7 +254,7 @@ def _list_executions(data):sm_arn = data.get("stateMachineArn")status_filter = data.get("statusFilter")execs = []- for exec_arn, ex in _executions.items():+ for ex in _executions.values():if sm_arn and ex["stateMachineArn"] != sm_arn:continueif status_filter and ex["status"] != status_filter:@@ -189,5 +274,954 @@ def _get_execution_history(data):exec_arn = data.get("executionArn")execution = _executions.get(exec_arn)if not execution:- return error_response_json("ExecutionDoesNotExist", f"Execution {exec_arn} not found", 400)- return json_response({"events": execution["events"]})+ return error_response_json(+ "ExecutionDoesNotExist",+ f"Execution {exec_arn} not found", 400)+ events = list(execution["events"])+ if data.get("reverseOrder", False):+ events = list(reversed(events))+ max_results = data.get("maxResults", 1000)+ return json_response({"events": events[:max_results]})+++def _start_sync_execution(data):+ sm_arn = data.get("stateMachineArn")+ if sm_arn not in _state_machines:+ return error_response_json(+ "StateMachineDoesNotExist",+ f"State machine {sm_arn} not found", 400)++ sm = _state_machines[sm_arn]+ name = data.get("name") or new_uuid()+ exec_arn = (f"arn:aws:states:{REGION}:{ACCOUNT_ID}"+ f":execution:{sm['name']}:{name}")++ start_date = now_iso()+ input_str = data.get("input", "{}")++ _executions[exec_arn] = {+ "executionArn": exec_arn,+ "stateMachineArn": sm_arn,+ "name": name,+ "status": "RUNNING",+ "startDate": start_date,+ "stopDate": None,+ "input": input_str,+ "inputDetails": {"included": True},+ "output": None,+ "outputDetails": {"included": True},+ "events": [+ {"id": 1, "type": "ExecutionStarted", "timestamp": start_date,+ "executionStartedEventDetails": {+ "input": input_str, "roleArn": sm["roleArn"]}},+ ],+ }++ _run_execution(exec_arn)++ execution = _executions[exec_arn]+ return json_response({+ "executionArn": exec_arn,+ "stateMachineArn": sm_arn,+ "name": name,+ "startDate": start_date,+ "stopDate": execution.get("stopDate") or now_iso(),+ "status": execution["status"],+ "input": input_str,+ "inputDetails": {"included": True},+ "output": execution.get("output") or "{}",+ "outputDetails": {"included": True},+ })+++def _describe_state_machine_for_execution(data):+ exec_arn = data.get("executionArn")+ execution = _executions.get(exec_arn)+ if not execution:+ return error_response_json(+ "ExecutionDoesNotExist",+ f"Execution {exec_arn} not found", 400)++ sm_arn = execution["stateMachineArn"]+ sm = _state_machines.get(sm_arn)+ if not sm:+ return error_response_json(+ "StateMachineDoesNotExist",+ f"State machine {sm_arn} not found", 400)++ return json_response({+ "stateMachineArn": sm["stateMachineArn"],+ "name": sm["name"],+ "definition": sm["definition"],+ "roleArn": sm["roleArn"],+ "updateDate": sm.get("creationDate", now_iso()),+ })+++# ---------------------------------------------------------------------------+# Callback pattern — SendTask*+# ---------------------------------------------------------------------------++def _send_task_success(data):+ token = data.get("taskToken")+ output = data.get("output", "{}")+ info = _task_tokens.get(token)+ if not info:+ return error_response_json(+ "TaskDoesNotExist", f"Task token not found", 400)+ info["result"] = output+ info["event"].set()+ return json_response({})+++def _send_task_failure(data):+ token = data.get("taskToken")+ info = _task_tokens.get(token)+ if not info:+ return error_response_json(+ "TaskDoesNotExist", f"Task token not found", 400)+ info["error"] = {+ "Error": data.get("error", "TaskFailed"),+ "Cause": data.get("cause", ""),+ }+ info["event"].set()+ return json_response({})+++def _send_task_heartbeat(data):+ token = data.get("taskToken")+ info = _task_tokens.get(token)+ if not info:+ return error_response_json(+ "TaskDoesNotExist", f"Task token not found", 400)+ info["heartbeat"] = now_iso()+ return json_response({})+++# ---------------------------------------------------------------------------+# Tagging+# ---------------------------------------------------------------------------++def _tag_resource(data):+ arn = data.get("resourceArn")+ new_tags = data.get("tags", [])+ existing = _tags.setdefault(arn, [])+ existing_map = {t["key"]: i for i, t in enumerate(existing)}+ for tag in new_tags:+ idx = existing_map.get(tag["key"])+ if idx is not None:+ existing[idx] = tag+ else:+ existing.append(tag)+ existing_map[tag["key"]] = len(existing) - 1+ return json_response({})+++def _untag_resource(data):+ arn = data.get("resourceArn")+ keys_to_remove = set(data.get("tagKeys", []))+ existing = _tags.get(arn, [])+ _tags[arn] = [t for t in existing if t["key"] not in keys_to_remove]+ return json_response({})+++def _list_tags_for_resource(data):+ arn = data.get("resourceArn")+ return json_response({"tags": _tags.get(arn, [])})+++# ---------------------------------------------------------------------------+# Event helper+# ---------------------------------------------------------------------------++def _add_event(execution, event_type, details=None):+ event = {+ "id": len(execution["events"]) + 1,+ "type": event_type,+ "timestamp": now_iso(),+ }+ if details:+ event.update(details)+ execution["events"].append(event)+ return event+++# ===================================================================+# ASL Execution Engine+# ===================================================================++class _ExecutionError(Exception):+ def __init__(self, error, cause):+ self.error = error+ self.cause = cause+ super().__init__(f"{error}: {cause}")+++def _run_execution(exec_arn):+ """Background thread: walk the ASL definition to completion."""+ execution = _executions.get(exec_arn)+ if not execution:+ return++ time.sleep(0.15)++ sm = _state_machines.get(execution["stateMachineArn"])+ if not sm:+ _fail_execution(execution, "StateMachineDeleted",+ "State machine no longer exists")+ return++ try:+ definition = json.loads(sm["definition"])+ except json.JSONDecodeError:+ _fail_execution(execution, "InvalidDefinition",+ "Could not parse state machine definition")+ return++ all_states = definition.get("States", {})+ current_name = definition.get("StartAt")+ if not current_name or current_name not in all_states:+ _fail_execution(execution, "InvalidDefinition",+ f"StartAt state '{current_name}' not found")+ return++ try:+ current_input = json.loads(execution["input"])+ except json.JSONDecodeError:+ current_input = {}++ ctx = {+ "Execution": {+ "Id": exec_arn,+ "Input": current_input,+ "Name": execution["name"],+ "StartTime": execution["startDate"],+ },+ "StateMachine": {+ "Id": execution["stateMachineArn"],+ "Name": sm["name"],+ },+ }++ try:+ while current_name and execution["status"] == "RUNNING":+ state_def = all_states.get(current_name)+ if not state_def:+ raise _ExecutionError(+ "States.Runtime",+ f"State '{current_name}' not found in definition")++ ctx["State"] = {"Name": current_name, "EnteredTime": now_iso()}+ state_type = state_def.get("Type")++ _add_event(execution, f"{state_type}StateEntered", {+ "stateEnteredEventDetails": {+ "name": current_name,+ "input": json.dumps(current_input),+ },+ })++ if state_type == "Succeed":+ current_input = _apply_input_path(state_def, current_input)+ current_input = _apply_output_path(state_def, current_input)+ _add_event(execution, "SucceedStateExited", {+ "stateExitedEventDetails": {+ "name": current_name,+ "output": json.dumps(current_input),+ },+ })+ current_name = None+ continue++ if state_type == "Fail":+ raise _ExecutionError(+ state_def.get("Error", "States.Fail"),+ state_def.get("Cause", ""))++ handler_fn = {+ "Pass": _execute_pass,+ "Task": _execute_task,+ "Choice": _execute_choice,+ "Wait": _execute_wait,+ "Parallel": _execute_parallel,+ "Map": _execute_map,+ }.get(state_type)++ if not handler_fn:+ raise _ExecutionError(+ "States.Runtime", f"Unknown state type: {state_type}")++ if state_type in ("Task", "Parallel", "Map"):+ current_input, next_name = handler_fn(+ state_def, current_input, execution, ctx)+ else:+ current_input, next_name = handler_fn(+ state_def, current_input)++ _add_event(execution, f"{state_type}StateExited", {+ "stateExitedEventDetails": {+ "name": current_name,+ "output": json.dumps(current_input),+ },+ })+ current_name = next_name++ if execution["status"] == "RUNNING":+ output_json = json.dumps(current_input)+ execution["status"] = "SUCCEEDED"+ execution["output"] = output_json+ execution["stopDate"] = now_iso()+ _add_event(execution, "ExecutionSucceeded", {+ "executionSucceededEventDetails": {"output": output_json},+ })++ except _ExecutionError as err:+ _fail_execution(execution, err.error, err.cause)+ except Exception as exc:+ logger.exception(f"Unexpected error in execution {exec_arn}")+ _fail_execution(execution, "States.Runtime", str(exc))+++def _fail_execution(execution, error, cause):+ execution["status"] = "FAILED"+ execution["output"] = json.dumps({"Error": error, "Cause": cause})+ execution["stopDate"] = now_iso()+ _add_event(execution, "ExecutionFailed", {+ "executionFailedEventDetails": {"error": error, "cause": cause},+ })+++# ---------------------------------------------------------------------------+# Pass state+# ---------------------------------------------------------------------------++def _execute_pass(state_def, raw_input):+ effective = _apply_input_path(state_def, raw_input)+ effective = _apply_parameters(state_def, effective)++ result = state_def.get("Result", effective)+ result = _apply_result_selector(state_def, result)+ output = _apply_result_path(state_def, raw_input, result)+ output = _apply_output_path(state_def, output)+ return output, _next_or_end(state_def)+++# ---------------------------------------------------------------------------+# Task state (with Retry / Catch)+# ---------------------------------------------------------------------------++def _execute_task(state_def, raw_input, execution, ctx):+ resource = state_def.get("Resource", "")+ is_callback = ".waitForTaskToken" in resource++ if is_callback:+ ctx["Task"] = {"Token": new_uuid()}++ effective = _apply_input_path(state_def, raw_input)+ effective = _apply_parameters(state_def, effective, ctx)++ retriers = state_def.get("Retry", [])+ catchers = state_def.get("Catch", [])+ retry_counts: dict = {}+ last_error: _ExecutionError | None = None++ while True:+ try:+ _add_event(execution, "TaskScheduled", {+ "taskScheduledEventDetails": {+ "resourceType": "lambda" if "lambda" in resource else "states",+ "resource": resource,+ },+ })++ if is_callback:+ task_result = _invoke_with_callback(+ resource, effective, ctx["Task"]["Token"], state_def)+ else:+ task_result = _invoke_resource(resource, effective)++ _add_event(execution, "TaskSucceeded", {+ "taskSucceededEventDetails": {+ "output": json.dumps(task_result),+ "resource": resource,+ },+ })++ result = _apply_result_selector(state_def, task_result)+ output = _apply_result_path(state_def, raw_input, result)+ output = _apply_output_path(state_def, output)+ return output, _next_or_end(state_def)++ except _ExecutionError as err:+ last_error = err+ _add_event(execution, "TaskFailed", {+ "taskFailedEventDetails": {+ "error": err.error, "cause": err.cause,+ "resource": resource,+ },+ })++ retrier, retrier_idx = _find_matching_retrier(+ retriers, err.error, retry_counts)+ if retrier is not None:+ count = retry_counts.get(retrier_idx, 0)+ interval = retrier.get("IntervalSeconds", 1)+ backoff = retrier.get("BackoffRate", 2.0)+ sleep_sec = interval * (backoff ** count)+ time.sleep(min(sleep_sec, 60))+ retry_counts[retrier_idx] = count + 1+ continue+ break++ if last_error:+ catcher = _find_matching_catcher(catchers, last_error.error)+ if catcher:+ error_output = {"Error": last_error.error, "Cause": last_error.cause}+ output = _apply_result_path_raw(+ catcher.get("ResultPath", "$"), raw_input, error_output)+ return output, catcher["Next"]+ raise last_error++ raise _ExecutionError("States.Runtime", "Task failed with no error captured")+++def _invoke_resource(resource, input_data):+ """Dispatch to Lambda or return a mock/passthrough."""+ if "states:::lambda:invoke" in resource:+ func_name = input_data.get("FunctionName", "")+ payload = input_data.get("Payload", input_data)+ if ":function:" in func_name:+ func_name = func_name.split(":function:")[-1].split(":")[0]+ result = _call_lambda(func_name, payload)+ return {"StatusCode": 200, "Payload": result}++ func_name = _extract_lambda_name(resource)+ if func_name:+ return _call_lambda(func_name, input_data)++ return input_data+++def _invoke_with_callback(resource, input_data, token, state_def):+ """waitForTaskToken pattern: invoke then block until callback."""+ evt = threading.Event()+ _task_tokens[token] = {+ "event": evt, "result": None, "error": None, "heartbeat": None}++ clean_resource = resource.replace(".waitForTaskToken", "")+ func_name = _extract_lambda_name(clean_resource)+ if not func_name and "states:::lambda:invoke" in clean_resource:+ func_name = input_data.get("FunctionName", "")+ if ":function:" in func_name:+ func_name = func_name.split(":function:")[-1].split(":")[0]++ if func_name:+ try:+ _call_lambda(func_name, input_data)+ except _ExecutionError:+ pass++ timeout = state_def.get("TimeoutSeconds", 99999)+ if not evt.wait(timeout=timeout):+ _task_tokens.pop(token, None)+ raise _ExecutionError("States.Timeout",+ "Task timed out waiting for callback")++ info = _task_tokens.pop(token, {})+ if info.get("error"):+ e = info["error"]+ raise _ExecutionError(e.get("Error", "TaskFailed"),+ e.get("Cause", ""))+ result_raw = info.get("result", "{}")+ try:+ return json.loads(result_raw) if isinstance(result_raw, str) else result_raw+ except json.JSONDecodeError:+ return result_raw+++def _call_lambda(func_name, event):+ """Invoke a Lambda via the co-located lambda_svc module."""+ try:+ from services import lambda_svc+ except ImportError:+ logger.warning("lambda_svc unavailable; returning passthrough for %s", func_name)+ return event++ status, headers, body = lambda_svc._invoke(func_name, event, {})++ if headers.get("X-Amz-Function-Error"):+ try:+ err = json.loads(body)+ raise _ExecutionError(+ err.get("errorType", "Lambda.Unknown"),+ err.get("errorMessage", body.decode("utf-8", errors="replace")+ if isinstance(body, bytes) else str(body)))+ except (json.JSONDecodeError, UnicodeDecodeError):+ raise _ExecutionError(+ "Lambda.Unknown",+ body.decode("utf-8", errors="replace")+ if isinstance(body, bytes) else str(body))++ try:+ return json.loads(body) if body else {}+ except (json.JSONDecodeError, UnicodeDecodeError):+ return body.decode("utf-8", errors="replace") if isinstance(body, bytes) else body+++# ---------------------------------------------------------------------------+# Choice state+# ---------------------------------------------------------------------------++def _execute_choice(state_def, raw_input):+ effective = _apply_input_path(state_def, raw_input)++ for choice in state_def.get("Choices", []):+ if _evaluate_rule(choice, effective):+ return _apply_output_path(state_def, effective), choice["Next"]++ default = state_def.get("Default")+ if default:+ return _apply_output_path(state_def, effective), default++ raise _ExecutionError("States.NoChoiceMatched",+ "No choice rule matched and no Default")+++def _evaluate_rule(rule, data):+ if "And" in rule:+ return all(_evaluate_rule(r, data) for r in rule["And"])+ if "Or" in rule:+ return any(_evaluate_rule(r, data) for r in rule["Or"])+ if "Not" in rule:+ return not _evaluate_rule(rule["Not"], data)++ variable = rule.get("Variable")+ if not variable:+ return False+ value = _resolve_path(variable, data)++ # --- type checks ---+ if "IsPresent" in rule:+ return (value is not None) == rule["IsPresent"]+ if "IsNull" in rule:+ return (value is None) == rule["IsNull"]+ if "IsNumeric" in rule:+ return isinstance(value, (int, float)) == rule["IsNumeric"]+ if "IsString" in rule:+ return isinstance(value, str) == rule["IsString"]+ if "IsBoolean" in rule:+ return isinstance(value, bool) == rule["IsBoolean"]+ if "IsTimestamp" in rule:+ return _is_timestamp(value) == rule["IsTimestamp"]++ # --- string ---+ if "StringEquals" in rule:+ return value == rule["StringEquals"]+ if "StringEqualsPath" in rule:+ return value == _resolve_path(rule["StringEqualsPath"], data)+ if "StringLessThan" in rule:+ return isinstance(value, str) and value < rule["StringLessThan"]+ if "StringGreaterThan" in rule:+ return isinstance(value, str) and value > rule["StringGreaterThan"]+ if "StringLessThanEquals" in rule:+ return isinstance(value, str) and value <= rule["StringLessThanEquals"]+ if "StringGreaterThanEquals" in rule:+ return isinstance(value, str) and value >= rule["StringGreaterThanEquals"]+ if "StringMatches" in rule:+ pattern = re.escape(rule["StringMatches"]).replace(r"\*", ".*")+ return isinstance(value, str) and bool(re.fullmatch(pattern, value))++ # --- numeric ---+ if "NumericEquals" in rule:+ return _is_num(value) and value == rule["NumericEquals"]+ if "NumericEqualsPath" in rule:+ return _is_num(value) and value == _resolve_path(rule["NumericEqualsPath"], data)+ if "NumericLessThan" in rule:+ return _is_num(value) and value < rule["NumericLessThan"]+ if "NumericGreaterThan" in rule:+ return _is_num(value) and value > rule["NumericGreaterThan"]+ if "NumericLessThanEquals" in rule:+ return _is_num(value) and value <= rule["NumericLessThanEquals"]+ if "NumericGreaterThanEquals" in rule:+ return _is_num(value) and value >= rule["NumericGreaterThanEquals"]++ # --- boolean ---+ if "BooleanEquals" in rule:+ return value is rule["BooleanEquals"] or value == rule["BooleanEquals"]+ if "BooleanEqualsPath" in rule:+ return value == _resolve_path(rule["BooleanEqualsPath"], data)++ # --- timestamp ---+ for op, cmp_fn in [("TimestampEquals", lambda a, b: a == b),+ ("TimestampLessThan", lambda a, b: a < b),+ ("TimestampGreaterThan", lambda a, b: a > b),+ ("TimestampLessThanEquals", lambda a, b: a <= b),+ ("TimestampGreaterThanEquals", lambda a, b: a >= b)]:+ if op in rule:+ a, b = _parse_ts(value), _parse_ts(rule[op])+ return a is not None and b is not None and cmp_fn(a, b)++ return False+++# ---------------------------------------------------------------------------+# Wait state+# ---------------------------------------------------------------------------++def _execute_wait(state_def, raw_input):+ effective = _apply_input_path(state_def, raw_input)++ if "Seconds" in state_def:+ time.sleep(state_def["Seconds"])+ elif "Timestamp" in state_def:+ _sleep_until(state_def["Timestamp"])+ elif "SecondsPath" in state_def:+ secs = _resolve_path(state_def["SecondsPath"], effective)+ if isinstance(secs, (int, float)) and secs > 0:+ time.sleep(secs)+ elif "TimestampPath" in state_def:+ ts_str = _resolve_path(state_def["TimestampPath"], effective)+ if isinstance(ts_str, str):+ _sleep_until(ts_str)++ output = _apply_output_path(state_def, effective)+ return output, _next_or_end(state_def)+++def _sleep_until(iso_ts):+ try:+ target = datetime.fromisoformat(iso_ts.replace("Z", "+00:00"))+ delta = (target - datetime.now(timezone.utc)).total_seconds()+ if delta > 0:+ time.sleep(delta)+ except (ValueError, TypeError):+ pass+++# ---------------------------------------------------------------------------+# Parallel state+# ---------------------------------------------------------------------------++def _execute_parallel(state_def, raw_input, execution, ctx):+ effective = _apply_input_path(state_def, raw_input)+ effective = _apply_parameters(state_def, effective, ctx)++ branches = state_def.get("Branches", [])+ results = [None] * len(branches)+ errors = [None] * len(branches)++ def run_branch(idx, branch):+ try:+ results[idx] = _run_sub_machine(+ branch.get("States", {}),+ branch.get("StartAt"),+ effective, execution, ctx)+ except Exception as exc:+ errors[idx] = exc++ threads = [threading.Thread(target=run_branch, args=(i, b), daemon=True)+ for i, b in enumerate(branches)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()++ for err in errors:+ if err is not None:+ raise err if isinstance(err, _ExecutionError) else _ExecutionError(+ "States.BranchFailed", str(err))++ result = _apply_result_selector(state_def, results)+ output = _apply_result_path(state_def, raw_input, result)+ output = _apply_output_path(state_def, output)+ return output, _next_or_end(state_def)+++# ---------------------------------------------------------------------------+# Map state+# ---------------------------------------------------------------------------++def _execute_map(state_def, raw_input, execution, ctx):+ effective = _apply_input_path(state_def, raw_input)+ effective = _apply_parameters(state_def, effective, ctx)++ items_path = state_def.get("ItemsPath", "$")+ items = _resolve_path(items_path, effective)+ if not isinstance(items, list):+ items = [items]++ iterator = state_def.get("Iterator") or state_def.get("ItemProcessor", {})+ iter_states = iterator.get("States", {})+ iter_start = iterator.get("StartAt")+ max_conc = state_def.get("MaxConcurrency", 0)++ results = [None] * len(items)+ errors = [None] * len(items)++ def run_item(idx, item):+ try:+ item_ctx = copy.deepcopy(ctx)+ item_ctx["Map"] = {"Item": {"Index": idx, "Value": item}}+ item_params = state_def.get("ItemSelector") or state_def.get("Parameters")+ item_input = (_resolve_params_obj(item_params, item, item_ctx)+ if item_params else item)+ results[idx] = _run_sub_machine(+ iter_states, iter_start, item_input, execution, item_ctx)+ except Exception as exc:+ errors[idx] = exc++ workers = max_conc if max_conc > 0 else (len(items) or 1)+ with ThreadPoolExecutor(max_workers=workers) as pool:+ futs = [pool.submit(run_item, i, item) for i, item in enumerate(items)]+ futures_wait(futs)++ for err in errors:+ if err is not None:+ raise err if isinstance(err, _ExecutionError) else _ExecutionError(+ "States.MapFailed", str(err))++ result = _apply_result_selector(state_def, results)+ output = _apply_result_path(state_def, raw_input, result)+ output = _apply_output_path(state_def, output)+ return output, _next_or_end(state_def)+++# ---------------------------------------------------------------------------+# Sub-machine runner (Parallel branches / Map iterations)+# ---------------------------------------------------------------------------++def _run_sub_machine(states, start_at, input_data, execution, ctx):+ current_name = start_at+ current_input = copy.deepcopy(input_data)++ while current_name:+ state_def = states.get(current_name)+ if not state_def:+ raise _ExecutionError(+ "States.Runtime", f"State '{current_name}' not found")++ state_type = state_def.get("Type")+ ctx["State"] = {"Name": current_name, "EnteredTime": now_iso()}++ if state_type == "Succeed":+ return _apply_output_path(state_def,+ _apply_input_path(state_def, current_input))+ if state_type == "Fail":+ raise _ExecutionError(+ state_def.get("Error", "States.Fail"),+ state_def.get("Cause", ""))++ handler_fn = {+ "Pass": _execute_pass,+ "Task": _execute_task,+ "Choice": _execute_choice,+ "Wait": _execute_wait,+ "Parallel": _execute_parallel,+ "Map": _execute_map,+ }.get(state_type)++ if not handler_fn:+ raise _ExecutionError(+ "States.Runtime", f"Unknown state type: {state_type}")++ if state_type in ("Task", "Parallel", "Map"):+ current_input, current_name = handler_fn(+ state_def, current_input, execution, ctx)+ else:+ current_input, current_name = handler_fn(+ state_def, current_input)++ return current_input+++# ===================================================================+# Path / Parameter processing+# ===================================================================++def _apply_input_path(state_def, data):+ ip = state_def.get("InputPath", "$")+ if ip is None:+ return {}+ return _resolve_path(ip, data)+++def _apply_output_path(state_def, data):+ op = state_def.get("OutputPath", "$")+ if op is None:+ return {}+ return _resolve_path(op, data)+++def _apply_parameters(state_def, data, ctx=None):+ params = state_def.get("Parameters")+ if not params:+ return data+ return _resolve_params_obj(params, data, ctx)+++def _apply_result_selector(state_def, data):+ sel = state_def.get("ResultSelector")+ if not sel:+ return data+ return _resolve_params_obj(sel, data)+++def _apply_result_path(state_def, original, result):+ return _apply_result_path_raw(+ state_def.get("ResultPath", "$"), original, result)+++def _apply_result_path_raw(result_path, original, result):+ if result_path is None:+ return copy.deepcopy(original)+ if result_path == "$":+ return result++ output = copy.deepcopy(original) if isinstance(original, dict) else {}+ parts = result_path.lstrip("$.").split(".")+ cur = output+ for p in parts[:-1]:+ if p not in cur or not isinstance(cur.get(p), dict):+ cur[p] = {}+ cur = cur[p]+ cur[parts[-1]] = result+ return output+++def _resolve_path(path, data):+ if path == "$" or not path:+ return data+ if not path.startswith("$"):+ return data++ parts = path[2:].split(".") if path.startswith("$.") else []+ cur = data+ for part in parts:+ if not part:+ continue+ m = re.match(r"(\w+)\[(\d+)]", part)+ if m:+ field, idx = m.group(1), int(m.group(2))+ if isinstance(cur, dict) and field in cur:+ cur = cur[field]+ if isinstance(cur, list) and idx < len(cur):+ cur = cur[idx]+ else:+ return None+ else:+ return None+ elif isinstance(cur, dict) and part in cur:+ cur = cur[part]+ else:+ return None+ return cur+++def _resolve_params_obj(template, data, ctx=None):+ if not isinstance(template, dict):+ return template+ result = {}+ for key, value in template.items():+ if key.endswith(".$"):+ real_key = key[:-2]+ if isinstance(value, str):+ if value.startswith("$$."):+ result[real_key] = _resolve_ctx_path(value, ctx or {})+ else:+ result[real_key] = _resolve_path(value, data)+ else:+ result[real_key] = value+ elif isinstance(value, dict):+ result[key] = _resolve_params_obj(value, data, ctx)+ elif isinstance(value, list):+ result[key] = [+ _resolve_params_obj(v, data, ctx) if isinstance(v, dict) else v+ for v in value+ ]+ else:+ result[key] = value+ return result+++def _resolve_ctx_path(path, ctx):+ if not path.startswith("$$."):+ return None+ parts = path[3:].split(".")+ cur = ctx+ for p in parts:+ if isinstance(cur, dict) and p in cur:+ cur = cur[p]+ else:+ return None+ return cur+++# ===================================================================+# Retry / Catch helpers+# ===================================================================++def _find_matching_retrier(retriers, error, retry_counts):+ for idx, retrier in enumerate(retriers):+ equals = retrier.get("ErrorEquals", [])+ max_attempts = retrier.get("MaxAttempts", 3)+ if retry_counts.get(idx, 0) >= max_attempts:+ continue+ if "States.ALL" in equals or error in equals:+ return retrier, idx+ return None, -1+++def _find_matching_catcher(catchers, error):+ for catcher in catchers:+ equals = catcher.get("ErrorEquals", [])+ if "States.ALL" in equals or error in equals:+ return catcher+ return None+++# ===================================================================+# Misc helpers+# ===================================================================++def _extract_lambda_name(resource):+ if not resource:+ return None+ if ":function:" in resource:+ return resource.split(":function:")[-1].split(":")[0]+ return None+++def _next_or_end(state_def):+ if state_def.get("End"):+ return None+ return state_def.get("Next")+++def _is_num(v):+ return isinstance(v, (int, float)) and not isinstance(v, bool)+++def _is_timestamp(v):+ if not isinstance(v, str):+ return False+ try:+ datetime.fromisoformat(v.replace("Z", "+00:00"))+ return True+ except (ValueError, TypeError):+ return False+++def _parse_ts(v):+ if isinstance(v, str):+ try:+ return datetime.fromisoformat(v.replace("Z", "+00:00"))+ except (ValueError, TypeError):+ pass+ return None+++def reset():+ _state_machines.clear()+ _executions.clear()+ _task_tokens.clear()+ _tags.clear()diff --git a/tests/conftest.py b/tests/conftest.pyindex baaaffe2..02956bb2 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -2,6 +2,7 @@Pytest fixtures for MiniStack integration tests."""import os+import urllib.requestimport pytestimport boto3from botocore.config import Config@@ -22,6 +23,20 @@ def make_client(service):return boto3.client(service, **_kwargs)[email protected](scope="session", autouse=True)+def reset_server():+ """Reset all server state once before the test session starts."""+ req = urllib.request.Request(+ f"{ENDPOINT}/_ministack/reset",+ data=b"",+ method="POST",+ )+ try:+ urllib.request.urlopen(req, timeout=5)+ except Exception:+ pass # server may not be up yet; individual tests will fail naturally++@pytest.fixture(scope="session")def s3():return make_client("s3")@@ -101,3 +116,24 @@ def glue():@pytest.fixture(scope="session")def athena():return make_client("athena")+[email protected](scope="session")+def apigw():+ return make_client("apigatewayv2")+[email protected](scope="session")+def sfn_sync():+ """SFN client for StartSyncExecution — forces same endpoint (boto3 normally prefixes sync-)."""+ from botocore.config import Config as BotoConfig+ return boto3.client(+ "stepfunctions",+ endpoint_url=ENDPOINT,+ aws_access_key_id="test",+ aws_secret_access_key="test",+ region_name=REGION,+ config=BotoConfig(+ region_name=REGION,+ retries={"max_attempts": 0},+ inject_host_prefix=False,+ ),+ )diff --git a/tests/test_services.py b/tests/test_services.pyindex 81b8fea4..ede8ec57 100644--- a/tests/test_services.py+++ b/tests/test_services.py@@ -9,135 +9,784 @@ import jsonimport timeimport zipfile+import pytest+from botocore.exceptions import ClientError+# ========== S3 ==========+def test_s3_create_bucket(s3):- s3.create_bucket(Bucket="test-bucket-1")+ s3.create_bucket(Bucket="intg-s3-create")buckets = s3.list_buckets()["Buckets"]- assert any(b["Name"] == "test-bucket-1" for b in buckets)+ assert any(b["Name"] == "intg-s3-create" for b in buckets)-def test_s3_put_get(s3):- s3.create_bucket(Bucket="test-bucket-2")- s3.put_object(Bucket="test-bucket-2", Key="hello.txt", Body=b"Hello, MiniStack!")- resp = s3.get_object(Bucket="test-bucket-2", Key="hello.txt")- assert resp["Body"].read() == b"Hello, MiniStack!"+def test_s3_create_bucket_already_exists(s3):+ s3.create_bucket(Bucket="intg-s3-dup")+ with pytest.raises(ClientError) as exc:+ s3.create_bucket(Bucket="intg-s3-dup")+ assert exc.value.response["Error"]["Code"] == "BucketAlreadyOwnedByYou"-def test_s3_list(s3):- s3.create_bucket(Bucket="test-bucket-3")- for i in range(5):- s3.put_object(Bucket="test-bucket-3", Key=f"file-{i}.txt", Body=f"content-{i}".encode())- resp = s3.list_objects_v2(Bucket="test-bucket-3")- assert resp["KeyCount"] == 5+def test_s3_delete_bucket(s3):+ s3.create_bucket(Bucket="intg-s3-delbkt")+ s3.delete_bucket(Bucket="intg-s3-delbkt")+ buckets = [b["Name"] for b in s3.list_buckets()["Buckets"]]+ assert "intg-s3-delbkt" not in buckets+++def test_s3_delete_bucket_not_empty(s3):+ s3.create_bucket(Bucket="intg-s3-notempty")+ s3.put_object(Bucket="intg-s3-notempty", Key="file.txt", Body=b"data")+ with pytest.raises(ClientError) as exc:+ s3.delete_bucket(Bucket="intg-s3-notempty")+ assert exc.value.response["Error"]["Code"] == "BucketNotEmpty"+++def test_s3_delete_bucket_not_found(s3):+ with pytest.raises(ClientError) as exc:+ s3.delete_bucket(Bucket="intg-s3-nonexistent-xyz")+ assert exc.value.response["Error"]["Code"] == "NoSuchBucket"+++def test_s3_head_bucket(s3):+ s3.create_bucket(Bucket="intg-s3-headbkt")+ resp = s3.head_bucket(Bucket="intg-s3-headbkt")+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200++ with pytest.raises(ClientError) as exc:+ s3.head_bucket(Bucket="intg-s3-headbkt-missing")+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404+++def test_s3_put_get_object(s3):+ s3.create_bucket(Bucket="intg-s3-putget")+ s3.put_object(Bucket="intg-s3-putget", Key="hello.txt", Body=b"Hello, World!")+ resp = s3.get_object(Bucket="intg-s3-putget", Key="hello.txt")+ assert resp["Body"].read() == b"Hello, World!"+++def test_s3_put_object_no_bucket(s3):+ with pytest.raises(ClientError) as exc:+ s3.put_object(Bucket="intg-s3-nobucket-xyz", Key="k", Body=b"x")+ assert exc.value.response["Error"]["Code"] == "NoSuchBucket"+++def test_s3_head_object(s3):+ s3.create_bucket(Bucket="intg-s3-headobj")+ s3.put_object(+ Bucket="intg-s3-headobj", Key="data.bin",+ Body=b"0123456789", ContentType="application/octet-stream",+ )+ resp = s3.head_object(Bucket="intg-s3-headobj", Key="data.bin")+ assert resp["ContentLength"] == 10+ assert resp["ContentType"] == "application/octet-stream"+ assert "ETag" in resp+++def test_s3_head_object_not_found(s3):+ s3.create_bucket(Bucket="intg-s3-headobj404")+ with pytest.raises(ClientError) as exc:+ s3.head_object(Bucket="intg-s3-headobj404", Key="missing.txt")+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404++def test_s3_delete_object(s3):+ s3.create_bucket(Bucket="intg-s3-delobj")+ s3.put_object(Bucket="intg-s3-delobj", Key="bye.txt", Body=b"bye")+ s3.delete_object(Bucket="intg-s3-delobj", Key="bye.txt")+ with pytest.raises(ClientError):+ s3.get_object(Bucket="intg-s3-delobj", Key="bye.txt")-def test_s3_delete(s3):- s3.create_bucket(Bucket="test-bucket-4")- s3.put_object(Bucket="test-bucket-4", Key="to-delete.txt", Body=b"bye")- s3.delete_object(Bucket="test-bucket-4", Key="to-delete.txt")- resp = s3.list_objects_v2(Bucket="test-bucket-4")- assert resp["KeyCount"] == 0++def test_s3_delete_object_idempotent(s3):+ s3.create_bucket(Bucket="intg-s3-delidempotent")+ resp = s3.delete_object(Bucket="intg-s3-delidempotent", Key="nonexistent.txt")+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 204+++def test_s3_copy_object(s3):+ s3.create_bucket(Bucket="intg-s3-copysrc")+ s3.create_bucket(Bucket="intg-s3-copydst")+ s3.put_object(Bucket="intg-s3-copysrc", Key="original.txt", Body=b"copy me")+ s3.copy_object(+ CopySource={"Bucket": "intg-s3-copysrc", "Key": "original.txt"},+ Bucket="intg-s3-copydst", Key="copied.txt",+ )+ resp = s3.get_object(Bucket="intg-s3-copydst", Key="copied.txt")+ assert resp["Body"].read() == b"copy me"-def test_s3_copy(s3):- s3.create_bucket(Bucket="test-bucket-5a")- s3.create_bucket(Bucket="test-bucket-5b")- s3.put_object(Bucket="test-bucket-5a", Key="original.txt", Body=b"original content")+def test_s3_copy_object_metadata_replace(s3):+ bkt = "intg-s3-copymeta"+ s3.create_bucket(Bucket=bkt)+ s3.put_object(+ Bucket=bkt, Key="src.txt", Body=b"metadata test",+ Metadata={"original-key": "original-value"},+ )s3.copy_object(- CopySource={"Bucket": "test-bucket-5a", "Key": "original.txt"},- Bucket="test-bucket-5b", Key="copied.txt",+ CopySource={"Bucket": bkt, "Key": "src.txt"},+ Bucket=bkt, Key="dst.txt",+ MetadataDirective="REPLACE",+ Metadata={"replaced-key": "replaced-value"},+ )+ resp = s3.head_object(Bucket=bkt, Key="dst.txt")+ assert resp["Metadata"].get("replaced-key") == "replaced-value"+ assert "original-key" not in resp["Metadata"]+++def test_s3_list_objects_v1(s3):+ bkt = "intg-s3-listv1"+ s3.create_bucket(Bucket=bkt)+ for key in ["photos/2023/a.jpg", "photos/2023/b.jpg",+ "photos/2024/c.jpg", "docs/readme.md"]:+ s3.put_object(Bucket=bkt, Key=key, Body=b"x")++ resp = s3.list_objects(Bucket=bkt, Prefix="photos/", Delimiter="/")+ prefixes = [p["Prefix"] for p in resp.get("CommonPrefixes", [])]+ assert "photos/2023/" in prefixes+ assert "photos/2024/" in prefixes+ assert len(resp.get("Contents", [])) == 0+++def test_s3_list_objects_v2(s3):+ bkt = "intg-s3-listv2"+ s3.create_bucket(Bucket=bkt)+ for key in ["a/1.txt", "a/2.txt", "b/3.txt"]:+ s3.put_object(Bucket=bkt, Key=key, Body=b"v2")++ resp = s3.list_objects_v2(Bucket=bkt, Prefix="a/")+ assert resp["KeyCount"] == 2+ keys = [c["Key"] for c in resp["Contents"]]+ assert "a/1.txt" in keys+ assert "a/2.txt" in keys+++def test_s3_list_objects_pagination(s3):+ bkt = "intg-s3-listpage"+ s3.create_bucket(Bucket=bkt)+ for i in range(7):+ s3.put_object(Bucket=bkt, Key=f"item-{i:02d}.txt", Body=b"p")++ resp = s3.list_objects_v2(Bucket=bkt, MaxKeys=3)+ assert resp["IsTruncated"] is True+ assert resp["KeyCount"] == 3+ token = resp["NextContinuationToken"]++ all_keys = [c["Key"] for c in resp["Contents"]]+ while resp["IsTruncated"]:+ resp = s3.list_objects_v2(+ Bucket=bkt, MaxKeys=3, ContinuationToken=token,+ )+ all_keys.extend(c["Key"] for c in resp["Contents"])+ token = resp.get("NextContinuationToken", "")++ assert len(all_keys) == 7+++def test_s3_delete_objects_batch(s3):+ bkt = "intg-s3-batchdel"+ s3.create_bucket(Bucket=bkt)+ keys = [f"obj-{i}.txt" for i in range(5)]+ for k in keys:+ s3.put_object(Bucket=bkt, Key=k, Body=b"batch")++ resp = s3.delete_objects(+ Bucket=bkt,+ Delete={"Objects": [{"Key": k} for k in keys], "Quiet": False},+ )+ assert len(resp.get("Deleted", [])) == 5+ listing = s3.list_objects_v2(Bucket=bkt)+ assert listing["KeyCount"] == 0+++def test_s3_multipart_upload(s3):+ bkt = "intg-s3-multipart"+ s3.create_bucket(Bucket=bkt)+ key = "large.bin"++ mpu = s3.create_multipart_upload(Bucket=bkt, Key=key)+ upload_id = mpu["UploadId"]++ p1 = s3.upload_part(+ Bucket=bkt, Key=key, UploadId=upload_id,+ PartNumber=1, Body=b"A" * 100,)- resp = s3.get_object(Bucket="test-bucket-5b", Key="copied.txt")- assert resp["Body"].read() == b"original content"+ p2 = s3.upload_part(+ Bucket=bkt, Key=key, UploadId=upload_id,+ PartNumber=2, Body=b"B" * 100,+ )++ s3.complete_multipart_upload(+ Bucket=bkt, Key=key, UploadId=upload_id,+ MultipartUpload={"Parts": [+ {"PartNumber": 1, "ETag": p1["ETag"]},+ {"PartNumber": 2, "ETag": p2["ETag"]},+ ]},+ )+ resp = s3.get_object(Bucket=bkt, Key=key)+ assert resp["Body"].read() == b"A" * 100 + b"B" * 100+++def test_s3_abort_multipart_upload(s3):+ bkt = "intg-s3-abortmpu"+ s3.create_bucket(Bucket=bkt)+ key = "aborted.bin"++ mpu = s3.create_multipart_upload(Bucket=bkt, Key=key)+ upload_id = mpu["UploadId"]+ s3.upload_part(+ Bucket=bkt, Key=key, UploadId=upload_id,+ PartNumber=1, Body=b"X" * 50,+ )+ s3.abort_multipart_upload(Bucket=bkt, Key=key, UploadId=upload_id)++ with pytest.raises(ClientError) as exc:+ s3.get_object(Bucket=bkt, Key=key)+ assert exc.value.response["Error"]["Code"] == "NoSuchKey"-def test_s3_head(s3):- s3.create_bucket(Bucket="test-bucket-6")- s3.put_object(Bucket="test-bucket-6", Key="meta.txt", Body=b"12345")- resp = s3.head_object(Bucket="test-bucket-6", Key="meta.txt")- assert resp["ContentLength"] == 5+def test_s3_get_object_range(s3):+ bkt = "intg-s3-range"+ s3.create_bucket(Bucket=bkt)+ s3.put_object(Bucket=bkt, Key="ranged.txt", Body=b"0123456789")++ resp = s3.get_object(Bucket=bkt, Key="ranged.txt", Range="bytes=2-5")+ assert resp["Body"].read() == b"2345"+ assert resp["ContentLength"] == 4+ assert "bytes" in resp.get("ContentRange", "")+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 206+++def test_s3_object_metadata(s3):+ bkt = "intg-s3-meta"+ s3.create_bucket(Bucket=bkt)+ s3.put_object(+ Bucket=bkt, Key="meta.txt", Body=b"metadata",+ Metadata={"custom-key": "custom-value", "another": "data"},+ )+ resp = s3.head_object(Bucket=bkt, Key="meta.txt")+ assert resp["Metadata"]["custom-key"] == "custom-value"+ assert resp["Metadata"]["another"] == "data"+++def test_s3_bucket_tagging(s3):+ bkt = "intg-s3-bkttags"+ s3.create_bucket(Bucket=bkt)+ s3.put_bucket_tagging(+ Bucket=bkt,+ Tagging={"TagSet": [+ {"Key": "env", "Value": "test"},+ {"Key": "team", "Value": "platform"},+ ]},+ )+ resp = s3.get_bucket_tagging(Bucket=bkt)+ tags = {t["Key"]: t["Value"] for t in resp["TagSet"]}+ assert tags["env"] == "test"+ assert tags["team"] == "platform"++ s3.delete_bucket_tagging(Bucket=bkt)+ with pytest.raises(ClientError) as exc:+ s3.get_bucket_tagging(Bucket=bkt)+ assert exc.value.response["Error"]["Code"] == "NoSuchTagSet"+++def test_s3_bucket_policy(s3):+ bkt = "intg-s3-policy"+ s3.create_bucket(Bucket=bkt)+ policy = json.dumps({+ "Version": "2012-10-17",+ "Statement": [{+ "Effect": "Allow",+ "Principal": "*",+ "Action": "s3:GetObject",+ "Resource": f"arn:aws:s3:::{bkt}/*",+ }],+ })+ s3.put_bucket_policy(Bucket=bkt, Policy=policy)+ resp = s3.get_bucket_policy(Bucket=bkt)+ stored = json.loads(resp["Policy"])+ assert stored["Version"] == "2012-10-17"+ assert len(stored["Statement"]) == 1+++def test_s3_object_tagging(s3):+ bkt = "intg-s3-objtags"+ s3.create_bucket(Bucket=bkt)+ s3.put_object(Bucket=bkt, Key="tagged.txt", Body=b"tagged")+ s3.put_object_tagging(+ Bucket=bkt, Key="tagged.txt",+ Tagging={"TagSet": [+ {"Key": "status", "Value": "active"},+ {"Key": "priority", "Value": "high"},+ ]},+ )+ resp = s3.get_object_tagging(Bucket=bkt, Key="tagged.txt")+ tags = {t["Key"]: t["Value"] for t in resp["TagSet"]}+ assert tags["status"] == "active"+ assert tags["priority"] == "high"# ========== SQS ==========-def test_sqs_basic(sqs):- resp = sqs.create_queue(QueueName="test-queue-1")- url = resp["QueueUrl"]- sqs.send_message(QueueUrl=url, MessageBody="hello sqs")- msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=1)- assert len(msgs.get("Messages", [])) == 1- assert msgs["Messages"][0]["Body"] == "hello sqs"+def test_sqs_create_queue(sqs):+ resp = sqs.create_queue(QueueName="intg-sqs-create")+ assert "QueueUrl" in resp+ assert "intg-sqs-create" in resp["QueueUrl"]+++def test_sqs_delete_queue(sqs):+ url = sqs.create_queue(QueueName="intg-sqs-delete")["QueueUrl"]+ sqs.delete_queue(QueueUrl=url)+ with pytest.raises(ClientError):+ sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["All"])+++def test_sqs_list_queues(sqs):+ sqs.create_queue(QueueName="intg-sqs-list-alpha")+ sqs.create_queue(QueueName="intg-sqs-list-beta")+ resp = sqs.list_queues(QueueNamePrefix="intg-sqs-list-")+ urls = resp.get("QueueUrls", [])+ assert len(urls) >= 2+ assert any("intg-sqs-list-alpha" in u for u in urls)+ assert any("intg-sqs-list-beta" in u for u in urls)+++def test_sqs_get_queue_url(sqs):+ sqs.create_queue(QueueName="intg-sqs-geturl")+ resp = sqs.get_queue_url(QueueName="intg-sqs-geturl")+ assert "intg-sqs-geturl" in resp["QueueUrl"]-def test_sqs_delete_msg(sqs):- resp = sqs.create_queue(QueueName="test-queue-2")- url = resp["QueueUrl"]- sqs.send_message(QueueUrl=url, MessageBody="to delete")++def test_sqs_send_receive_delete(sqs):+ url = sqs.create_queue(QueueName="intg-sqs-srd")["QueueUrl"]+ sqs.send_message(QueueUrl=url, MessageBody="test-body")msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=1)- receipt = msgs["Messages"][0]["ReceiptHandle"]- sqs.delete_message(QueueUrl=url, ReceiptHandle=receipt)+ assert len(msgs["Messages"]) == 1+ assert msgs["Messages"][0]["Body"] == "test-body"+ sqs.delete_message(+ QueueUrl=url, ReceiptHandle=msgs["Messages"][0]["ReceiptHandle"],+ )+ empty = sqs.receive_message(+ QueueUrl=url, MaxNumberOfMessages=1, WaitTimeSeconds=0,+ )+ assert len(empty.get("Messages", [])) == 0-def test_sqs_list(sqs):- sqs.create_queue(QueueName="test-queue-list-1")- sqs.create_queue(QueueName="test-queue-list-2")- resp = sqs.list_queues()- assert len(resp.get("QueueUrls", [])) >= 2+def test_sqs_message_attributes(sqs):+ url = sqs.create_queue(QueueName="intg-sqs-attrs")["QueueUrl"]+ sqs.send_message(+ QueueUrl=url, MessageBody="with-attrs",+ MessageAttributes={+ "color": {"DataType": "String", "StringValue": "blue"},+ "count": {"DataType": "Number", "StringValue": "42"},+ },+ )+ msgs = sqs.receive_message(+ QueueUrl=url, MaxNumberOfMessages=1,+ MessageAttributeNames=["All"],+ )+ attrs = msgs["Messages"][0]["MessageAttributes"]+ assert attrs["color"]["StringValue"] == "blue"+ assert attrs["count"]["StringValue"] == "42"-def test_sqs_batch(sqs):- resp = sqs.create_queue(QueueName="test-queue-batch")- url = resp["QueueUrl"]- sqs.send_message_batch(+def test_sqs_batch_send(sqs):+ url = sqs.create_queue(QueueName="intg-sqs-batchsend")["QueueUrl"]+ resp = sqs.send_message_batch(QueueUrl=url,- Entries=[{"Id": str(i), "MessageBody": f"msg{i}"} for i in range(3)],+ Entries=[+ {"Id": "m1", "MessageBody": "batch-1"},+ {"Id": "m2", "MessageBody": "batch-2"},+ {"Id": "m3", "MessageBody": "batch-3"},+ ],+ )+ assert len(resp["Successful"]) == 3+ assert len(resp.get("Failed", [])) == 0+++def test_sqs_batch_delete(sqs):+ url = sqs.create_queue(QueueName="intg-sqs-batchdel")["QueueUrl"]+ for i in range(3):+ sqs.send_message(QueueUrl=url, MessageBody=f"del-{i}")++ msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10)+ entries = [+ {"Id": str(i), "ReceiptHandle": m["ReceiptHandle"]}+ for i, m in enumerate(msgs["Messages"])+ ]+ resp = sqs.delete_message_batch(QueueUrl=url, Entries=entries)+ assert len(resp["Successful"]) == len(entries)+++def test_sqs_purge_queue(sqs):+ url = sqs.create_queue(QueueName="intg-sqs-purge")["QueueUrl"]+ for i in range(5):+ sqs.send_message(QueueUrl=url, MessageBody=f"purge-{i}")+ sqs.purge_queue(QueueUrl=url)+ msgs = sqs.receive_message(+ QueueUrl=url, MaxNumberOfMessages=10, WaitTimeSeconds=0,+ )+ assert len(msgs.get("Messages", [])) == 0+++def test_sqs_visibility_timeout(sqs):+ url = sqs.create_queue(QueueName="intg-sqs-vis")["QueueUrl"]+ sqs.send_message(QueueUrl=url, MessageBody="vis-test")++ msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=1)+ rh = msgs["Messages"][0]["ReceiptHandle"]+ sqs.change_message_visibility(+ QueueUrl=url, ReceiptHandle=rh, VisibilityTimeout=0,+ )+ msgs2 = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=1)+ assert len(msgs2["Messages"]) == 1+ assert msgs2["Messages"][0]["Body"] == "vis-test"+++def test_sqs_change_visibility_batch(sqs):+ url = sqs.create_queue(QueueName="intg-sqs-visbatch")["QueueUrl"]+ for i in range(2):+ sqs.send_message(QueueUrl=url, MessageBody=f"vb-{i}")++ msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10)+ entries = [+ {"Id": str(i), "ReceiptHandle": m["ReceiptHandle"],+ "VisibilityTimeout": 0}+ for i, m in enumerate(msgs["Messages"])+ ]+ resp = sqs.change_message_visibility_batch(QueueUrl=url, Entries=entries)+ assert len(resp["Successful"]) == len(entries)++ msgs2 = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10)+ assert len(msgs2["Messages"]) == 2+++def test_sqs_queue_attributes(sqs):+ url = sqs.create_queue(QueueName="intg-sqs-qattr")["QueueUrl"]+ sqs.set_queue_attributes(+ QueueUrl=url, Attributes={"VisibilityTimeout": "60"},+ )+ resp = sqs.get_queue_attributes(+ QueueUrl=url, AttributeNames=["VisibilityTimeout"],)+ assert resp["Attributes"]["VisibilityTimeout"] == "60"+++def test_sqs_queue_tags(sqs):+ url = sqs.create_queue(QueueName="intg-sqs-tags")["QueueUrl"]+ sqs.tag_queue(QueueUrl=url, Tags={"env": "test", "team": "backend"})+ resp = sqs.list_queue_tags(QueueUrl=url)+ assert resp["Tags"]["env"] == "test"+ assert resp["Tags"]["team"] == "backend"++ sqs.untag_queue(QueueUrl=url, TagKeys=["team"])+ resp = sqs.list_queue_tags(QueueUrl=url)+ assert "team" not in resp.get("Tags", {})+ assert resp["Tags"]["env"] == "test"+++def test_sqs_fifo_queue(sqs):+ url = sqs.create_queue(+ QueueName="intg-sqs-fifo.fifo",+ Attributes={+ "FifoQueue": "true",+ "ContentBasedDeduplication": "true",+ },+ )["QueueUrl"]++ for i in range(3):+ sqs.send_message(+ QueueUrl=url, MessageBody=f"fifo-msg-{i}",+ MessageGroupId="group-1",+ )+msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10)- assert len(msgs.get("Messages", [])) >= 1+ assert len(msgs["Messages"]) >= 1+ assert msgs["Messages"][0]["Body"] == "fifo-msg-0"+++def test_sqs_fifo_deduplication(sqs):+ url = sqs.create_queue(+ QueueName="intg-sqs-dedup.fifo",+ Attributes={+ "FifoQueue": "true",+ "ContentBasedDeduplication": "false",+ },+ )["QueueUrl"]++ r1 = sqs.send_message(+ QueueUrl=url, MessageBody="dedup-body",+ MessageGroupId="g1", MessageDeduplicationId="dedup-001",+ )+ r2 = sqs.send_message(+ QueueUrl=url, MessageBody="dedup-body",+ MessageGroupId="g1", MessageDeduplicationId="dedup-001",+ )+ assert r1["MessageId"] == r2["MessageId"]+++def test_sqs_dlq(sqs):+ dlq_url = sqs.create_queue(QueueName="intg-sqs-dlq-target")["QueueUrl"]+ dlq_arn = sqs.get_queue_attributes(+ QueueUrl=dlq_url, AttributeNames=["QueueArn"],+ )["Attributes"]["QueueArn"]++ src_url = sqs.create_queue(+ QueueName="intg-sqs-dlq-source",+ Attributes={+ "RedrivePolicy": json.dumps({+ "deadLetterTargetArn": dlq_arn,+ "maxReceiveCount": "2",+ }),+ },+ )["QueueUrl"]++ sqs.send_message(QueueUrl=src_url, MessageBody="dlq-test")++ for _ in range(2):+ msgs = sqs.receive_message(QueueUrl=src_url, MaxNumberOfMessages=1)+ assert len(msgs["Messages"]) == 1+ rh = msgs["Messages"][0]["ReceiptHandle"]+ sqs.change_message_visibility(+ QueueUrl=src_url, ReceiptHandle=rh, VisibilityTimeout=0,+ )++ time.sleep(0.1)+ empty = sqs.receive_message(+ QueueUrl=src_url, MaxNumberOfMessages=1, WaitTimeSeconds=0,+ )+ assert len(empty.get("Messages", [])) == 0++ dlq_msgs = sqs.receive_message(+ QueueUrl=dlq_url, MaxNumberOfMessages=1,+ )+ assert len(dlq_msgs["Messages"]) == 1+ assert dlq_msgs["Messages"][0]["Body"] == "dlq-test"+++def test_sqs_delay_seconds(sqs):+ url = sqs.create_queue(QueueName="intg-sqs-delay")["QueueUrl"]+ sqs.send_message(QueueUrl=url, MessageBody="delayed", DelaySeconds=2)++ msgs = sqs.receive_message(+ QueueUrl=url, MaxNumberOfMessages=1, WaitTimeSeconds=0,+ )+ assert len(msgs.get("Messages", [])) == 0++ time.sleep(2.5)+ msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=1)+ assert len(msgs["Messages"]) == 1+ assert msgs["Messages"][0]["Body"] == "delayed"+++def test_sqs_message_system_attributes(sqs):+ url = sqs.create_queue(QueueName="intg-sqs-sysattr")["QueueUrl"]+ sqs.send_message(QueueUrl=url, MessageBody="sysattr-test")++ msgs = sqs.receive_message(+ QueueUrl=url, MaxNumberOfMessages=1,+ AttributeNames=["ApproximateReceiveCount"],+ )+ assert msgs["Messages"][0]["Attributes"]["ApproximateReceiveCount"] == "1"++ rh = msgs["Messages"][0]["ReceiptHandle"]+ sqs.change_message_visibility(+ QueueUrl=url, ReceiptHandle=rh, VisibilityTimeout=0,+ )+ msgs2 = sqs.receive_message(+ QueueUrl=url, MaxNumberOfMessages=1,+ AttributeNames=["ApproximateReceiveCount"],+ )+ assert msgs2["Messages"][0]["Attributes"]["ApproximateReceiveCount"] == "2"+++def test_sqs_nonexistent_queue(sqs):+ with pytest.raises(ClientError) as exc:+ sqs.get_queue_url(QueueName="intg-sqs-does-not-exist")+ assert "NonExistentQueue" in exc.value.response["Error"]["Code"]+++def test_sqs_receive_empty(sqs):+ url = sqs.create_queue(QueueName="intg-sqs-empty")["QueueUrl"]+ msgs = sqs.receive_message(+ QueueUrl=url, MaxNumberOfMessages=1, WaitTimeSeconds=0,+ )+ assert len(msgs.get("Messages", [])) == 0# ========== SNS ==========-def test_sns_basic(sns):- resp = sns.create_topic(Name="test-topic-1")- arn = resp["TopicArn"]- assert "test-topic-1" in arn- pub = sns.publish(TopicArn=arn, Message="hello sns", Subject="Test")- assert "MessageId" in pub++def test_sns_create_topic(sns):+ resp = sns.create_topic(Name="intg-sns-create")+ assert "TopicArn" in resp+ assert "intg-sns-create" in resp["TopicArn"]+++def test_sns_delete_topic(sns):+ arn = sns.create_topic(Name="intg-sns-delete")["TopicArn"]+ sns.delete_topic(TopicArn=arn)+ topics = sns.list_topics()["Topics"]+ assert not any(t["TopicArn"] == arn for t in topics)+++def test_sns_list_topics(sns):+ sns.create_topic(Name="intg-sns-list-1")+ sns.create_topic(Name="intg-sns-list-2")+ topics = sns.list_topics()["Topics"]+ arns = [t["TopicArn"] for t in topics]+ assert any("intg-sns-list-1" in a for a in arns)+ assert any("intg-sns-list-2" in a for a in arns)+++def test_sns_get_topic_attributes(sns):+ arn = sns.create_topic(Name="intg-sns-getattr")["TopicArn"]+ resp = sns.get_topic_attributes(TopicArn=arn)+ assert resp["Attributes"]["TopicArn"] == arn+ assert resp["Attributes"]["DisplayName"] == "intg-sns-getattr"-def test_sns_subscribe(sns):- resp = sns.create_topic(Name="test-topic-2")- arn = resp["TopicArn"]- sub = sns.subscribe(TopicArn=arn, Protocol="email", Endpoint="[email protected]")- assert "SubscriptionArn" in sub- subs = sns.list_subscriptions_by_topic(TopicArn=arn)- assert len(subs.get("Subscriptions", [])) >= 1+def test_sns_set_topic_attributes(sns):+ arn = sns.create_topic(Name="intg-sns-setattr")["TopicArn"]+ sns.set_topic_attributes(+ TopicArn=arn,+ AttributeName="DisplayName",+ AttributeValue="New Display Name",+ )+ resp = sns.get_topic_attributes(TopicArn=arn)+ assert resp["Attributes"]["DisplayName"] == "New Display Name"+++def test_sns_subscribe_email(sns):+ arn = sns.create_topic(Name="intg-sns-subemail")["TopicArn"]+ resp = sns.subscribe(+ TopicArn=arn, Protocol="email", Endpoint="[email protected]",+ )+ assert "SubscriptionArn" in resp+++def test_sns_unsubscribe(sns):+ arn = sns.create_topic(Name="intg-sns-unsub")["TopicArn"]+ sub = sns.subscribe(+ TopicArn=arn, Protocol="email", Endpoint="[email protected]",+ )+ sub_arn = sub["SubscriptionArn"]+ sns.unsubscribe(SubscriptionArn=sub_arn)+ subs = sns.list_subscriptions_by_topic(TopicArn=arn)["Subscriptions"]+ assert not any(s["SubscriptionArn"] == sub_arn for s in subs)+++def test_sns_list_subscriptions(sns):+ arn = sns.create_topic(Name="intg-sns-listsubs")["TopicArn"]+ sns.subscribe(TopicArn=arn, Protocol="email", Endpoint="[email protected]")+ sns.subscribe(TopicArn=arn, Protocol="email", Endpoint="[email protected]")+ subs = sns.list_subscriptions()["Subscriptions"]+ topic_subs = [s for s in subs if s["TopicArn"] == arn]+ assert len(topic_subs) >= 2+++def test_sns_list_subscriptions_by_topic(sns):+ arn = sns.create_topic(Name="intg-sns-listbytopic")["TopicArn"]+ sns.subscribe(+ TopicArn=arn, Protocol="email", Endpoint="[email protected]",+ )+ subs = sns.list_subscriptions_by_topic(TopicArn=arn)["Subscriptions"]+ assert len(subs) >= 1+ assert all(s["TopicArn"] == arn for s in subs)+++def test_sns_publish(sns):+ arn = sns.create_topic(Name="intg-sns-publish")["TopicArn"]+ resp = sns.publish(+ TopicArn=arn, Message="hello sns", Subject="Test Subject",+ )+ assert "MessageId" in resp+++def test_sns_publish_nonexistent_topic(sns):+ fake_arn = "arn:aws:sns:us-east-1:000000000000:intg-sns-nonexist"+ with pytest.raises(ClientError) as exc:+ sns.publish(TopicArn=fake_arn, Message="fail")+ assert exc.value.response["Error"]["Code"] == "NotFound"def test_sns_sqs_fanout(sns, sqs):- # Create topic and queue- topic_arn = sns.create_topic(Name="fanout-topic")["TopicArn"]- q_url = sqs.create_queue(QueueName="fanout-queue")["QueueUrl"]- q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]+ topic_arn = sns.create_topic(Name="intg-sns-fanout")["TopicArn"]+ q_url = sqs.create_queue(QueueName="intg-sns-fanout-q")["QueueUrl"]+ q_arn = sqs.get_queue_attributes(+ QueueUrl=q_url, AttributeNames=["QueueArn"],+ )["Attributes"]["QueueArn"]- # Subscribe SQS queue to SNS topicsns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)+ sns.publish(TopicArn=topic_arn, Message="fanout msg", Subject="Fan")- # Publish to topic- sns.publish(TopicArn=topic_arn, Message="hello fanout", Subject="test")-- # Message should appear in SQS queue- msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1)+ msgs = sqs.receive_message(+ QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=1,+ )assert len(msgs.get("Messages", [])) == 1- import jsonbody = json.loads(msgs["Messages"][0]["Body"])- assert body["Message"] == "hello fanout"+ assert body["Message"] == "fanout msg"assert body["TopicArn"] == topic_arn+def test_sns_tags(sns):+ arn = sns.create_topic(Name="intg-sns-tags")["TopicArn"]+ sns.tag_resource(+ ResourceArn=arn,+ Tags=[+ {"Key": "env", "Value": "staging"},+ {"Key": "team", "Value": "infra"},+ ],+ )+ resp = sns.list_tags_for_resource(ResourceArn=arn)+ tags = {t["Key"]: t["Value"] for t in resp["Tags"]}+ assert tags["env"] == "staging"+ assert tags["team"] == "infra"++ sns.untag_resource(ResourceArn=arn, TagKeys=["team"])+ resp = sns.list_tags_for_resource(ResourceArn=arn)+ tags = {t["Key"]: t["Value"] for t in resp["Tags"]}+ assert "team" not in tags+ assert tags["env"] == "staging"+++def test_sns_subscription_attributes(sns):+ arn = sns.create_topic(Name="intg-sns-subattr")["TopicArn"]+ sub = sns.subscribe(+ TopicArn=arn, Protocol="email", Endpoint="[email protected]",+ )+ sub_arn = sub["SubscriptionArn"]++ resp = sns.get_subscription_attributes(SubscriptionArn=sub_arn)+ assert resp["Attributes"]["Protocol"] == "email"+ assert resp["Attributes"]["TopicArn"] == arn++ sns.set_subscription_attributes(+ SubscriptionArn=sub_arn,+ AttributeName="RawMessageDelivery",+ AttributeValue="true",+ )+ resp = sns.get_subscription_attributes(SubscriptionArn=sub_arn)+ assert resp["Attributes"]["RawMessageDelivery"] == "true"+++def test_sns_publish_batch(sns):+ arn = sns.create_topic(Name="intg-sns-batch")["TopicArn"]+ resp = sns.publish_batch(+ TopicArn=arn,+ PublishBatchRequestEntries=[+ {"Id": "msg1", "Message": "batch message 1"},+ {"Id": "msg2", "Message": "batch message 2"},+ {"Id": "msg3", "Message": "batch message 3"},+ ],+ )+ assert len(resp["Successful"]) == 3+ assert len(resp.get("Failed", [])) == 0++# ========== DynamoDB ==========def test_dynamodb_basic(ddb):@@ -736,3 +1385,4370 @@ def test_athena_workgroup(athena):WorkGroup="test-wg",)assert "NamedQueryId" in resp+++# ===================================================================+# DynamoDB — comprehensive tests+# ===================================================================++def _make_zip(code: str) -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ return buf.getvalue()+++def test_ddb_create_table(ddb):+ resp = ddb.create_table(+ TableName="t_hash_only",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ desc = resp["TableDescription"]+ assert desc["TableName"] == "t_hash_only"+ assert desc["TableStatus"] == "ACTIVE"+ assert any(k["KeyType"] == "HASH" for k in desc["KeySchema"])+++def test_ddb_create_table_composite(ddb):+ resp = ddb.create_table(+ TableName="t_composite",+ KeySchema=[+ {"AttributeName": "pk", "KeyType": "HASH"},+ {"AttributeName": "sk", "KeyType": "RANGE"},+ ],+ AttributeDefinitions=[+ {"AttributeName": "pk", "AttributeType": "S"},+ {"AttributeName": "sk", "AttributeType": "S"},+ ],+ BillingMode="PAY_PER_REQUEST",+ )+ ks = resp["TableDescription"]["KeySchema"]+ types = {k["KeyType"] for k in ks}+ assert types == {"HASH", "RANGE"}+++def test_ddb_create_table_duplicate(ddb):+ with pytest.raises(ClientError) as exc:+ ddb.create_table(+ TableName="t_hash_only",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ assert exc.value.response["Error"]["Code"] == "ResourceInUseException"+++def test_ddb_delete_table(ddb):+ ddb.create_table(+ TableName="t_to_delete",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ resp = ddb.delete_table(TableName="t_to_delete")+ assert resp["TableDescription"]["TableStatus"] == "DELETING"+ tables = ddb.list_tables()["TableNames"]+ assert "t_to_delete" not in tables+++def test_ddb_delete_table_not_found(ddb):+ with pytest.raises(ClientError) as exc:+ ddb.delete_table(TableName="t_nonexistent_xyz")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_ddb_describe_table(ddb):+ ddb.create_table(+ TableName="t_describe_gsi",+ KeySchema=[+ {"AttributeName": "pk", "KeyType": "HASH"},+ {"AttributeName": "sk", "KeyType": "RANGE"},+ ],+ AttributeDefinitions=[+ {"AttributeName": "pk", "AttributeType": "S"},+ {"AttributeName": "sk", "AttributeType": "S"},+ {"AttributeName": "gsi_pk", "AttributeType": "S"},+ ],+ GlobalSecondaryIndexes=[{+ "IndexName": "gsi1",+ "KeySchema": [{"AttributeName": "gsi_pk", "KeyType": "HASH"}],+ "Projection": {"ProjectionType": "ALL"},+ }],+ LocalSecondaryIndexes=[{+ "IndexName": "lsi1",+ "KeySchema": [+ {"AttributeName": "pk", "KeyType": "HASH"},+ {"AttributeName": "sk", "KeyType": "RANGE"},+ ],+ "Projection": {"ProjectionType": "ALL"},+ }],+ BillingMode="PAY_PER_REQUEST",+ )+ resp = ddb.describe_table(TableName="t_describe_gsi")+ table = resp["Table"]+ assert table["TableName"] == "t_describe_gsi"+ assert len(table["GlobalSecondaryIndexes"]) == 1+ assert table["GlobalSecondaryIndexes"][0]["IndexName"] == "gsi1"+ assert len(table["LocalSecondaryIndexes"]) == 1+ assert table["LocalSecondaryIndexes"][0]["IndexName"] == "lsi1"+++def test_ddb_list_tables(ddb):+ for i in range(3):+ try:+ ddb.create_table(+ TableName=f"t_list_{i}",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ except ClientError:+ pass+ resp = ddb.list_tables(Limit=2)+ assert len(resp["TableNames"]) <= 2+ if "LastEvaluatedTableName" in resp:+ resp2 = ddb.list_tables(ExclusiveStartTableName=resp["LastEvaluatedTableName"], Limit=100)+ assert len(resp2["TableNames"]) >= 1+++def test_ddb_put_get_item(ddb):+ ddb.put_item(+ TableName="t_hash_only",+ Item={+ "pk": {"S": "allTypes"},+ "str_attr": {"S": "hello"},+ "num_attr": {"N": "42"},+ "bool_attr": {"BOOL": True},+ "null_attr": {"NULL": True},+ "list_attr": {"L": [{"S": "a"}, {"N": "1"}]},+ "map_attr": {"M": {"nested": {"S": "value"}}},+ "ss_attr": {"SS": ["x", "y"]},+ "ns_attr": {"NS": ["1", "2", "3"]},+ },+ )+ resp = ddb.get_item(TableName="t_hash_only", Key={"pk": {"S": "allTypes"}})+ item = resp["Item"]+ assert item["str_attr"]["S"] == "hello"+ assert item["num_attr"]["N"] == "42"+ assert item["bool_attr"]["BOOL"] is True+ assert item["null_attr"]["NULL"] is True+ assert len(item["list_attr"]["L"]) == 2+ assert item["map_attr"]["M"]["nested"]["S"] == "value"+ assert set(item["ss_attr"]["SS"]) == {"x", "y"}+ assert set(item["ns_attr"]["NS"]) == {"1", "2", "3"}+++def test_ddb_put_item_condition(ddb):+ ddb.put_item(+ TableName="t_hash_only",+ Item={"pk": {"S": "cond_new"}, "val": {"S": "first"}},+ ConditionExpression="attribute_not_exists(pk)",+ )+ resp = ddb.get_item(TableName="t_hash_only", Key={"pk": {"S": "cond_new"}})+ assert resp["Item"]["val"]["S"] == "first"+++def test_ddb_put_item_condition_fail(ddb):+ ddb.put_item(TableName="t_hash_only", Item={"pk": {"S": "cond_fail"}, "val": {"S": "v1"}})+ with pytest.raises(ClientError) as exc:+ ddb.put_item(+ TableName="t_hash_only",+ Item={"pk": {"S": "cond_fail"}, "val": {"S": "v2"}},+ ConditionExpression="attribute_not_exists(pk)",+ )+ assert exc.value.response["Error"]["Code"] == "ConditionalCheckFailedException"+++def test_ddb_delete_item(ddb):+ ddb.put_item(TableName="t_hash_only", Item={"pk": {"S": "to_del"}, "v": {"S": "gone"}})+ ddb.delete_item(TableName="t_hash_only", Key={"pk": {"S": "to_del"}})+ resp = ddb.get_item(TableName="t_hash_only", Key={"pk": {"S": "to_del"}})+ assert "Item" not in resp+++def test_ddb_delete_item_return_old(ddb):+ ddb.put_item(TableName="t_hash_only", Item={"pk": {"S": "ret_old"}, "data": {"S": "precious"}})+ resp = ddb.delete_item(+ TableName="t_hash_only",+ Key={"pk": {"S": "ret_old"}},+ ReturnValues="ALL_OLD",+ )+ assert resp["Attributes"]["data"]["S"] == "precious"+++def test_ddb_update_item_set(ddb):+ ddb.put_item(TableName="t_hash_only", Item={"pk": {"S": "upd_set"}, "count": {"N": "0"}})+ resp = ddb.update_item(+ TableName="t_hash_only",+ Key={"pk": {"S": "upd_set"}},+ UpdateExpression="SET #c = :val",+ ExpressionAttributeNames={"#c": "count"},+ ExpressionAttributeValues={":val": {"N": "10"}},+ ReturnValues="ALL_NEW",+ )+ assert resp["Attributes"]["count"]["N"] == "10"+++def test_ddb_update_item_remove(ddb):+ ddb.put_item(+ TableName="t_hash_only",+ Item={"pk": {"S": "upd_rem"}, "extra": {"S": "bye"}, "keep": {"S": "stay"}},+ )+ resp = ddb.update_item(+ TableName="t_hash_only",+ Key={"pk": {"S": "upd_rem"}},+ UpdateExpression="REMOVE extra",+ ReturnValues="ALL_NEW",+ )+ assert "extra" not in resp["Attributes"]+ assert resp["Attributes"]["keep"]["S"] == "stay"+++def test_ddb_update_item_add(ddb):+ ddb.put_item(TableName="t_hash_only", Item={"pk": {"S": "upd_add"}, "counter": {"N": "5"}})+ resp = ddb.update_item(+ TableName="t_hash_only",+ Key={"pk": {"S": "upd_add"}},+ UpdateExpression="ADD counter :inc",+ ExpressionAttributeValues={":inc": {"N": "3"}},+ ReturnValues="ALL_NEW",+ )+ assert resp["Attributes"]["counter"]["N"] == "8"+++def test_ddb_update_item_all_old(ddb):+ ddb.put_item(TableName="t_hash_only", Item={"pk": {"S": "upd_old"}, "v": {"N": "1"}})+ resp = ddb.update_item(+ TableName="t_hash_only",+ Key={"pk": {"S": "upd_old"}},+ UpdateExpression="SET v = :new",+ ExpressionAttributeValues={":new": {"N": "99"}},+ ReturnValues="ALL_OLD",+ )+ assert resp["Attributes"]["v"]["N"] == "1"+++def test_ddb_query_pk_only(ddb):+ for i in range(3):+ ddb.put_item(+ TableName="t_composite",+ Item={"pk": {"S": "q_pk"}, "sk": {"S": f"sk_{i}"}, "n": {"N": str(i)}},+ )+ resp = ddb.query(+ TableName="t_composite",+ KeyConditionExpression="pk = :pk",+ ExpressionAttributeValues={":pk": {"S": "q_pk"}},+ )+ assert resp["Count"] == 3+++def test_ddb_query_pk_sk(ddb):+ for i in range(5):+ ddb.put_item(+ TableName="t_composite",+ Item={"pk": {"S": "q_sk"}, "sk": {"S": f"item_{i:03d}"}},+ )+ resp_bw = ddb.query(+ TableName="t_composite",+ KeyConditionExpression="pk = :pk AND begins_with(sk, :prefix)",+ ExpressionAttributeValues={+ ":pk": {"S": "q_sk"},+ ":prefix": {"S": "item_00"},+ },+ )+ assert resp_bw["Count"] >= 1+ for item in resp_bw["Items"]:+ assert item["sk"]["S"].startswith("item_00")++ resp_bt = ddb.query(+ TableName="t_composite",+ KeyConditionExpression="pk = :pk AND sk BETWEEN :lo AND :hi",+ ExpressionAttributeValues={+ ":pk": {"S": "q_sk"},+ ":lo": {"S": "item_001"},+ ":hi": {"S": "item_003"},+ },+ )+ assert resp_bt["Count"] >= 1+ for item in resp_bt["Items"]:+ assert "item_001" <= item["sk"]["S"] <= "item_003"+++def test_ddb_query_filter(ddb):+ for i in range(5):+ ddb.put_item(+ TableName="t_composite",+ Item={"pk": {"S": "q_filt"}, "sk": {"S": f"f_{i}"}, "val": {"N": str(i)}},+ )+ resp = ddb.query(+ TableName="t_composite",+ KeyConditionExpression="pk = :pk",+ FilterExpression="val > :min",+ ExpressionAttributeValues={":pk": {"S": "q_filt"}, ":min": {"N": "2"}},+ )+ assert resp["Count"] == 2+ assert resp["ScannedCount"] == 5+++def test_ddb_query_pagination(ddb):+ for i in range(6):+ ddb.put_item(+ TableName="t_composite",+ Item={"pk": {"S": "q_page"}, "sk": {"S": f"p_{i:03d}"}},+ )+ resp1 = ddb.query(+ TableName="t_composite",+ KeyConditionExpression="pk = :pk",+ ExpressionAttributeValues={":pk": {"S": "q_page"}},+ Limit=3,+ )+ assert resp1["Count"] == 3+ assert "LastEvaluatedKey" in resp1++ resp2 = ddb.query(+ TableName="t_composite",+ KeyConditionExpression="pk = :pk",+ ExpressionAttributeValues={":pk": {"S": "q_page"}},+ ExclusiveStartKey=resp1["LastEvaluatedKey"],+ Limit=3,+ )+ assert resp2["Count"] == 3+ page1_sks = {it["sk"]["S"] for it in resp1["Items"]}+ page2_sks = {it["sk"]["S"] for it in resp2["Items"]}+ assert page1_sks.isdisjoint(page2_sks)+++def test_ddb_scan(ddb):+ ddb.create_table(+ TableName="t_scan",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ for i in range(8):+ ddb.put_item(TableName="t_scan", Item={"pk": {"S": f"sc_{i}"}, "n": {"N": str(i)}})+ resp = ddb.scan(TableName="t_scan")+ assert resp["Count"] == 8+ assert len(resp["Items"]) == 8+++def test_ddb_scan_filter(ddb):+ resp = ddb.scan(+ TableName="t_scan",+ FilterExpression="n >= :min",+ ExpressionAttributeValues={":min": {"N": "5"}},+ )+ assert resp["Count"] == 3+ for item in resp["Items"]:+ assert int(item["n"]["N"]) >= 5+++def test_ddb_batch_write(ddb):+ ddb.create_table(+ TableName="t_bw",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ ddb.batch_write_item(+ RequestItems={+ "t_bw": [+ {"PutRequest": {"Item": {"pk": {"S": f"bw_{i}"}, "data": {"S": f"d{i}"}}}}+ for i in range(10)+ ]+ }+ )+ resp = ddb.scan(TableName="t_bw")+ assert resp["Count"] == 10+++def test_ddb_batch_get(ddb):+ resp = ddb.batch_get_item(+ RequestItems={+ "t_bw": {+ "Keys": [{"pk": {"S": f"bw_{i}"}} for i in range(5)],+ }+ }+ )+ assert len(resp["Responses"]["t_bw"]) == 5+++def test_ddb_transact_write(ddb):+ ddb.create_table(+ TableName="t_tx",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ ddb.transact_write_items(+ TransactItems=[+ {"Put": {"TableName": "t_tx", "Item": {"pk": {"S": "tx1"}, "v": {"S": "a"}}}},+ {"Put": {"TableName": "t_tx", "Item": {"pk": {"S": "tx2"}, "v": {"S": "b"}}}},+ {"Put": {"TableName": "t_tx", "Item": {"pk": {"S": "tx3"}, "v": {"S": "c"}}}},+ ]+ )+ resp = ddb.scan(TableName="t_tx")+ assert resp["Count"] == 3++ ddb.transact_write_items(+ TransactItems=[+ {"Delete": {"TableName": "t_tx", "Key": {"pk": {"S": "tx3"}}}},+ {+ "Update": {+ "TableName": "t_tx",+ "Key": {"pk": {"S": "tx1"}},+ "UpdateExpression": "SET v = :new",+ "ExpressionAttributeValues": {":new": {"S": "updated"}},+ },+ },+ ]+ )+ item = ddb.get_item(TableName="t_tx", Key={"pk": {"S": "tx1"}})["Item"]+ assert item["v"]["S"] == "updated"+ gone = ddb.get_item(TableName="t_tx", Key={"pk": {"S": "tx3"}})+ assert "Item" not in gone+++def test_ddb_transact_get(ddb):+ resp = ddb.transact_get_items(+ TransactItems=[+ {"Get": {"TableName": "t_tx", "Key": {"pk": {"S": "tx1"}}}},+ {"Get": {"TableName": "t_tx", "Key": {"pk": {"S": "tx2"}}}},+ ]+ )+ assert len(resp["Responses"]) == 2+ assert resp["Responses"][0]["Item"]["pk"]["S"] == "tx1"+ assert resp["Responses"][1]["Item"]["pk"]["S"] == "tx2"+++def test_ddb_gsi_query(ddb):+ ddb.create_table(+ TableName="t_gsi_q",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[+ {"AttributeName": "pk", "AttributeType": "S"},+ {"AttributeName": "gsi_pk", "AttributeType": "S"},+ ],+ GlobalSecondaryIndexes=[{+ "IndexName": "gsi_index",+ "KeySchema": [{"AttributeName": "gsi_pk", "KeyType": "HASH"}],+ "Projection": {"ProjectionType": "ALL"},+ }],+ BillingMode="PAY_PER_REQUEST",+ )+ for i in range(4):+ ddb.put_item(+ TableName="t_gsi_q",+ Item={+ "pk": {"S": f"main_{i}"},+ "gsi_pk": {"S": "shared_gsi"},+ "data": {"N": str(i)},+ },+ )+ ddb.put_item(+ TableName="t_gsi_q",+ Item={"pk": {"S": "main_other"}, "gsi_pk": {"S": "other_gsi"}, "data": {"N": "99"}},+ )+ resp = ddb.query(+ TableName="t_gsi_q",+ IndexName="gsi_index",+ KeyConditionExpression="gsi_pk = :gpk",+ ExpressionAttributeValues={":gpk": {"S": "shared_gsi"}},+ )+ assert resp["Count"] == 4+ for item in resp["Items"]:+ assert item["gsi_pk"]["S"] == "shared_gsi"+++# ===================================================================+# Lambda — comprehensive tests+# ===================================================================++_LAMBDA_CODE = 'def handler(event, context):\n return {"statusCode": 200, "body": "ok"}\n'+_LAMBDA_CODE_V2 = 'def handler(event, context):\n return {"statusCode": 200, "body": "v2"}\n'+_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"+++def test_lambda_create_function(lam):+ resp = lam.create_function(+ FunctionName="lam-create-test",+ Runtime="python3.9",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(_LAMBDA_CODE)},+ )+ assert resp["FunctionName"] == "lam-create-test"+ assert resp["Runtime"] == "python3.9"+ assert resp["Handler"] == "index.handler"+ assert resp["State"] == "Active"+ assert "FunctionArn" in resp+++def test_lambda_create_duplicate(lam):+ with pytest.raises(ClientError) as exc:+ lam.create_function(+ FunctionName="lam-create-test",+ Runtime="python3.9",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(_LAMBDA_CODE)},+ )+ assert exc.value.response["Error"]["Code"] == "ResourceConflictException"+++def test_lambda_get_function(lam):+ resp = lam.get_function(FunctionName="lam-create-test")+ assert resp["Configuration"]["FunctionName"] == "lam-create-test"+ assert "Code" in resp+ assert "Tags" in resp+++def test_lambda_get_function_not_found(lam):+ with pytest.raises(ClientError) as exc:+ lam.get_function(FunctionName="nonexistent-func-xyz")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_lambda_list_functions(lam):+ resp = lam.list_functions()+ names = [f["FunctionName"] for f in resp["Functions"]]+ assert "lam-create-test" in names+++def test_lambda_delete_function(lam):+ lam.create_function(+ FunctionName="lam-to-delete",+ Runtime="python3.9",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(_LAMBDA_CODE)},+ )+ lam.delete_function(FunctionName="lam-to-delete")+ with pytest.raises(ClientError) as exc:+ lam.get_function(FunctionName="lam-to-delete")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_lambda_invoke(lam):+ lam.create_function(+ FunctionName="lam-invoke-test",+ Runtime="python3.9",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(_LAMBDA_CODE)},+ )+ resp = lam.invoke(+ FunctionName="lam-invoke-test",+ Payload=json.dumps({"hello": "world"}),+ )+ assert resp["StatusCode"] == 200+ payload = json.loads(resp["Payload"].read())+ assert payload["statusCode"] == 200+ assert payload["body"] == "ok"+++def test_lambda_invoke_async(lam):+ resp = lam.invoke(+ FunctionName="lam-invoke-test",+ InvocationType="Event",+ Payload=json.dumps({"async": True}),+ )+ assert resp["StatusCode"] == 202+++def test_lambda_update_code(lam):+ lam.update_function_code(+ FunctionName="lam-invoke-test",+ ZipFile=_make_zip(_LAMBDA_CODE_V2),+ )+ resp = lam.invoke(+ FunctionName="lam-invoke-test",+ Payload=json.dumps({}),+ )+ payload = json.loads(resp["Payload"].read())+ assert payload["body"] == "v2"+++def test_lambda_update_config(lam):+ lam.update_function_configuration(+ FunctionName="lam-invoke-test",+ Handler="index.new_handler",+ Environment={"Variables": {"MY_VAR": "my_val"}},+ )+ resp = lam.get_function(FunctionName="lam-invoke-test")+ cfg = resp["Configuration"]+ assert cfg["Handler"] == "index.new_handler"+ assert cfg["Environment"]["Variables"]["MY_VAR"] == "my_val"++ lam.update_function_configuration(+ FunctionName="lam-invoke-test",+ Handler="index.handler",+ )+++def test_lambda_tags(lam):+ arn = lam.get_function(FunctionName="lam-invoke-test")["Configuration"]["FunctionArn"]+ lam.tag_resource(Resource=arn, Tags={"env": "test", "team": "backend"})+ resp = lam.list_tags(Resource=arn)+ assert resp["Tags"]["env"] == "test"+ assert resp["Tags"]["team"] == "backend"++ lam.untag_resource(Resource=arn, TagKeys=["team"])+ resp = lam.list_tags(Resource=arn)+ assert "team" not in resp["Tags"]+ assert resp["Tags"]["env"] == "test"+++def test_lambda_add_permission(lam):+ lam.add_permission(+ FunctionName="lam-invoke-test",+ StatementId="allow-s3",+ Action="lambda:InvokeFunction",+ Principal="s3.amazonaws.com",+ SourceArn="arn:aws:s3:::my-bucket",+ )+ resp = lam.get_policy(FunctionName="lam-invoke-test")+ policy = json.loads(resp["Policy"])+ sids = [s["Sid"] for s in policy["Statement"]]+ assert "allow-s3" in sids+++def test_lambda_list_versions(lam):+ resp = lam.list_versions_by_function(FunctionName="lam-invoke-test")+ versions = resp["Versions"]+ assert any(v["Version"] == "$LATEST" for v in versions)+++def test_lambda_publish_version(lam):+ resp = lam.publish_version(+ FunctionName="lam-invoke-test",+ Description="first published version",+ )+ assert resp["Version"] == "1"+ assert resp["Description"] == "first published version"+ assert "FunctionArn" in resp++ versions = lam.list_versions_by_function(FunctionName="lam-invoke-test")["Versions"]+ version_nums = [v["Version"] for v in versions]+ assert "$LATEST" in version_nums+ assert "1" in version_nums+++def test_lambda_esm_sqs_comprehensive(lam, sqs):+ try:+ lam.delete_function(FunctionName="esm-comp-func")+ except ClientError:+ pass++ code = (+ 'def handler(event, context):\n'+ ' return {"processed": len(event.get("Records", []))}\n'+ )+ lam.create_function(+ FunctionName="esm-comp-func",+ Runtime="python3.9",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(code)},+ )+ q_url = sqs.create_queue(QueueName="esm-comp-queue")["QueueUrl"]+ q_arn = sqs.get_queue_attributes(+ QueueUrl=q_url, AttributeNames=["QueueArn"],+ )["Attributes"]["QueueArn"]++ resp = lam.create_event_source_mapping(+ EventSourceArn=q_arn,+ FunctionName="esm-comp-func",+ BatchSize=5,+ Enabled=True,+ )+ esm_uuid = resp["UUID"]+ assert resp["State"] == "Enabled"+ assert resp["BatchSize"] == 5+ assert resp["EventSourceArn"] == q_arn++ got = lam.get_event_source_mapping(UUID=esm_uuid)+ assert got["UUID"] == esm_uuid++ listed = lam.list_event_source_mappings(FunctionName="esm-comp-func")+ assert any(e["UUID"] == esm_uuid for e in listed["EventSourceMappings"])++ lam.delete_event_source_mapping(UUID=esm_uuid)+++# ===================================================================+# IAM — comprehensive tests+# ===================================================================++def test_iam_create_user(iam):+ resp = iam.create_user(UserName="iam-test-user")+ user = resp["User"]+ assert user["UserName"] == "iam-test-user"+ assert "Arn" in user+ assert "UserId" in user+++def test_iam_get_user(iam):+ resp = iam.get_user(UserName="iam-test-user")+ assert resp["User"]["UserName"] == "iam-test-user"+++def test_iam_get_user_not_found(iam):+ with pytest.raises(ClientError) as exc:+ iam.get_user(UserName="ghost-user-xyz")+ assert exc.value.response["Error"]["Code"] == "NoSuchEntity"+++def test_iam_list_users(iam):+ resp = iam.list_users()+ names = [u["UserName"] for u in resp["Users"]]+ assert "iam-test-user" in names+++def test_iam_delete_user(iam):+ iam.create_user(UserName="iam-del-user")+ iam.delete_user(UserName="iam-del-user")+ with pytest.raises(ClientError) as exc:+ iam.get_user(UserName="iam-del-user")+ assert exc.value.response["Error"]["Code"] == "NoSuchEntity"+++def test_iam_create_role(iam):+ assume = json.dumps({+ "Version": "2012-10-17",+ "Statement": [{+ "Effect": "Allow",+ "Principal": {"Service": "lambda.amazonaws.com"},+ "Action": "sts:AssumeRole",+ }],+ })+ resp = iam.create_role(+ RoleName="iam-test-role",+ AssumeRolePolicyDocument=assume,+ Description="integration test role",+ )+ role = resp["Role"]+ assert role["RoleName"] == "iam-test-role"+ assert "Arn" in role+ assert "RoleId" in role+++def test_iam_get_role(iam):+ resp = iam.get_role(RoleName="iam-test-role")+ assert resp["Role"]["RoleName"] == "iam-test-role"+++def test_iam_list_roles(iam):+ resp = iam.list_roles()+ names = [r["RoleName"] for r in resp["Roles"]]+ assert "iam-test-role" in names+++def test_iam_delete_role(iam):+ assume = json.dumps({"Version": "2012-10-17", "Statement": []})+ iam.create_role(RoleName="iam-del-role", AssumeRolePolicyDocument=assume)+ iam.delete_role(RoleName="iam-del-role")+ with pytest.raises(ClientError) as exc:+ iam.get_role(RoleName="iam-del-role")+ assert exc.value.response["Error"]["Code"] == "NoSuchEntity"+++def test_iam_create_policy(iam):+ policy_doc = json.dumps({+ "Version": "2012-10-17",+ "Statement": [{+ "Effect": "Allow",+ "Action": "s3:GetObject",+ "Resource": "arn:aws:s3:::my-bucket/*",+ }],+ })+ resp = iam.create_policy(+ PolicyName="iam-test-policy",+ PolicyDocument=policy_doc,+ )+ pol = resp["Policy"]+ assert pol["PolicyName"] == "iam-test-policy"+ assert "Arn" in pol+ assert pol["DefaultVersionId"] == "v1"+++def test_iam_get_policy(iam):+ arn = f"arn:aws:iam::000000000000:policy/iam-test-policy"+ resp = iam.get_policy(PolicyArn=arn)+ assert resp["Policy"]["PolicyName"] == "iam-test-policy"+++def test_iam_attach_role_policy(iam):+ policy_arn = f"arn:aws:iam::000000000000:policy/iam-test-policy"+ iam.attach_role_policy(RoleName="iam-test-role", PolicyArn=policy_arn)+++def test_iam_list_attached_role_policies(iam):+ resp = iam.list_attached_role_policies(RoleName="iam-test-role")+ arns = [p["PolicyArn"] for p in resp["AttachedPolicies"]]+ assert f"arn:aws:iam::000000000000:policy/iam-test-policy" in arns+++def test_iam_detach_role_policy(iam):+ policy_arn = f"arn:aws:iam::000000000000:policy/iam-test-policy"+ iam.detach_role_policy(RoleName="iam-test-role", PolicyArn=policy_arn)+ resp = iam.list_attached_role_policies(RoleName="iam-test-role")+ arns = [p["PolicyArn"] for p in resp["AttachedPolicies"]]+ assert policy_arn not in arns+++def test_iam_put_role_policy(iam):+ inline_doc = json.dumps({+ "Version": "2012-10-17",+ "Statement": [{+ "Effect": "Allow",+ "Action": "logs:*",+ "Resource": "*",+ }],+ })+ iam.put_role_policy(+ RoleName="iam-test-role",+ PolicyName="inline-logs",+ PolicyDocument=inline_doc,+ )+++def test_iam_get_role_policy(iam):+ resp = iam.get_role_policy(RoleName="iam-test-role", PolicyName="inline-logs")+ assert resp["RoleName"] == "iam-test-role"+ assert resp["PolicyName"] == "inline-logs"+ doc = resp["PolicyDocument"]+ if isinstance(doc, str):+ doc = json.loads(doc)+ assert doc["Statement"][0]["Action"] == "logs:*"+++def test_iam_list_role_policies(iam):+ resp = iam.list_role_policies(RoleName="iam-test-role")+ assert "inline-logs" in resp["PolicyNames"]+++def test_iam_create_access_key(iam):+ resp = iam.create_access_key(UserName="iam-test-user")+ key = resp["AccessKey"]+ assert key["UserName"] == "iam-test-user"+ assert key["AccessKeyId"].startswith("AKIA")+ assert len(key["SecretAccessKey"]) > 0+ assert key["Status"] == "Active"+++def test_iam_instance_profile(iam):+ assume = json.dumps({"Version": "2012-10-17", "Statement": []})+ try:+ iam.create_role(RoleName="ip-role", AssumeRolePolicyDocument=assume)+ except ClientError:+ pass++ resp = iam.create_instance_profile(InstanceProfileName="test-ip")+ ip = resp["InstanceProfile"]+ assert ip["InstanceProfileName"] == "test-ip"+ assert "Arn" in ip++ iam.add_role_to_instance_profile(InstanceProfileName="test-ip", RoleName="ip-role")++ resp = iam.get_instance_profile(InstanceProfileName="test-ip")+ roles = resp["InstanceProfile"]["Roles"]+ assert any(r["RoleName"] == "ip-role" for r in roles)++ resp = iam.list_instance_profiles()+ names = [p["InstanceProfileName"] for p in resp["InstanceProfiles"]]+ assert "test-ip" in names++ iam.remove_role_from_instance_profile(InstanceProfileName="test-ip", RoleName="ip-role")+ iam.delete_instance_profile(InstanceProfileName="test-ip")+++# ===================================================================+# STS — comprehensive tests+# ===================================================================++def test_sts_get_caller_identity_full(sts):+ resp = sts.get_caller_identity()+ assert resp["Account"] == "000000000000"+ assert "Arn" in resp+ assert "UserId" in resp+++def test_sts_assume_role(sts):+ resp = sts.assume_role(+ RoleArn="arn:aws:iam::000000000000:role/iam-test-role",+ RoleSessionName="test-session",+ DurationSeconds=900,+ )+ creds = resp["Credentials"]+ assert creds["AccessKeyId"].startswith("ASIA")+ assert len(creds["SecretAccessKey"]) > 0+ assert len(creds["SessionToken"]) > 0+ assert "Expiration" in creds++ assumed = resp["AssumedRoleUser"]+ assert "test-session" in assumed["Arn"]+ assert "AssumedRoleId" in assumed+++# ===================================================================+# SecretsManager — comprehensive tests+# ===================================================================++def test_secrets_create_get_v2(sm):+ sm.create_secret(Name="sm-cg-v2", SecretString='{"user":"admin","pass":"s3cr3t"}')+ resp = sm.get_secret_value(SecretId="sm-cg-v2")+ parsed = json.loads(resp["SecretString"])+ assert parsed["user"] == "admin"+ assert parsed["pass"] == "s3cr3t"+ assert "VersionId" in resp+ assert "ARN" in resp++ sm.create_secret(Name="sm-cg-bin", SecretBinary=b"\x00\x01\x02")+ resp_bin = sm.get_secret_value(SecretId="sm-cg-bin")+ assert resp_bin["SecretBinary"] == b"\x00\x01\x02"+++def test_secrets_update_v2(sm):+ sm.create_secret(Name="sm-upd-v2", SecretString="original")+ sm.update_secret(SecretId="sm-upd-v2", SecretString="updated", Description="new desc")+ resp = sm.get_secret_value(SecretId="sm-upd-v2")+ assert resp["SecretString"] == "updated"+ desc = sm.describe_secret(SecretId="sm-upd-v2")+ assert desc["Description"] == "new desc"+++def test_secrets_list_v2(sm):+ sm.create_secret(Name="sm-list-a", SecretString="a")+ sm.create_secret(Name="sm-list-b", SecretString="b")+ listed = sm.list_secrets()+ names = [s["Name"] for s in listed["SecretList"]]+ assert "sm-list-a" in names+ assert "sm-list-b" in names+++def test_secrets_delete_v2(sm):+ sm.create_secret(Name="sm-del-v2", SecretString="gone")+ sm.delete_secret(SecretId="sm-del-v2", ForceDeleteWithoutRecovery=True)+ with pytest.raises(ClientError) as exc:+ sm.get_secret_value(SecretId="sm-del-v2")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_secrets_delete_with_recovery(sm):+ sm.create_secret(Name="sm-del-rec", SecretString="recoverable")+ sm.delete_secret(SecretId="sm-del-rec", RecoveryWindowInDays=7)+ with pytest.raises(ClientError) as exc:+ sm.get_secret_value(SecretId="sm-del-rec")+ assert "marked for deletion" in exc.value.response["Error"]["Message"].lower() or \+ exc.value.response["Error"]["Code"] == "InvalidRequestException"+ desc = sm.describe_secret(SecretId="sm-del-rec")+ assert "DeletedDate" in desc++ sm.restore_secret(SecretId="sm-del-rec")+ resp = sm.get_secret_value(SecretId="sm-del-rec")+ assert resp["SecretString"] == "recoverable"+++def test_secrets_put_value_version_stages_v2(sm):+ sm.create_secret(Name="sm-pvs-v2", SecretString="v1")+ sm.put_secret_value(SecretId="sm-pvs-v2", SecretString="v2")++ desc = sm.describe_secret(SecretId="sm-pvs-v2")+ stages = desc["VersionIdsToStages"]+ current_vids = [vid for vid, s in stages.items() if "AWSCURRENT" in s]+ previous_vids = [vid for vid, s in stages.items() if "AWSPREVIOUS" in s]+ assert len(current_vids) == 1+ assert len(previous_vids) == 1+ assert current_vids[0] != previous_vids[0]++ cur = sm.get_secret_value(SecretId="sm-pvs-v2", VersionStage="AWSCURRENT")+ assert cur["SecretString"] == "v2"+ prev = sm.get_secret_value(SecretId="sm-pvs-v2", VersionStage="AWSPREVIOUS")+ assert prev["SecretString"] == "v1"+++def test_secrets_describe_v2(sm):+ sm.create_secret(Name="sm-dsc-v2", SecretString="val", Description="detailed desc",+ Tags=[{"Key": "Env", "Value": "dev"}])+ resp = sm.describe_secret(SecretId="sm-dsc-v2")+ assert resp["Name"] == "sm-dsc-v2"+ assert resp["Description"] == "detailed desc"+ assert any(t["Key"] == "Env" for t in resp["Tags"])+ assert "VersionIdsToStages" in resp+ assert "ARN" in resp+++def test_secrets_tags_v2(sm):+ sm.create_secret(Name="sm-tag-v2", SecretString="val")+ sm.tag_resource(SecretId="sm-tag-v2", Tags=[{"Key": "team", "Value": "backend"}])+ sm.tag_resource(SecretId="sm-tag-v2", Tags=[{"Key": "env", "Value": "prod"}])++ desc = sm.describe_secret(SecretId="sm-tag-v2")+ assert any(t["Key"] == "team" and t["Value"] == "backend" for t in desc["Tags"])+ assert any(t["Key"] == "env" and t["Value"] == "prod" for t in desc["Tags"])++ sm.untag_resource(SecretId="sm-tag-v2", TagKeys=["team"])+ desc2 = sm.describe_secret(SecretId="sm-tag-v2")+ assert not any(t["Key"] == "team" for t in desc2.get("Tags", []))+ assert any(t["Key"] == "env" for t in desc2.get("Tags", []))+++def test_secrets_get_random_password_v2(sm):+ resp = sm.get_random_password(PasswordLength=32)+ assert len(resp["RandomPassword"]) == 32++ resp2 = sm.get_random_password(PasswordLength=20, ExcludeCharacters="aeiou")+ pw = resp2["RandomPassword"]+ assert len(pw) == 20+ for c in "aeiou":+ assert c not in pw+++# ===================================================================+# CloudWatch Logs — comprehensive tests+# ===================================================================++def test_logs_create_group_v2(logs):+ logs.create_log_group(logGroupName="/cwl/cg-v2")+ resp = logs.describe_log_groups(logGroupNamePrefix="/cwl/cg-v2")+ assert any(g["logGroupName"] == "/cwl/cg-v2" for g in resp["logGroups"])+++def test_logs_create_group_duplicate_v2(logs):+ logs.create_log_group(logGroupName="/cwl/dup-v2")+ with pytest.raises(ClientError) as exc:+ logs.create_log_group(logGroupName="/cwl/dup-v2")+ assert exc.value.response["Error"]["Code"] == "ResourceAlreadyExistsException"+++def test_logs_delete_group_v2(logs):+ logs.create_log_group(logGroupName="/cwl/del-v2")+ logs.delete_log_group(logGroupName="/cwl/del-v2")+ resp = logs.describe_log_groups(logGroupNamePrefix="/cwl/del-v2")+ assert not any(g["logGroupName"] == "/cwl/del-v2" for g in resp["logGroups"])+++def test_logs_describe_groups_v2(logs):+ logs.create_log_group(logGroupName="/cwl/dg-a")+ logs.create_log_group(logGroupName="/cwl/dg-b")+ resp = logs.describe_log_groups(logGroupNamePrefix="/cwl/dg-")+ names = [g["logGroupName"] for g in resp["logGroups"]]+ assert "/cwl/dg-a" in names+ assert "/cwl/dg-b" in names+++def test_logs_create_stream_v2(logs):+ logs.create_log_group(logGroupName="/cwl/str-v2")+ logs.create_log_stream(logGroupName="/cwl/str-v2", logStreamName="stream-a")+ logs.create_log_stream(logGroupName="/cwl/str-v2", logStreamName="stream-b")+ resp = logs.describe_log_streams(logGroupName="/cwl/str-v2")+ names = [s["logStreamName"] for s in resp["logStreams"]]+ assert "stream-a" in names+ assert "stream-b" in names+++def test_logs_put_get_events_v2(logs):+ logs.create_log_group(logGroupName="/cwl/pge-v2")+ logs.create_log_stream(logGroupName="/cwl/pge-v2", logStreamName="s1")+ now = int(time.time() * 1000)+ logs.put_log_events(+ logGroupName="/cwl/pge-v2", logStreamName="s1",+ logEvents=[+ {"timestamp": now, "message": "first line"},+ {"timestamp": now + 1, "message": "second line"},+ {"timestamp": now + 2, "message": "third line"},+ ],+ )+ resp = logs.get_log_events(logGroupName="/cwl/pge-v2", logStreamName="s1")+ assert len(resp["events"]) == 3+ assert resp["events"][0]["message"] == "first line"+ assert resp["events"][2]["message"] == "third line"+++def test_logs_filter_events_v2(logs):+ logs.create_log_group(logGroupName="/cwl/flt-v2")+ logs.create_log_stream(logGroupName="/cwl/flt-v2", logStreamName="s1")+ now = int(time.time() * 1000)+ logs.put_log_events(+ logGroupName="/cwl/flt-v2", logStreamName="s1",+ logEvents=[+ {"timestamp": now, "message": "ERROR disk full"},+ {"timestamp": now + 1, "message": "INFO all clear"},+ {"timestamp": now + 2, "message": "ERROR timeout"},+ ],+ )+ resp = logs.filter_log_events(logGroupName="/cwl/flt-v2", filterPattern="ERROR")+ assert len(resp["events"]) == 2+ msgs = [e["message"] for e in resp["events"]]+ assert "ERROR disk full" in msgs+ assert "ERROR timeout" in msgs+++def test_logs_retention_policy_v2(logs):+ logs.create_log_group(logGroupName="/cwl/ret-v2")+ logs.put_retention_policy(logGroupName="/cwl/ret-v2", retentionInDays=30)+ resp = logs.describe_log_groups(logGroupNamePrefix="/cwl/ret-v2")+ grp = next(g for g in resp["logGroups"] if g["logGroupName"] == "/cwl/ret-v2")+ assert grp["retentionInDays"] == 30++ logs.delete_retention_policy(logGroupName="/cwl/ret-v2")+ resp2 = logs.describe_log_groups(logGroupNamePrefix="/cwl/ret-v2")+ grp2 = next(g for g in resp2["logGroups"] if g["logGroupName"] == "/cwl/ret-v2")+ assert "retentionInDays" not in grp2+++def test_logs_tags_v2(logs):+ logs.create_log_group(logGroupName="/cwl/tag-v2", tags={"env": "prod"})+ resp = logs.list_tags_log_group(logGroupName="/cwl/tag-v2")+ assert resp["tags"]["env"] == "prod"++ logs.tag_log_group(logGroupName="/cwl/tag-v2", tags={"team": "infra"})+ resp2 = logs.list_tags_log_group(logGroupName="/cwl/tag-v2")+ assert resp2["tags"]["env"] == "prod"+ assert resp2["tags"]["team"] == "infra"++ logs.untag_log_group(logGroupName="/cwl/tag-v2", tags=["env"])+ resp3 = logs.list_tags_log_group(logGroupName="/cwl/tag-v2")+ assert "env" not in resp3["tags"]+ assert resp3["tags"]["team"] == "infra"+++def test_logs_put_requires_group_v2(logs):+ with pytest.raises(ClientError) as exc:+ logs.put_log_events(+ logGroupName="/cwl/nonexistent-xyz", logStreamName="s1",+ logEvents=[{"timestamp": int(time.time() * 1000), "message": "fail"}],+ )+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++# ===================================================================+# SSM — comprehensive tests+# ===================================================================++def test_ssm_put_get_v2(ssm):+ ssm.put_parameter(Name="/ssm2/pg/host", Value="db.local", Type="String")+ resp = ssm.get_parameter(Name="/ssm2/pg/host")+ assert resp["Parameter"]["Value"] == "db.local"+ assert resp["Parameter"]["Type"] == "String"+ assert resp["Parameter"]["Version"] == 1++ ssm.put_parameter(Name="/ssm2/pg/pass", Value="secret123", Type="SecureString")+ resp_enc = ssm.get_parameter(Name="/ssm2/pg/pass", WithDecryption=True)+ assert resp_enc["Parameter"]["Value"] == "secret123"+++def test_ssm_overwrite_version_v2(ssm):+ ssm.put_parameter(Name="/ssm2/ov/p", Value="v1", Type="String")+ r1 = ssm.get_parameter(Name="/ssm2/ov/p")+ assert r1["Parameter"]["Version"] == 1++ ssm.put_parameter(Name="/ssm2/ov/p", Value="v2", Type="String", Overwrite=True)+ r2 = ssm.get_parameter(Name="/ssm2/ov/p")+ assert r2["Parameter"]["Value"] == "v2"+ assert r2["Parameter"]["Version"] == 2++ ssm.put_parameter(Name="/ssm2/ov/p", Value="v3", Type="String", Overwrite=True)+ r3 = ssm.get_parameter(Name="/ssm2/ov/p")+ assert r3["Parameter"]["Version"] == 3+++def test_ssm_get_by_path_v2(ssm):+ ssm.put_parameter(Name="/ssm2/path/x", Value="vx", Type="String")+ ssm.put_parameter(Name="/ssm2/path/y", Value="vy", Type="String")+ ssm.put_parameter(Name="/ssm2/path/sub/z", Value="vz", Type="String")++ resp = ssm.get_parameters_by_path(Path="/ssm2/path", Recursive=True)+ names = [p["Name"] for p in resp["Parameters"]]+ assert "/ssm2/path/x" in names+ assert "/ssm2/path/y" in names+ assert "/ssm2/path/sub/z" in names++ resp_shallow = ssm.get_parameters_by_path(Path="/ssm2/path", Recursive=False)+ names_shallow = [p["Name"] for p in resp_shallow["Parameters"]]+ assert "/ssm2/path/x" in names_shallow+ assert "/ssm2/path/sub/z" not in names_shallow+++def test_ssm_get_parameters_multiple_v2(ssm):+ ssm.put_parameter(Name="/ssm2/multi/a", Value="va", Type="String")+ ssm.put_parameter(Name="/ssm2/multi/b", Value="vb", Type="String")+ resp = ssm.get_parameters(Names=["/ssm2/multi/a", "/ssm2/multi/b", "/ssm2/multi/nope"])+ assert len(resp["Parameters"]) == 2+ assert any(p["Name"] == "/ssm2/multi/a" for p in resp["Parameters"])+ assert any(p["Name"] == "/ssm2/multi/b" for p in resp["Parameters"])+ assert "/ssm2/multi/nope" in resp["InvalidParameters"]+++def test_ssm_delete_v2(ssm):+ ssm.put_parameter(Name="/ssm2/del/tmp", Value="bye", Type="String")+ ssm.delete_parameter(Name="/ssm2/del/tmp")+ with pytest.raises(ClientError) as exc:+ ssm.get_parameter(Name="/ssm2/del/tmp")+ assert exc.value.response["Error"]["Code"] == "ParameterNotFound"++ ssm.put_parameter(Name="/ssm2/del/b1", Value="v1", Type="String")+ ssm.put_parameter(Name="/ssm2/del/b2", Value="v2", Type="String")+ resp = ssm.delete_parameters(Names=["/ssm2/del/b1", "/ssm2/del/b2", "/ssm2/del/ghost"])+ assert len(resp["DeletedParameters"]) == 2+ assert "/ssm2/del/ghost" in resp["InvalidParameters"]+++def test_ssm_describe_v2(ssm):+ ssm.put_parameter(Name="/ssm2/desc/alpha", Value="va", Type="String", Description="alpha param")+ ssm.put_parameter(Name="/ssm2/desc/beta", Value="vb", Type="SecureString")+ resp = ssm.describe_parameters(+ ParameterFilters=[{"Key": "Name", "Option": "BeginsWith", "Values": ["/ssm2/desc/"]}]+ )+ names = [p["Name"] for p in resp["Parameters"]]+ assert "/ssm2/desc/alpha" in names+ assert "/ssm2/desc/beta" in names+++def test_ssm_parameter_history_v2(ssm):+ ssm.put_parameter(Name="/ssm2/hist/h", Value="h1", Type="String", Description="d1")+ ssm.put_parameter(Name="/ssm2/hist/h", Value="h2", Type="String", Overwrite=True, Description="d2")+ ssm.put_parameter(Name="/ssm2/hist/h", Value="h3", Type="String", Overwrite=True, Description="d3")+ resp = ssm.get_parameter_history(Name="/ssm2/hist/h")+ assert len(resp["Parameters"]) == 3+ assert resp["Parameters"][0]["Value"] == "h1"+ assert resp["Parameters"][0]["Version"] == 1+ assert resp["Parameters"][2]["Value"] == "h3"+ assert resp["Parameters"][2]["Version"] == 3+++def test_ssm_tags_v2(ssm):+ ssm.put_parameter(Name="/ssm2/tag/t1", Value="v", Type="String")+ ssm.add_tags_to_resource(+ ResourceType="Parameter", ResourceId="/ssm2/tag/t1",+ Tags=[{"Key": "team", "Value": "platform"}, {"Key": "env", "Value": "staging"}],+ )+ resp = ssm.list_tags_for_resource(ResourceType="Parameter", ResourceId="/ssm2/tag/t1")+ tag_map = {t["Key"]: t["Value"] for t in resp["TagList"]}+ assert tag_map["team"] == "platform"+ assert tag_map["env"] == "staging"++ ssm.remove_tags_from_resource(+ ResourceType="Parameter", ResourceId="/ssm2/tag/t1", TagKeys=["team"],+ )+ resp2 = ssm.list_tags_for_resource(ResourceType="Parameter", ResourceId="/ssm2/tag/t1")+ tag_map2 = {t["Key"]: t["Value"] for t in resp2["TagList"]}+ assert "team" not in tag_map2+ assert tag_map2["env"] == "staging"+++# ===================================================================+# EventBridge — comprehensive tests+# ===================================================================++def test_eb_create_event_bus_v2(eb):+ resp = eb.create_event_bus(Name="eb-bus-v2")+ assert "eb-bus-v2" in resp["EventBusArn"]+ buses = eb.list_event_buses()+ assert any(b["Name"] == "eb-bus-v2" for b in buses["EventBuses"])++ desc = eb.describe_event_bus(Name="eb-bus-v2")+ assert desc["Name"] == "eb-bus-v2"+++def test_eb_put_rule_v2(eb):+ eb.create_event_bus(Name="eb-rule-bus")+ resp = eb.put_rule(+ Name="eb-rule-v2", EventBusName="eb-rule-bus",+ EventPattern=json.dumps({"source": ["my.app"]}), State="ENABLED",+ )+ assert "RuleArn" in resp++ rules = eb.list_rules(EventBusName="eb-rule-bus")+ assert any(r["Name"] == "eb-rule-v2" for r in rules["Rules"])++ described = eb.describe_rule(Name="eb-rule-v2", EventBusName="eb-rule-bus")+ assert described["Name"] == "eb-rule-v2"+ assert described["State"] == "ENABLED"+++def test_eb_put_targets_v2(eb):+ eb.put_rule(Name="eb-tgt-v2", ScheduleExpression="rate(10 minutes)", State="ENABLED")+ eb.put_targets(Rule="eb-tgt-v2", Targets=[+ {"Id": "t1", "Arn": "arn:aws:lambda:us-east-1:000000000000:function:f1"},+ {"Id": "t2", "Arn": "arn:aws:sqs:us-east-1:000000000000:q1"},+ ])+ resp = eb.list_targets_by_rule(Rule="eb-tgt-v2")+ assert len(resp["Targets"]) == 2+ ids = {t["Id"] for t in resp["Targets"]}+ assert ids == {"t1", "t2"}+++def test_eb_list_targets_v2(eb):+ eb.put_rule(Name="eb-lt-v2", ScheduleExpression="rate(1 hour)", State="ENABLED")+ eb.put_targets(Rule="eb-lt-v2", Targets=[+ {"Id": "a", "Arn": "arn:aws:lambda:us-east-1:000000000000:function:fa"},+ ])+ resp = eb.list_targets_by_rule(Rule="eb-lt-v2")+ assert resp["Targets"][0]["Id"] == "a"+ assert "fa" in resp["Targets"][0]["Arn"]+++def test_eb_put_events_v2(eb):+ resp = eb.put_events(Entries=[+ {"Source": "app.v2", "DetailType": "Ev1", "Detail": json.dumps({"a": 1}), "EventBusName": "default"},+ {"Source": "app.v2", "DetailType": "Ev2", "Detail": json.dumps({"b": 2}), "EventBusName": "default"},+ {"Source": "app.v2", "DetailType": "Ev3", "Detail": json.dumps({"c": 3}), "EventBusName": "default"},+ ])+ assert resp["FailedEntryCount"] == 0+ assert len(resp["Entries"]) == 3+ assert all("EventId" in e for e in resp["Entries"])+++def test_eb_remove_targets_v2(eb):+ eb.put_rule(Name="eb-rm-v2", ScheduleExpression="rate(1 minute)", State="ENABLED")+ eb.put_targets(Rule="eb-rm-v2", Targets=[+ {"Id": "rm1", "Arn": "arn:aws:lambda:us-east-1:000000000000:function:f"},+ {"Id": "rm2", "Arn": "arn:aws:lambda:us-east-1:000000000000:function:g"},+ ])+ assert len(eb.list_targets_by_rule(Rule="eb-rm-v2")["Targets"]) == 2++ eb.remove_targets(Rule="eb-rm-v2", Ids=["rm1"])+ remaining = eb.list_targets_by_rule(Rule="eb-rm-v2")["Targets"]+ assert len(remaining) == 1+ assert remaining[0]["Id"] == "rm2"+++def test_eb_delete_rule_v2(eb):+ eb.put_rule(Name="eb-del-v2", ScheduleExpression="rate(1 day)", State="ENABLED")+ eb.delete_rule(Name="eb-del-v2")+ with pytest.raises(ClientError) as exc:+ eb.describe_rule(Name="eb-del-v2")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_eb_tags_v2(eb):+ resp = eb.put_rule(Name="eb-tag-v2", ScheduleExpression="rate(1 hour)", State="ENABLED")+ arn = resp["RuleArn"]+ eb.tag_resource(ResourceARN=arn, Tags=[+ {"Key": "stage", "Value": "dev"}, {"Key": "team", "Value": "ops"},+ ])+ tags = eb.list_tags_for_resource(ResourceARN=arn)["Tags"]+ tag_map = {t["Key"]: t["Value"] for t in tags}+ assert tag_map["stage"] == "dev"+ assert tag_map["team"] == "ops"++ eb.untag_resource(ResourceARN=arn, TagKeys=["stage"])+ tags2 = eb.list_tags_for_resource(ResourceARN=arn)["Tags"]+ assert not any(t["Key"] == "stage" for t in tags2)+ assert any(t["Key"] == "team" for t in tags2)+++# ===================================================================+# Kinesis — comprehensive tests+# ===================================================================++def test_kinesis_create_stream_v2(kin):+ kin.create_stream(StreamName="kin-cs-v2", ShardCount=2)+ desc = kin.describe_stream(StreamName="kin-cs-v2")+ sd = desc["StreamDescription"]+ assert sd["StreamName"] == "kin-cs-v2"+ assert sd["StreamStatus"] == "ACTIVE"+ assert len(sd["Shards"]) == 2+++def test_kinesis_put_get_records_v2(kin):+ kin.create_stream(StreamName="kin-pgr-v2", ShardCount=1)+ kin.put_record(StreamName="kin-pgr-v2", Data=b"rec1", PartitionKey="pk1")+ kin.put_record(StreamName="kin-pgr-v2", Data=b"rec2", PartitionKey="pk2")+ kin.put_record(StreamName="kin-pgr-v2", Data=b"rec3", PartitionKey="pk3")++ desc = kin.describe_stream(StreamName="kin-pgr-v2")+ shard_id = desc["StreamDescription"]["Shards"][0]["ShardId"]+ it = kin.get_shard_iterator(+ StreamName="kin-pgr-v2", ShardId=shard_id, ShardIteratorType="TRIM_HORIZON",+ )+ records = kin.get_records(ShardIterator=it["ShardIterator"])+ assert len(records["Records"]) == 3+ assert records["Records"][0]["Data"] == b"rec1"+++def test_kinesis_put_records_batch_v2(kin):+ kin.create_stream(StreamName="kin-batch-v2", ShardCount=1)+ resp = kin.put_records(+ StreamName="kin-batch-v2",+ Records=[{"Data": f"b{i}".encode(), "PartitionKey": f"pk{i}"} for i in range(7)],+ )+ assert resp["FailedRecordCount"] == 0+ assert len(resp["Records"]) == 7+ for r in resp["Records"]:+ assert "ShardId" in r+ assert "SequenceNumber" in r+++def test_kinesis_list_streams_v2(kin):+ kin.create_stream(StreamName="kin-ls-v2a", ShardCount=1)+ kin.create_stream(StreamName="kin-ls-v2b", ShardCount=1)+ resp = kin.list_streams()+ assert "kin-ls-v2a" in resp["StreamNames"]+ assert "kin-ls-v2b" in resp["StreamNames"]+++def test_kinesis_list_shards_v2(kin):+ kin.create_stream(StreamName="kin-lsh-v2", ShardCount=3)+ resp = kin.list_shards(StreamName="kin-lsh-v2")+ assert len(resp["Shards"]) == 3+ for shard in resp["Shards"]:+ assert "ShardId" in shard+ assert "HashKeyRange" in shard+++def test_kinesis_describe_stream_v2(kin):+ kin.create_stream(StreamName="kin-desc-v2", ShardCount=1)+ resp = kin.describe_stream(StreamName="kin-desc-v2")+ sd = resp["StreamDescription"]+ assert sd["StreamName"] == "kin-desc-v2"+ assert sd["RetentionPeriodHours"] == 24+ assert "StreamARN" in sd+ assert len(sd["Shards"]) == 1++ summary = kin.describe_stream_summary(StreamName="kin-desc-v2")+ assert summary["StreamDescriptionSummary"]["StreamName"] == "kin-desc-v2"+++def test_kinesis_tags_v2(kin):+ kin.create_stream(StreamName="kin-tag-v2", ShardCount=1)+ kin.add_tags_to_stream(StreamName="kin-tag-v2", Tags={"env": "test", "team": "data"})+ resp = kin.list_tags_for_stream(StreamName="kin-tag-v2")+ tag_map = {t["Key"]: t["Value"] for t in resp["Tags"]}+ assert tag_map["env"] == "test"+ assert tag_map["team"] == "data"++ kin.remove_tags_from_stream(StreamName="kin-tag-v2", TagKeys=["team"])+ resp2 = kin.list_tags_for_stream(StreamName="kin-tag-v2")+ tag_map2 = {t["Key"]: t["Value"] for t in resp2["Tags"]}+ assert "team" not in tag_map2+ assert tag_map2["env"] == "test"+++def test_kinesis_delete_stream_v2(kin):+ kin.create_stream(StreamName="kin-del-v2", ShardCount=1)+ kin.delete_stream(StreamName="kin-del-v2")+ with pytest.raises(ClientError) as exc:+ kin.describe_stream(StreamName="kin-del-v2")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++# ===================================================================+# CloudWatch — comprehensive tests+# ===================================================================++def test_cw_put_list_metrics_v2(cw):+ cw.put_metric_data(+ Namespace="CWv2",+ MetricData=[+ {"MetricName": "Reqs", "Value": 100.0, "Unit": "Count",+ "Dimensions": [{"Name": "API", "Value": "/users"}]},+ {"MetricName": "Errs", "Value": 5.0, "Unit": "Count"},+ ],+ )+ resp = cw.list_metrics(Namespace="CWv2")+ names = [m["MetricName"] for m in resp["Metrics"]]+ assert "Reqs" in names+ assert "Errs" in names++ resp_filtered = cw.list_metrics(Namespace="CWv2", MetricName="Reqs")+ assert all(m["MetricName"] == "Reqs" for m in resp_filtered["Metrics"])+++def test_cw_get_metric_statistics_v2(cw):+ cw.put_metric_data(+ Namespace="CWStat2",+ MetricData=[+ {"MetricName": "Duration", "Value": 100.0, "Unit": "Milliseconds"},+ {"MetricName": "Duration", "Value": 200.0, "Unit": "Milliseconds"},+ ],+ )+ resp = cw.get_metric_statistics(+ Namespace="CWStat2", MetricName="Duration", Period=60,+ StartTime=time.time() - 600, EndTime=time.time() + 600,+ Statistics=["Average", "Sum", "SampleCount", "Minimum", "Maximum"],+ )+ assert len(resp["Datapoints"]) >= 1+ dp = resp["Datapoints"][0]+ assert "Average" in dp+ assert "Sum" in dp+ assert "SampleCount" in dp+ assert "Minimum" in dp+ assert "Maximum" in dp+++def test_cw_put_metric_alarm_v2(cw):+ cw.put_metric_alarm(+ AlarmName="cw-v2-high-err", MetricName="Errors", Namespace="CWv2Alarms",+ Statistic="Sum", Period=300, EvaluationPeriods=2,+ Threshold=10.0, ComparisonOperator="GreaterThanOrEqualToThreshold",+ AlarmActions=["arn:aws:sns:us-east-1:000000000000:alarm-topic"],+ AlarmDescription="Fires when errors >= 10",+ )+ resp = cw.describe_alarms(AlarmNames=["cw-v2-high-err"])+ alarm = resp["MetricAlarms"][0]+ assert alarm["AlarmName"] == "cw-v2-high-err"+ assert alarm["Threshold"] == 10.0+ assert alarm["ComparisonOperator"] == "GreaterThanOrEqualToThreshold"+ assert alarm["EvaluationPeriods"] == 2+++def test_cw_describe_alarms_v2(cw):+ for i in range(3):+ cw.put_metric_alarm(+ AlarmName=f"cw-da-v2-{i}", MetricName="M", Namespace="N",+ Statistic="Sum", Period=60, EvaluationPeriods=1,+ Threshold=float(i), ComparisonOperator="GreaterThanThreshold",+ )+ resp = cw.describe_alarms(AlarmNamePrefix="cw-da-v2-")+ names = [a["AlarmName"] for a in resp["MetricAlarms"]]+ for i in range(3):+ assert f"cw-da-v2-{i}" in names+++def test_cw_delete_alarms_v2(cw):+ cw.put_metric_alarm(+ AlarmName="cw-del-v2", MetricName="M", Namespace="N",+ Statistic="Sum", Period=60, EvaluationPeriods=1,+ Threshold=1.0, ComparisonOperator="GreaterThanThreshold",+ )+ cw.delete_alarms(AlarmNames=["cw-del-v2"])+ resp = cw.describe_alarms(AlarmNames=["cw-del-v2"])+ assert len(resp["MetricAlarms"]) == 0+++def test_cw_set_alarm_state_v2(cw):+ cw.put_metric_alarm(+ AlarmName="cw-state-v2", MetricName="M", Namespace="N",+ Statistic="Sum", Period=60, EvaluationPeriods=1,+ Threshold=1.0, ComparisonOperator="GreaterThanThreshold",+ )+ initial = cw.describe_alarms(AlarmNames=["cw-state-v2"])["MetricAlarms"][0]+ assert initial["StateValue"] == "INSUFFICIENT_DATA"++ cw.set_alarm_state(+ AlarmName="cw-state-v2", StateValue="ALARM",+ StateReason="Manual trigger for testing",+ )+ after = cw.describe_alarms(AlarmNames=["cw-state-v2"])["MetricAlarms"][0]+ assert after["StateValue"] == "ALARM"+ assert after["StateReason"] == "Manual trigger for testing"+++def test_cw_get_metric_data_v2(cw):+ cw.put_metric_data(+ Namespace="CWData2",+ MetricData=[{"MetricName": "Hits", "Value": 42.0, "Unit": "Count"}],+ )+ resp = cw.get_metric_data(+ MetricDataQueries=[{+ "Id": "q1",+ "MetricStat": {+ "Metric": {"Namespace": "CWData2", "MetricName": "Hits"},+ "Period": 60, "Stat": "Sum",+ },+ "ReturnData": True,+ }],+ StartTime=time.time() - 600, EndTime=time.time() + 600,+ )+ assert len(resp["MetricDataResults"]) == 1+ assert resp["MetricDataResults"][0]["Id"] == "q1"+ assert resp["MetricDataResults"][0]["StatusCode"] == "Complete"+ assert len(resp["MetricDataResults"][0]["Values"]) >= 1+++def test_cw_tags_v2(cw):+ cw.put_metric_alarm(+ AlarmName="cw-tag-v2", MetricName="M", Namespace="N",+ Statistic="Sum", Period=60, EvaluationPeriods=1,+ Threshold=1.0, ComparisonOperator="GreaterThanThreshold",+ )+ arn = cw.describe_alarms(AlarmNames=["cw-tag-v2"])["MetricAlarms"][0]["AlarmArn"]+ cw.tag_resource(ResourceARN=arn, Tags=[+ {"Key": "env", "Value": "prod"}, {"Key": "team", "Value": "sre"},+ ])+ resp = cw.list_tags_for_resource(ResourceARN=arn)+ tag_map = {t["Key"]: t["Value"] for t in resp["Tags"]}+ assert tag_map["env"] == "prod"+ assert tag_map["team"] == "sre"++ cw.untag_resource(ResourceARN=arn, TagKeys=["env"])+ resp2 = cw.list_tags_for_resource(ResourceARN=arn)+ assert not any(t["Key"] == "env" for t in resp2["Tags"])+ assert any(t["Key"] == "team" for t in resp2["Tags"])+++# ===================================================================+# SES — comprehensive tests+# ===================================================================++def test_ses_verify_identity_v2(ses):+ ses.verify_email_identity(EmailAddress="[email protected]")+ identities = ses.list_identities()["Identities"]+ assert "[email protected]" in identities++ attrs = ses.get_identity_verification_attributes(Identities=["[email protected]"])+ assert "[email protected]" in attrs["VerificationAttributes"]+ assert attrs["VerificationAttributes"]["[email protected]"]["VerificationStatus"] == "Success"+++def test_ses_send_email_v2(ses):+ ses.verify_email_identity(EmailAddress="[email protected]")+ resp = ses.send_email(+ Source="[email protected]",+ Destination={"ToAddresses": ["[email protected]"], "CcAddresses": ["[email protected]"]},+ Message={"Subject": {"Data": "Test V2"}, "Body": {"Text": {"Data": "Body v2"}}},+ )+ assert "MessageId" in resp+++def test_ses_list_identities_v2(ses):+ ses.verify_email_identity(EmailAddress="[email protected]")+ ses.verify_domain_identity(Domain="example-v2.com")+ email_ids = ses.list_identities(IdentityType="EmailAddress")["Identities"]+ assert "[email protected]" in email_ids+ domain_ids = ses.list_identities(IdentityType="Domain")["Identities"]+ assert "example-v2.com" in domain_ids+++def test_ses_quota_v2(ses):+ resp = ses.get_send_quota()+ assert resp["Max24HourSend"] == 50000.0+ assert resp["MaxSendRate"] == 14.0+ assert "SentLast24Hours" in resp+++def test_ses_send_raw_email_v2(ses):+ ses.verify_email_identity(EmailAddress="[email protected]")+ raw = (+ "From: [email protected]\r\n"+ "To: [email protected]\r\n"+ "Subject: Raw V2\r\n"+ "Content-Type: text/plain\r\n\r\n"+ "Raw body v2"+ )+ resp = ses.send_raw_email(RawMessage={"Data": raw})+ assert "MessageId" in resp+++def test_ses_configuration_set_v2(ses):+ ses.create_configuration_set(ConfigurationSet={"Name": "ses-cs-v2"})+ listed = ses.list_configuration_sets()["ConfigurationSets"]+ assert any(cs["Name"] == "ses-cs-v2" for cs in listed)++ described = ses.describe_configuration_set(ConfigurationSetName="ses-cs-v2")+ assert described["ConfigurationSet"]["Name"] == "ses-cs-v2"++ ses.delete_configuration_set(ConfigurationSetName="ses-cs-v2")+ listed2 = ses.list_configuration_sets()["ConfigurationSets"]+ assert not any(cs["Name"] == "ses-cs-v2" for cs in listed2)+++def test_ses_template_v2(ses):+ ses.create_template(Template={+ "TemplateName": "ses-tpl-v2",+ "SubjectPart": "Hello {{name}}",+ "TextPart": "Hi {{name}}, order #{{oid}}",+ "HtmlPart": "<h1>Hi {{name}}</h1>",+ })+ resp = ses.get_template(TemplateName="ses-tpl-v2")+ assert resp["Template"]["TemplateName"] == "ses-tpl-v2"+ assert "{{name}}" in resp["Template"]["SubjectPart"]++ listed = ses.list_templates()["TemplatesMetadata"]+ assert any(t["Name"] == "ses-tpl-v2" for t in listed)++ ses.update_template(Template={+ "TemplateName": "ses-tpl-v2", "SubjectPart": "Updated {{name}}",+ "TextPart": "Updated", "HtmlPart": "<p>Updated</p>",+ })+ resp2 = ses.get_template(TemplateName="ses-tpl-v2")+ assert "Updated" in resp2["Template"]["SubjectPart"]++ ses.delete_template(TemplateName="ses-tpl-v2")+ with pytest.raises(ClientError):+ ses.get_template(TemplateName="ses-tpl-v2")+++def test_ses_send_templated_v2(ses):+ ses.verify_email_identity(EmailAddress="[email protected]")+ ses.create_template(Template={+ "TemplateName": "ses-tpl-send-v2",+ "SubjectPart": "Hey {{name}}",+ "TextPart": "Hi {{name}}",+ "HtmlPart": "<h1>Hi {{name}}</h1>",+ })+ resp = ses.send_templated_email(+ Source="[email protected]",+ Destination={"ToAddresses": ["[email protected]"]},+ Template="ses-tpl-send-v2",+ TemplateData=json.dumps({"name": "Alice"}),+ )+ assert "MessageId" in resp+++# ===================================================================+# Step Functions — comprehensive tests+# ===================================================================++def test_sfn_create_state_machine_v2(sfn):+ definition = json.dumps({+ "StartAt": "Init",+ "States": {"Init": {"Type": "Pass", "Result": "ok", "End": True}},+ })+ resp = sfn.create_state_machine(+ name="sfn-csm-v2", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/R",+ )+ assert "stateMachineArn" in resp+ assert "sfn-csm-v2" in resp["stateMachineArn"]+++def test_sfn_list_state_machines_v2(sfn):+ definition = json.dumps({+ "StartAt": "X", "States": {"X": {"Type": "Pass", "End": True}},+ })+ sfn.create_state_machine(+ name="sfn-ls-v2a", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/R",+ )+ sfn.create_state_machine(+ name="sfn-ls-v2b", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/R",+ )+ resp = sfn.list_state_machines()+ names = [m["name"] for m in resp["stateMachines"]]+ assert "sfn-ls-v2a" in names+ assert "sfn-ls-v2b" in names+++def test_sfn_describe_state_machine_v2(sfn):+ definition = json.dumps({+ "StartAt": "D", "States": {"D": {"Type": "Pass", "End": True}},+ })+ create = sfn.create_state_machine(+ name="sfn-desc-v2", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/R",+ )+ resp = sfn.describe_state_machine(stateMachineArn=create["stateMachineArn"])+ assert resp["name"] == "sfn-desc-v2"+ assert resp["status"] == "ACTIVE"+ assert resp["definition"] == definition+ assert resp["roleArn"] == "arn:aws:iam::000000000000:role/R"+++def test_sfn_start_execution_pass_v2(sfn):+ definition = json.dumps({+ "StartAt": "P",+ "States": {"P": {"Type": "Pass", "Result": {"msg": "done"}, "End": True}},+ })+ sm = sfn.create_state_machine(+ name="sfn-pass-v2", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/R",+ )+ ex = sfn.start_execution(stateMachineArn=sm["stateMachineArn"], input='{}')+ for _ in range(50):+ time.sleep(0.1)+ desc = sfn.describe_execution(executionArn=ex["executionArn"])+ if desc["status"] != "RUNNING":+ break+ assert desc["status"] == "SUCCEEDED"+ assert json.loads(desc["output"]) == {"msg": "done"}+++def test_sfn_execution_choice_v2(sfn):+ definition = json.dumps({+ "StartAt": "Check",+ "States": {+ "Check": {+ "Type": "Choice",+ "Choices": [+ {"Variable": "$.x", "NumericEquals": 1, "Next": "One"},+ {"Variable": "$.x", "NumericGreaterThan": 1, "Next": "Many"},+ ],+ "Default": "Zero",+ },+ "One": {"Type": "Pass", "Result": "one", "End": True},+ "Many": {"Type": "Pass", "Result": "many", "End": True},+ "Zero": {"Type": "Pass", "Result": "zero", "End": True},+ },+ })+ sm = sfn.create_state_machine(+ name="sfn-choice-v2", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/R",+ )+ arn = sm["stateMachineArn"]++ ex1 = sfn.start_execution(stateMachineArn=arn, input='{"x":1}')+ for _ in range(50):+ time.sleep(0.1)+ d1 = sfn.describe_execution(executionArn=ex1["executionArn"])+ if d1["status"] != "RUNNING":+ break+ assert d1["status"] == "SUCCEEDED"+ assert json.loads(d1["output"]) == "one"++ ex2 = sfn.start_execution(stateMachineArn=arn, input='{"x":5}')+ for _ in range(50):+ time.sleep(0.1)+ d2 = sfn.describe_execution(executionArn=ex2["executionArn"])+ if d2["status"] != "RUNNING":+ break+ assert d2["status"] == "SUCCEEDED"+ assert json.loads(d2["output"]) == "many"++ ex3 = sfn.start_execution(stateMachineArn=arn, input='{"x":0}')+ for _ in range(50):+ time.sleep(0.1)+ d3 = sfn.describe_execution(executionArn=ex3["executionArn"])+ if d3["status"] != "RUNNING":+ break+ assert d3["status"] == "SUCCEEDED"+ assert json.loads(d3["output"]) == "zero"+++def test_sfn_stop_execution_v2(sfn):+ definition = json.dumps({+ "StartAt": "W", "States": {"W": {"Type": "Wait", "Seconds": 120, "End": True}},+ })+ sm = sfn.create_state_machine(+ name="sfn-stop-v2", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/R",+ )+ ex = sfn.start_execution(stateMachineArn=sm["stateMachineArn"])+ time.sleep(0.3)+ sfn.stop_execution(executionArn=ex["executionArn"], error="UserAbort", cause="test stop")+ desc = sfn.describe_execution(executionArn=ex["executionArn"])+ assert desc["status"] == "ABORTED"+++def test_sfn_get_execution_history_v2(sfn):+ definition = json.dumps({+ "StartAt": "A",+ "States": {"A": {"Type": "Pass", "Next": "B"}, "B": {"Type": "Pass", "End": True}},+ })+ sm = sfn.create_state_machine(+ name="sfn-hist-v2", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/R",+ )+ ex = sfn.start_execution(stateMachineArn=sm["stateMachineArn"], input='{}')+ for _ in range(50):+ time.sleep(0.1)+ desc = sfn.describe_execution(executionArn=ex["executionArn"])+ if desc["status"] != "RUNNING":+ break+ assert desc["status"] == "SUCCEEDED"++ history = sfn.get_execution_history(executionArn=ex["executionArn"])+ types = [e["type"] for e in history["events"]]+ assert "ExecutionStarted" in types+ assert "ExecutionSucceeded" in types+ assert any("Pass" in t for t in types)+++def test_sfn_tags_v2(sfn):+ definition = json.dumps({+ "StartAt": "T", "States": {"T": {"Type": "Pass", "End": True}},+ })+ sm = sfn.create_state_machine(+ name="sfn-tag-v2", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/R",+ tags=[{"key": "init", "value": "yes"}],+ )+ arn = sm["stateMachineArn"]+ tags = sfn.list_tags_for_resource(resourceArn=arn)["tags"]+ assert any(t["key"] == "init" and t["value"] == "yes" for t in tags)++ sfn.tag_resource(resourceArn=arn, tags=[{"key": "env", "value": "test"}])+ tags2 = sfn.list_tags_for_resource(resourceArn=arn)["tags"]+ assert any(t["key"] == "env" for t in tags2)++ sfn.untag_resource(resourceArn=arn, tagKeys=["init"])+ tags3 = sfn.list_tags_for_resource(resourceArn=arn)["tags"]+ assert not any(t["key"] == "init" for t in tags3)+ assert any(t["key"] == "env" for t in tags3)+++# ===================================================================+# ECS — comprehensive tests+# ===================================================================++def test_ecs_create_cluster_v2(ecs):+ resp = ecs.create_cluster(clusterName="ecs-cc-v2")+ assert resp["cluster"]["clusterName"] == "ecs-cc-v2"+ assert resp["cluster"]["status"] == "ACTIVE"+ assert "clusterArn" in resp["cluster"]+++def test_ecs_list_clusters_v2(ecs):+ ecs.create_cluster(clusterName="ecs-lc-v2a")+ ecs.create_cluster(clusterName="ecs-lc-v2b")+ resp = ecs.list_clusters()+ arns = resp["clusterArns"]+ assert any("ecs-lc-v2a" in a for a in arns)+ assert any("ecs-lc-v2b" in a for a in arns)+++def test_ecs_register_task_def_v2(ecs):+ resp = ecs.register_task_definition(+ family="ecs-td-v2",+ containerDefinitions=[+ {"name": "web", "image": "nginx:alpine", "cpu": 256, "memory": 512,+ "portMappings": [{"containerPort": 80, "hostPort": 8080}]},+ {"name": "sidecar", "image": "envoy:latest", "cpu": 128, "memory": 256},+ ],+ requiresCompatibilities=["EC2"], cpu="512", memory="1024",+ )+ td = resp["taskDefinition"]+ assert td["family"] == "ecs-td-v2"+ assert td["revision"] == 1+ assert td["status"] == "ACTIVE"+ assert len(td["containerDefinitions"]) == 2++ resp2 = ecs.register_task_definition(+ family="ecs-td-v2",+ containerDefinitions=[{"name": "web", "image": "nginx:latest", "cpu": 256, "memory": 512}],+ )+ assert resp2["taskDefinition"]["revision"] == 2+++def test_ecs_list_task_defs_v2(ecs):+ ecs.register_task_definition(+ family="ecs-ltd-v2",+ containerDefinitions=[{"name": "app", "image": "img", "cpu": 64, "memory": 128}],+ )+ resp = ecs.list_task_definitions(familyPrefix="ecs-ltd-v2")+ assert len(resp["taskDefinitionArns"]) >= 1+ assert all("ecs-ltd-v2" in a for a in resp["taskDefinitionArns"])+++def test_ecs_create_service_v2(ecs):+ ecs.create_cluster(clusterName="ecs-svc-v2c")+ ecs.register_task_definition(+ family="ecs-svc-v2td",+ containerDefinitions=[{"name": "w", "image": "nginx", "cpu": 64, "memory": 128}],+ )+ resp = ecs.create_service(+ cluster="ecs-svc-v2c", serviceName="ecs-svc-v2",+ taskDefinition="ecs-svc-v2td", desiredCount=2,+ )+ svc = resp["service"]+ assert svc["serviceName"] == "ecs-svc-v2"+ assert svc["status"] == "ACTIVE"+ assert svc["desiredCount"] == 2+++def test_ecs_describe_services_v2(ecs):+ ecs.create_cluster(clusterName="ecs-ds-v2c")+ ecs.register_task_definition(+ family="ecs-ds-v2td",+ containerDefinitions=[{"name": "w", "image": "nginx", "cpu": 64, "memory": 128}],+ )+ ecs.create_service(+ cluster="ecs-ds-v2c", serviceName="ecs-ds-v2a",+ taskDefinition="ecs-ds-v2td", desiredCount=1,+ )+ ecs.create_service(+ cluster="ecs-ds-v2c", serviceName="ecs-ds-v2b",+ taskDefinition="ecs-ds-v2td", desiredCount=3,+ )+ resp = ecs.describe_services(cluster="ecs-ds-v2c", services=["ecs-ds-v2a", "ecs-ds-v2b"])+ assert len(resp["services"]) == 2+ svc_map = {s["serviceName"]: s for s in resp["services"]}+ assert svc_map["ecs-ds-v2a"]["desiredCount"] == 1+ assert svc_map["ecs-ds-v2b"]["desiredCount"] == 3+++def test_ecs_update_service_v2(ecs):+ ecs.create_cluster(clusterName="ecs-us-v2c")+ ecs.register_task_definition(+ family="ecs-us-v2td",+ containerDefinitions=[{"name": "w", "image": "nginx", "cpu": 64, "memory": 128}],+ )+ ecs.create_service(+ cluster="ecs-us-v2c", serviceName="ecs-us-v2",+ taskDefinition="ecs-us-v2td", desiredCount=1,+ )+ ecs.update_service(cluster="ecs-us-v2c", service="ecs-us-v2", desiredCount=5)+ resp = ecs.describe_services(cluster="ecs-us-v2c", services=["ecs-us-v2"])+ assert resp["services"][0]["desiredCount"] == 5+++def test_ecs_tags_v2(ecs):+ resp = ecs.create_cluster(+ clusterName="ecs-tag-v2c",+ tags=[{"key": "env", "value": "staging"}],+ )+ arn = resp["cluster"]["clusterArn"]++ tags = ecs.list_tags_for_resource(resourceArn=arn)["tags"]+ assert any(t["key"] == "env" and t["value"] == "staging" for t in tags)++ ecs.tag_resource(resourceArn=arn, tags=[{"key": "team", "value": "platform"}])+ tags2 = ecs.list_tags_for_resource(resourceArn=arn)["tags"]+ tag_map = {t["key"]: t["value"] for t in tags2}+ assert tag_map["env"] == "staging"+ assert tag_map["team"] == "platform"++ ecs.untag_resource(resourceArn=arn, tagKeys=["env"])+ tags3 = ecs.list_tags_for_resource(resourceArn=arn)["tags"]+ assert not any(t["key"] == "env" for t in tags3)+ assert any(t["key"] == "team" for t in tags3)+++# ===================================================================+# RDS — comprehensive tests+# ===================================================================++def test_rds_create_instance_v2(rds):+ resp = rds.create_db_instance(+ DBInstanceIdentifier="rds-ci-v2", DBInstanceClass="db.t3.micro",+ Engine="postgres", MasterUsername="admin", MasterUserPassword="pass123",+ AllocatedStorage=20, DBName="mydb",+ )+ inst = resp["DBInstance"]+ assert inst["DBInstanceIdentifier"] == "rds-ci-v2"+ assert inst["DBInstanceStatus"] == "available"+ assert inst["Engine"] == "postgres"+ assert "Address" in inst["Endpoint"]+ assert "Port" in inst["Endpoint"]+++def test_rds_describe_instances_v2(rds):+ rds.create_db_instance(+ DBInstanceIdentifier="rds-di-v2a", DBInstanceClass="db.t3.micro",+ Engine="mysql", MasterUsername="admin", MasterUserPassword="pass",+ AllocatedStorage=10,+ )+ rds.create_db_instance(+ DBInstanceIdentifier="rds-di-v2b", DBInstanceClass="db.t3.small",+ Engine="postgres", MasterUsername="admin", MasterUserPassword="pass",+ AllocatedStorage=20,+ )+ resp = rds.describe_db_instances()+ ids = [i["DBInstanceIdentifier"] for i in resp["DBInstances"]]+ assert "rds-di-v2a" in ids+ assert "rds-di-v2b" in ids++ resp2 = rds.describe_db_instances(DBInstanceIdentifier="rds-di-v2a")+ assert len(resp2["DBInstances"]) == 1+ assert resp2["DBInstances"][0]["Engine"] == "mysql"+++def test_rds_delete_instance_v2(rds):+ rds.create_db_instance(+ DBInstanceIdentifier="rds-del-v2", DBInstanceClass="db.t3.micro",+ Engine="postgres", MasterUsername="admin", MasterUserPassword="pass",+ AllocatedStorage=10,+ )+ rds.delete_db_instance(DBInstanceIdentifier="rds-del-v2", SkipFinalSnapshot=True)+ with pytest.raises(ClientError) as exc:+ rds.describe_db_instances(DBInstanceIdentifier="rds-del-v2")+ assert exc.value.response["Error"]["Code"] == "DBInstanceNotFound"+++def test_rds_modify_instance_v2(rds):+ rds.create_db_instance(+ DBInstanceIdentifier="rds-mod-v2", DBInstanceClass="db.t3.micro",+ Engine="postgres", MasterUsername="admin", MasterUserPassword="pass",+ AllocatedStorage=20,+ )+ rds.modify_db_instance(+ DBInstanceIdentifier="rds-mod-v2",+ DBInstanceClass="db.t3.small", AllocatedStorage=50,+ ApplyImmediately=True,+ )+ resp = rds.describe_db_instances(DBInstanceIdentifier="rds-mod-v2")+ inst = resp["DBInstances"][0]+ assert inst["DBInstanceClass"] == "db.t3.small"+ assert inst["AllocatedStorage"] == 50+++def test_rds_create_cluster_v2(rds):+ resp = rds.create_db_cluster(+ DBClusterIdentifier="rds-cc-v2", Engine="aurora-postgresql",+ MasterUsername="admin", MasterUserPassword="pass123",+ )+ cluster = resp["DBCluster"]+ assert cluster["DBClusterIdentifier"] == "rds-cc-v2"+ assert cluster["Status"] == "available"+ assert cluster["Engine"] == "aurora-postgresql"+ assert "DBClusterArn" in cluster++ desc = rds.describe_db_clusters(DBClusterIdentifier="rds-cc-v2")+ assert desc["DBClusters"][0]["DBClusterIdentifier"] == "rds-cc-v2"+++def test_rds_engine_versions_v2(rds):+ pg = rds.describe_db_engine_versions(Engine="postgres")+ assert len(pg["DBEngineVersions"]) > 0+ assert all(v["Engine"] == "postgres" for v in pg["DBEngineVersions"])++ mysql = rds.describe_db_engine_versions(Engine="mysql")+ assert len(mysql["DBEngineVersions"]) > 0+ assert all(v["Engine"] == "mysql" for v in mysql["DBEngineVersions"])+++def test_rds_snapshot_v2(rds):+ rds.create_db_instance(+ DBInstanceIdentifier="rds-snap-v2", DBInstanceClass="db.t3.micro",+ Engine="postgres", MasterUsername="admin", MasterUserPassword="pass",+ AllocatedStorage=10,+ )+ resp = rds.create_db_snapshot(+ DBSnapshotIdentifier="rds-snap-v2-s1", DBInstanceIdentifier="rds-snap-v2",+ )+ snap = resp["DBSnapshot"]+ assert snap["DBSnapshotIdentifier"] == "rds-snap-v2-s1"+ assert snap["Status"] == "available"++ desc = rds.describe_db_snapshots(DBSnapshotIdentifier="rds-snap-v2-s1")+ assert len(desc["DBSnapshots"]) == 1++ rds.delete_db_snapshot(DBSnapshotIdentifier="rds-snap-v2-s1")+ with pytest.raises(ClientError) as exc:+ rds.describe_db_snapshots(DBSnapshotIdentifier="rds-snap-v2-s1")+ assert exc.value.response["Error"]["Code"] == "DBSnapshotNotFound"+++def test_rds_tags_v2(rds):+ rds.create_db_instance(+ DBInstanceIdentifier="rds-tag-v2", DBInstanceClass="db.t3.micro",+ Engine="postgres", MasterUsername="admin", MasterUserPassword="pass",+ AllocatedStorage=10, Tags=[{"Key": "env", "Value": "dev"}],+ )+ arn = rds.describe_db_instances(DBInstanceIdentifier="rds-tag-v2")["DBInstances"][0]["DBInstanceArn"]++ tags = rds.list_tags_for_resource(ResourceName=arn)["TagList"]+ assert any(t["Key"] == "env" and t["Value"] == "dev" for t in tags)++ rds.add_tags_to_resource(ResourceName=arn, Tags=[{"Key": "team", "Value": "dba"}])+ tags2 = rds.list_tags_for_resource(ResourceName=arn)["TagList"]+ assert any(t["Key"] == "team" and t["Value"] == "dba" for t in tags2)++ rds.remove_tags_from_resource(ResourceName=arn, TagKeys=["env"])+ tags3 = rds.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)+++# ===================================================================+# ElastiCache — comprehensive tests+# ===================================================================++def test_ec_create_cluster_v2(ec):+ resp = ec.create_cache_cluster(+ CacheClusterId="ec-cc-v2", Engine="redis",+ CacheNodeType="cache.t3.micro", NumCacheNodes=1,+ )+ c = resp["CacheCluster"]+ assert c["CacheClusterId"] == "ec-cc-v2"+ assert c["Engine"] == "redis"+ assert c["CacheClusterStatus"] == "available"+ assert len(c["CacheNodes"]) == 1+++def test_ec_describe_clusters_v2(ec):+ ec.create_cache_cluster(+ CacheClusterId="ec-dc-v2a", Engine="redis",+ CacheNodeType="cache.t3.micro", NumCacheNodes=1,+ )+ ec.create_cache_cluster(+ CacheClusterId="ec-dc-v2b", Engine="memcached",+ CacheNodeType="cache.t3.micro", NumCacheNodes=1,+ )+ resp = ec.describe_cache_clusters()+ ids = [c["CacheClusterId"] for c in resp["CacheClusters"]]+ assert "ec-dc-v2a" in ids+ assert "ec-dc-v2b" in ids++ resp2 = ec.describe_cache_clusters(CacheClusterId="ec-dc-v2b")+ assert resp2["CacheClusters"][0]["Engine"] == "memcached"+++def test_ec_replication_group_v2(ec):+ resp = ec.create_replication_group(+ ReplicationGroupId="ec-rg-v2",+ ReplicationGroupDescription="Test RG v2",+ Engine="redis", CacheNodeType="cache.t3.micro",+ NumNodeGroups=1, ReplicasPerNodeGroup=1,+ )+ rg = resp["ReplicationGroup"]+ assert rg["ReplicationGroupId"] == "ec-rg-v2"+ assert rg["Status"] == "available"+ assert len(rg["NodeGroups"]) == 1++ desc = ec.describe_replication_groups(ReplicationGroupId="ec-rg-v2")+ assert desc["ReplicationGroups"][0]["ReplicationGroupId"] == "ec-rg-v2"+++def test_ec_engine_versions_v2(ec):+ redis = ec.describe_cache_engine_versions(Engine="redis")+ assert len(redis["CacheEngineVersions"]) > 0+ assert all(v["Engine"] == "redis" for v in redis["CacheEngineVersions"])++ mc = ec.describe_cache_engine_versions(Engine="memcached")+ assert len(mc["CacheEngineVersions"]) > 0+++def test_ec_tags_v2(ec):+ ec.create_cache_cluster(+ CacheClusterId="ec-tag-v2", Engine="redis",+ CacheNodeType="cache.t3.micro", NumCacheNodes=1,+ )+ arn = ec.describe_cache_clusters(CacheClusterId="ec-tag-v2")["CacheClusters"][0]["ARN"]++ ec.add_tags_to_resource(ResourceName=arn, Tags=[+ {"Key": "env", "Value": "prod"}, {"Key": "tier", "Value": "cache"},+ ])+ tags = ec.list_tags_for_resource(ResourceName=arn)["TagList"]+ tag_map = {t["Key"]: t["Value"] for t in tags}+ assert tag_map["env"] == "prod"+ assert tag_map["tier"] == "cache"++ ec.remove_tags_from_resource(ResourceName=arn, TagKeys=["env"])+ tags2 = ec.list_tags_for_resource(ResourceName=arn)["TagList"]+ assert not any(t["Key"] == "env" for t in tags2)+ assert any(t["Key"] == "tier" for t in tags2)+++def test_ec_snapshot_v2(ec):+ ec.create_cache_cluster(+ CacheClusterId="ec-snap-v2", Engine="redis",+ CacheNodeType="cache.t3.micro", NumCacheNodes=1,+ )+ resp = ec.create_snapshot(SnapshotName="ec-snap-v2-s1", CacheClusterId="ec-snap-v2")+ assert resp["Snapshot"]["SnapshotName"] == "ec-snap-v2-s1"+ assert resp["Snapshot"]["SnapshotStatus"] == "available"++ desc = ec.describe_snapshots(SnapshotName="ec-snap-v2-s1")+ assert len(desc["Snapshots"]) == 1+ assert desc["Snapshots"][0]["SnapshotName"] == "ec-snap-v2-s1"+++# ===================================================================+# Glue — comprehensive tests+# ===================================================================++def test_glue_database_v2(glue):+ glue.create_database(DatabaseInput={"Name": "glue_db_v2", "Description": "v2 DB"})+ resp = glue.get_database(Name="glue_db_v2")+ assert resp["Database"]["Name"] == "glue_db_v2"+ assert resp["Database"]["Description"] == "v2 DB"++ glue.update_database(Name="glue_db_v2", DatabaseInput={"Name": "glue_db_v2", "Description": "updated"})+ resp2 = glue.get_database(Name="glue_db_v2")+ assert resp2["Database"]["Description"] == "updated"++ glue.delete_database(Name="glue_db_v2")+ with pytest.raises(ClientError) as exc:+ glue.get_database(Name="glue_db_v2")+ assert exc.value.response["Error"]["Code"] == "EntityNotFoundException"+++def test_glue_table_v2(glue):+ glue.create_database(DatabaseInput={"Name": "glue_tbl_v2db"})+ glue.create_table(+ DatabaseName="glue_tbl_v2db",+ TableInput={+ "Name": "tbl_v2",+ "StorageDescriptor": {+ "Columns": [{"Name": "id", "Type": "int"}, {"Name": "name", "Type": "string"}],+ "Location": "s3://bucket/tbl_v2/",+ "InputFormat": "org.apache.hadoop.mapred.TextInputFormat",+ "OutputFormat": "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat",+ "SerdeInfo": {"SerializationLibrary": "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe"},+ },+ "TableType": "EXTERNAL_TABLE",+ },+ )+ resp = glue.get_table(DatabaseName="glue_tbl_v2db", Name="tbl_v2")+ assert resp["Table"]["Name"] == "tbl_v2"+ assert len(resp["Table"]["StorageDescriptor"]["Columns"]) == 2++ glue.update_table(+ DatabaseName="glue_tbl_v2db",+ TableInput={"Name": "tbl_v2", "Description": "updated table"},+ )+ resp2 = glue.get_table(DatabaseName="glue_tbl_v2db", Name="tbl_v2")+ assert resp2["Table"]["Description"] == "updated table"++ glue.delete_table(DatabaseName="glue_tbl_v2db", Name="tbl_v2")+ with pytest.raises(ClientError) as exc:+ glue.get_table(DatabaseName="glue_tbl_v2db", Name="tbl_v2")+ assert exc.value.response["Error"]["Code"] == "EntityNotFoundException"+++def test_glue_list_v2(glue):+ glue.create_database(DatabaseInput={"Name": "glue_lst_v2db"})+ glue.create_table(+ DatabaseName="glue_lst_v2db",+ TableInput={+ "Name": "lt_a", "StorageDescriptor": {+ "Columns": [{"Name": "c", "Type": "string"}],+ "Location": "s3://b/lt_a/", "InputFormat": "TIF",+ "OutputFormat": "TOF", "SerdeInfo": {"SerializationLibrary": "SL"},+ },+ },+ )+ glue.create_table(+ DatabaseName="glue_lst_v2db",+ TableInput={+ "Name": "lt_b", "StorageDescriptor": {+ "Columns": [{"Name": "c", "Type": "string"}],+ "Location": "s3://b/lt_b/", "InputFormat": "TIF",+ "OutputFormat": "TOF", "SerdeInfo": {"SerializationLibrary": "SL"},+ },+ },+ )+ dbs = glue.get_databases()+ assert any(d["Name"] == "glue_lst_v2db" for d in dbs["DatabaseList"])+ tables = glue.get_tables(DatabaseName="glue_lst_v2db")+ names = [t["Name"] for t in tables["TableList"]]+ assert "lt_a" in names+ assert "lt_b" in names+++def test_glue_job_v2(glue):+ glue.create_job(+ Name="glue-job-v2", Role="arn:aws:iam::000000000000:role/R",+ Command={"Name": "glueetl", "ScriptLocation": "s3://b/s.py"},+ GlueVersion="3.0",+ )+ job = glue.get_job(JobName="glue-job-v2")["Job"]+ assert job["Name"] == "glue-job-v2"++ run_resp = glue.start_job_run(JobName="glue-job-v2", Arguments={"--key": "val"})+ run_id = run_resp["JobRunId"]+ assert run_id++ run = glue.get_job_run(JobName="glue-job-v2", RunId=run_id)["JobRun"]+ assert run["Id"] == run_id+ assert run["JobName"] == "glue-job-v2"++ runs = glue.get_job_runs(JobName="glue-job-v2")["JobRuns"]+ assert any(r["Id"] == run_id for r in runs)+++def test_glue_crawler_v2(glue):+ glue.create_database(DatabaseInput={"Name": "glue_cr_v2db"})+ glue.create_crawler(+ Name="glue-cr-v2", Role="arn:aws:iam::000000000000:role/R",+ DatabaseName="glue_cr_v2db",+ Targets={"S3Targets": [{"Path": "s3://b/data/"}]},+ )+ cr = glue.get_crawler(Name="glue-cr-v2")["Crawler"]+ assert cr["Name"] == "glue-cr-v2"+ assert cr["State"] == "READY"++ glue.start_crawler(Name="glue-cr-v2")+ cr2 = glue.get_crawler(Name="glue-cr-v2")["Crawler"]+ assert cr2["State"] == "RUNNING"+++def test_glue_tags_v2(glue):+ glue.create_database(DatabaseInput={"Name": "glue_tag_v2db"})+ arn = "arn:aws:glue:us-east-1:000000000000:database/glue_tag_v2db"+ glue.tag_resource(ResourceArn=arn, TagsToAdd={"env": "test", "team": "data"})+ resp = glue.get_tags(ResourceArn=arn)+ assert resp["Tags"]["env"] == "test"+ assert resp["Tags"]["team"] == "data"++ glue.untag_resource(ResourceArn=arn, TagsToRemove=["team"])+ resp2 = glue.get_tags(ResourceArn=arn)+ assert resp2["Tags"] == {"env": "test"}+++def test_glue_partition_v2(glue):+ glue.create_database(DatabaseInput={"Name": "glue_part_v2db"})+ glue.create_table(+ DatabaseName="glue_part_v2db",+ TableInput={+ "Name": "ptbl_v2",+ "StorageDescriptor": {+ "Columns": [{"Name": "data", "Type": "string"}],+ "Location": "s3://b/pt/", "InputFormat": "TIF",+ "OutputFormat": "TOF", "SerdeInfo": {"SerializationLibrary": "SL"},+ },+ "PartitionKeys": [{"Name": "year", "Type": "string"}, {"Name": "month", "Type": "string"}],+ },+ )+ glue.create_partition(+ DatabaseName="glue_part_v2db", TableName="ptbl_v2",+ PartitionInput={+ "Values": ["2024", "01"],+ "StorageDescriptor": {+ "Columns": [{"Name": "data", "Type": "string"}],+ "Location": "s3://b/pt/year=2024/month=01/",+ "InputFormat": "TIF", "OutputFormat": "TOF",+ "SerdeInfo": {"SerializationLibrary": "SL"},+ },+ },+ )+ glue.create_partition(+ DatabaseName="glue_part_v2db", TableName="ptbl_v2",+ PartitionInput={+ "Values": ["2024", "02"],+ "StorageDescriptor": {+ "Columns": [{"Name": "data", "Type": "string"}],+ "Location": "s3://b/pt/year=2024/month=02/",+ "InputFormat": "TIF", "OutputFormat": "TOF",+ "SerdeInfo": {"SerializationLibrary": "SL"},+ },+ },+ )+ resp = glue.get_partition(+ DatabaseName="glue_part_v2db", TableName="ptbl_v2", PartitionValues=["2024", "01"],+ )+ assert resp["Partition"]["Values"] == ["2024", "01"]++ parts = glue.get_partitions(DatabaseName="glue_part_v2db", TableName="ptbl_v2")+ assert len(parts["Partitions"]) == 2+++def test_glue_connection_v2(glue):+ glue.create_connection(ConnectionInput={+ "Name": "glue-conn-v2",+ "ConnectionType": "JDBC",+ "ConnectionProperties": {+ "JDBC_CONNECTION_URL": "jdbc:postgresql://host/db",+ "USERNAME": "user",+ "PASSWORD": "pass",+ },+ })+ resp = glue.get_connection(Name="glue-conn-v2")+ assert resp["Connection"]["Name"] == "glue-conn-v2"+ assert resp["Connection"]["ConnectionType"] == "JDBC"++ conns = glue.get_connections()+ assert any(c["Name"] == "glue-conn-v2" for c in conns["ConnectionList"])++ glue.delete_connection(ConnectionName="glue-conn-v2")+ with pytest.raises(ClientError) as exc:+ glue.get_connection(Name="glue-conn-v2")+ assert exc.value.response["Error"]["Code"] == "EntityNotFoundException"+++# ===================================================================+# Athena — comprehensive tests+# ===================================================================++def test_athena_query_execution_v2(athena):+ resp = athena.start_query_execution(+ QueryString="SELECT 42 AS answer, 'world' AS hello",+ QueryExecutionContext={"Database": "default"},+ ResultConfiguration={"OutputLocation": "s3://athena-out/"},+ )+ qid = resp["QueryExecutionId"]+ state = None+ for _ in range(50):+ status = athena.get_query_execution(QueryExecutionId=qid)+ state = status["QueryExecution"]["Status"]["State"]+ if state in ("SUCCEEDED", "FAILED", "CANCELLED"):+ break+ time.sleep(0.1)+ assert state == "SUCCEEDED", f"Query ended in state: {state}"++ results = athena.get_query_results(QueryExecutionId=qid)+ rows = results["ResultSet"]["Rows"]+ assert len(rows) >= 2+ assert rows[0]["Data"][0]["VarCharValue"] == "answer"+ assert rows[1]["Data"][0]["VarCharValue"] == "42"+++def test_athena_workgroup_v2(athena):+ athena.create_work_group(+ Name="ath-wg-v2", Description="V2 workgroup",+ Configuration={"ResultConfiguration": {"OutputLocation": "s3://ath-out/v2/"}},+ )+ resp = athena.get_work_group(WorkGroup="ath-wg-v2")+ assert resp["WorkGroup"]["Name"] == "ath-wg-v2"+ assert resp["WorkGroup"]["Description"] == "V2 workgroup"+ assert resp["WorkGroup"]["State"] == "ENABLED"++ wgs = athena.list_work_groups()+ assert any(wg["Name"] == "ath-wg-v2" for wg in wgs["WorkGroups"])++ athena.update_work_group(+ WorkGroup="ath-wg-v2",+ ConfigurationUpdates={"ResultConfigurationUpdates": {"OutputLocation": "s3://ath-out/v2-new/"}},+ )+ resp2 = athena.get_work_group(WorkGroup="ath-wg-v2")+ assert "v2-new" in resp2["WorkGroup"]["Configuration"]["ResultConfiguration"]["OutputLocation"]++ athena.delete_work_group(WorkGroup="ath-wg-v2", RecursiveDeleteOption=True)+ with pytest.raises(ClientError):+ athena.get_work_group(WorkGroup="ath-wg-v2")+++def test_athena_named_query_v2(athena):+ resp = athena.create_named_query(+ Name="ath-nq-v2", Database="default",+ QueryString="SELECT * FROM t LIMIT 10", WorkGroup="primary",+ Description="Named query v2",+ )+ nqid = resp["NamedQueryId"]+ nq = athena.get_named_query(NamedQueryId=nqid)["NamedQuery"]+ assert nq["Name"] == "ath-nq-v2"+ assert nq["Database"] == "default"+ assert nq["QueryString"] == "SELECT * FROM t LIMIT 10"++ listed = athena.list_named_queries()+ assert nqid in listed["NamedQueryIds"]++ athena.delete_named_query(NamedQueryId=nqid)+ with pytest.raises(ClientError):+ athena.get_named_query(NamedQueryId=nqid)+++def test_athena_data_catalog_v2(athena):+ athena.create_data_catalog(+ Name="ath-cat-v2", Type="HIVE", Description="V2 catalog",+ Parameters={"metadata-function": "arn:aws:lambda:us-east-1:000000000000:function:f"},+ )+ resp = athena.get_data_catalog(Name="ath-cat-v2")+ assert resp["DataCatalog"]["Name"] == "ath-cat-v2"+ assert resp["DataCatalog"]["Type"] == "HIVE"++ listed = athena.list_data_catalogs()+ assert any(c["CatalogName"] == "ath-cat-v2" for c in listed["DataCatalogsSummary"])++ athena.update_data_catalog(Name="ath-cat-v2", Type="HIVE", Description="Updated v2")+ resp2 = athena.get_data_catalog(Name="ath-cat-v2")+ assert resp2["DataCatalog"]["Description"] == "Updated v2"++ athena.delete_data_catalog(Name="ath-cat-v2")+ with pytest.raises(ClientError):+ athena.get_data_catalog(Name="ath-cat-v2")+++def test_athena_prepared_statement_v2(athena):+ athena.create_work_group(+ Name="ath-ps-v2wg", Description="PS WG",+ Configuration={"ResultConfiguration": {"OutputLocation": "s3://out/"}},+ )+ athena.create_prepared_statement(+ StatementName="ath-ps-v2", WorkGroup="ath-ps-v2wg",+ QueryStatement="SELECT ? AS val",+ Description="Prepared v2",+ )+ resp = athena.get_prepared_statement(StatementName="ath-ps-v2", WorkGroup="ath-ps-v2wg")+ assert resp["PreparedStatement"]["StatementName"] == "ath-ps-v2"+ assert resp["PreparedStatement"]["QueryStatement"] == "SELECT ? AS val"++ listed = athena.list_prepared_statements(WorkGroup="ath-ps-v2wg")+ assert any(s["StatementName"] == "ath-ps-v2" for s in listed["PreparedStatements"])++ athena.delete_prepared_statement(StatementName="ath-ps-v2", WorkGroup="ath-ps-v2wg")+ with pytest.raises(ClientError):+ athena.get_prepared_statement(StatementName="ath-ps-v2", WorkGroup="ath-ps-v2wg")+++def test_athena_tags_v2(athena):+ athena.create_work_group(+ Name="ath-tag-v2wg", Description="Tag WG",+ Configuration={"ResultConfiguration": {"OutputLocation": "s3://out/"}},+ Tags=[{"Key": "init", "Value": "yes"}],+ )+ arn = athena.get_work_group(WorkGroup="ath-tag-v2wg")["WorkGroup"]["Configuration"]["ResultConfiguration"]["OutputLocation"]+ wg_arn = f"arn:aws:athena:us-east-1:000000000000:workgroup/ath-tag-v2wg"++ athena.tag_resource(ResourceARN=wg_arn, Tags=[{"Key": "env", "Value": "dev"}])+ resp = athena.list_tags_for_resource(ResourceARN=wg_arn)+ tag_map = {t["Key"]: t["Value"] for t in resp["Tags"]}+ assert tag_map["env"] == "dev"++ athena.untag_resource(ResourceARN=wg_arn, TagKeys=["env"])+ resp2 = athena.list_tags_for_resource(ResourceARN=wg_arn)+ assert not any(t["Key"] == "env" for t in resp2["Tags"])+++# ========== S3 Event Notifications ==========+++def test_s3_event_notification_to_sqs(s3, sqs):+ s3.create_bucket(Bucket="s3-evt-bkt")+ queue_url = sqs.create_queue(QueueName="s3-evt-queue")["QueueUrl"]+ queue_arn = sqs.get_queue_attributes(+ QueueUrl=queue_url, AttributeNames=["QueueArn"],+ )["Attributes"]["QueueArn"]+ s3.put_bucket_notification_configuration(+ Bucket="s3-evt-bkt",+ NotificationConfiguration={+ "QueueConfigurations": [{"QueueArn": queue_arn, "Events": ["s3:ObjectCreated:*"]}],+ },+ )+ s3.put_object(Bucket="s3-evt-bkt", Key="test-notify.txt", Body=b"hello")+ time.sleep(0.5)+ msgs = sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=2)+ assert "Messages" in msgs and len(msgs["Messages"]) > 0+ body = json.loads(msgs["Messages"][0]["Body"])+ assert body["Records"][0]["eventSource"] == "aws:s3"+ assert body["Records"][0]["s3"]["object"]["key"] == "test-notify.txt"+++def test_s3_event_notification_filter(s3, sqs):+ s3.create_bucket(Bucket="s3-evt-filter-bkt")+ queue_url = sqs.create_queue(QueueName="s3-evt-filter-q")["QueueUrl"]+ queue_arn = sqs.get_queue_attributes(+ QueueUrl=queue_url, AttributeNames=["QueueArn"],+ )["Attributes"]["QueueArn"]+ s3.put_bucket_notification_configuration(+ Bucket="s3-evt-filter-bkt",+ NotificationConfiguration={+ "QueueConfigurations": [{+ "QueueArn": queue_arn,+ "Events": ["s3:ObjectCreated:*"],+ "Filter": {"Key": {"FilterRules": [{"Name": "suffix", "Value": ".csv"}]}},+ }],+ },+ )+ s3.put_object(Bucket="s3-evt-filter-bkt", Key="data.txt", Body=b"no match")+ s3.put_object(Bucket="s3-evt-filter-bkt", Key="data.csv", Body=b"match")+ time.sleep(0.5)+ msgs = sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=2)+ keys = [+ json.loads(m["Body"])["Records"][0]["s3"]["object"]["key"]+ for m in msgs.get("Messages", [])+ ]+ assert "data.csv" in keys+ assert "data.txt" not in keys+++def test_s3_event_notification_delete(s3, sqs):+ s3.create_bucket(Bucket="s3-evt-del-bkt")+ queue_url = sqs.create_queue(QueueName="s3-evt-del-q")["QueueUrl"]+ queue_arn = sqs.get_queue_attributes(+ QueueUrl=queue_url, AttributeNames=["QueueArn"],+ )["Attributes"]["QueueArn"]+ s3.put_bucket_notification_configuration(+ Bucket="s3-evt-del-bkt",+ NotificationConfiguration={+ "QueueConfigurations": [{"QueueArn": queue_arn, "Events": ["s3:ObjectRemoved:*"]}],+ },+ )+ s3.put_object(Bucket="s3-evt-del-bkt", Key="to-del.txt", Body=b"bye")+ s3.delete_object(Bucket="s3-evt-del-bkt", Key="to-del.txt")+ time.sleep(0.5)+ msgs = sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=2)+ assert "Messages" in msgs and len(msgs["Messages"]) > 0+ body = json.loads(msgs["Messages"][0]["Body"])+ assert "ObjectRemoved" in body["Records"][0]["eventName"]+++# ========== S3 ListObjectVersions / Website / Logging ==========+++def test_s3_list_object_versions(s3):+ s3.create_bucket(Bucket="s3-ver-bkt")+ s3.put_object(Bucket="s3-ver-bkt", Key="v1.txt", Body=b"v1")+ s3.put_object(Bucket="s3-ver-bkt", Key="v2.txt", Body=b"v2")+ resp = s3.list_object_versions(Bucket="s3-ver-bkt")+ versions = resp.get("Versions", [])+ assert len(versions) >= 2+ keys = [v["Key"] for v in versions]+ assert "v1.txt" in keys and "v2.txt" in keys+++def test_s3_bucket_website(s3):+ s3.create_bucket(Bucket="s3-web-bkt")+ s3.put_bucket_website(+ Bucket="s3-web-bkt",+ WebsiteConfiguration={"IndexDocument": {"Suffix": "index.html"}},+ )+ resp = s3.get_bucket_website(Bucket="s3-web-bkt")+ assert resp["IndexDocument"]["Suffix"] == "index.html"+ s3.delete_bucket_website(Bucket="s3-web-bkt")+ with pytest.raises(ClientError):+ s3.get_bucket_website(Bucket="s3-web-bkt")+++def test_s3_put_bucket_logging(s3):+ s3.create_bucket(Bucket="s3-log-bkt")+ s3.put_bucket_logging(+ Bucket="s3-log-bkt",+ BucketLoggingStatus={+ "LoggingEnabled": {"TargetBucket": "s3-log-bkt", "TargetPrefix": "logs/"},+ },+ )+ resp = s3.get_bucket_logging(Bucket="s3-log-bkt")+ assert "LoggingEnabled" in resp+++# ========== DynamoDB PITR / Endpoints ==========+++def test_dynamodb_describe_continuous_backups(ddb):+ ddb.create_table(+ TableName="ddb-pitr-tbl",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ resp = ddb.describe_continuous_backups(TableName="ddb-pitr-tbl")+ assert resp["ContinuousBackupsDescription"]["ContinuousBackupsStatus"] == "ENABLED"+ pitr = resp["ContinuousBackupsDescription"]["PointInTimeRecoveryDescription"]+ assert pitr["PointInTimeRecoveryStatus"] == "DISABLED"+++def test_dynamodb_update_continuous_backups(ddb):+ ddb.update_continuous_backups(+ TableName="ddb-pitr-tbl",+ PointInTimeRecoverySpecification={"PointInTimeRecoveryEnabled": True},+ )+ resp = ddb.describe_continuous_backups(TableName="ddb-pitr-tbl")+ pitr = resp["ContinuousBackupsDescription"]["PointInTimeRecoveryDescription"]+ assert pitr["PointInTimeRecoveryStatus"] == "ENABLED"+++def test_dynamodb_describe_endpoints(ddb):+ resp = ddb.describe_endpoints()+ assert len(resp["Endpoints"]) > 0+ assert "Address" in resp["Endpoints"][0]+++# ========== IAM Groups / Inline Policies / OIDC / ServiceLinkedRole ==========+++def test_iam_groups(iam):+ iam.create_group(GroupName="test-grp")+ resp = iam.get_group(GroupName="test-grp")+ assert resp["Group"]["GroupName"] == "test-grp"++ listed = iam.list_groups()+ assert any(g["GroupName"] == "test-grp" for g in listed["Groups"])++ iam.create_user(UserName="grp-usr")+ iam.add_user_to_group(GroupName="test-grp", UserName="grp-usr")+ members = iam.get_group(GroupName="test-grp")+ assert any(u["UserName"] == "grp-usr" for u in members["Users"])++ user_groups = iam.list_groups_for_user(UserName="grp-usr")+ assert any(g["GroupName"] == "test-grp" for g in user_groups["Groups"])++ iam.remove_user_from_group(GroupName="test-grp", UserName="grp-usr")+ iam.delete_group(GroupName="test-grp")+++def test_iam_user_inline_policy(iam):+ iam.create_user(UserName="inl-pol-usr")+ doc = json.dumps({"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]})+ iam.put_user_policy(UserName="inl-pol-usr", PolicyName="s3-acc", PolicyDocument=doc)+ resp = iam.get_user_policy(UserName="inl-pol-usr", PolicyName="s3-acc")+ assert resp["PolicyName"] == "s3-acc"+ listed = iam.list_user_policies(UserName="inl-pol-usr")+ assert "s3-acc" in listed["PolicyNames"]+ iam.delete_user_policy(UserName="inl-pol-usr", PolicyName="s3-acc")+++def test_iam_service_linked_role(iam):+ resp = iam.create_service_linked_role(AWSServiceName="elasticloadbalancing.amazonaws.com")+ role = resp["Role"]+ assert "AWSServiceRoleFor" in role["RoleName"]+ assert role["Path"].startswith("/aws-service-role/")+++def test_iam_oidc_provider(iam):+ resp = iam.create_open_id_connect_provider(+ Url="https://oidc.example.com",+ ClientIDList=["my-client"],+ ThumbprintList=["a" * 40],+ )+ arn = resp["OpenIDConnectProviderArn"]+ assert "oidc.example.com" in arn+ desc = iam.get_open_id_connect_provider(OpenIDConnectProviderArn=arn)+ assert "my-client" in desc["ClientIDList"]+ iam.delete_open_id_connect_provider(OpenIDConnectProviderArn=arn)+++def test_iam_policy_tags(iam):+ resp = iam.create_policy(+ PolicyName="tagged-pol",+ PolicyDocument=json.dumps({"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}]}),+ )+ arn = resp["Policy"]["Arn"]+ iam.tag_policy(PolicyArn=arn, Tags=[{"Key": "env", "Value": "test"}])+ tags = iam.list_policy_tags(PolicyArn=arn)+ assert any(t["Key"] == "env" for t in tags["Tags"])+ iam.untag_policy(PolicyArn=arn, TagKeys=["env"])+ tags2 = iam.list_policy_tags(PolicyArn=arn)+ assert not any(t["Key"] == "env" for t in tags2["Tags"])+++# ========== SecretsManager Resource Policy ==========+++def test_secretsmanager_resource_policy(sm):+ sm.create_secret(Name="sm-pol-sec", SecretString="secret-val")+ policy = json.dumps({"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Principal": "*", "Action": "secretsmanager:GetSecretValue", "Resource": "*"}]})+ sm.put_resource_policy(SecretId="sm-pol-sec", ResourcePolicy=policy)+ resp = sm.get_resource_policy(SecretId="sm-pol-sec")+ assert resp["Name"] == "sm-pol-sec"+ assert "ResourcePolicy" in resp+ sm.delete_resource_policy(SecretId="sm-pol-sec")+++def test_secretsmanager_validate_resource_policy(sm):+ policy = json.dumps({"Version": "2012-10-17", "Statement": []})+ resp = sm.validate_resource_policy(ResourcePolicy=policy)+ assert resp["PolicyValidationPassed"] is True+++# ========== RDS Cluster Param Groups / Snapshots / Option Groups ==========+++def test_rds_cluster_parameter_group(rds):+ rds.create_db_cluster_parameter_group(+ DBClusterParameterGroupName="test-cpg",+ DBParameterGroupFamily="aurora-mysql8.0",+ Description="Test cluster param group",+ )+ resp = rds.describe_db_cluster_parameter_groups(DBClusterParameterGroupName="test-cpg")+ groups = resp["DBClusterParameterGroups"]+ assert len(groups) >= 1+ assert groups[0]["DBClusterParameterGroupName"] == "test-cpg"+ rds.delete_db_cluster_parameter_group(DBClusterParameterGroupName="test-cpg")+++def test_rds_modify_db_parameter_group(rds):+ rds.create_db_parameter_group(+ DBParameterGroupName="test-mpg",+ DBParameterGroupFamily="mysql8.0",+ Description="Test param group for modify",+ )+ resp = rds.modify_db_parameter_group(+ DBParameterGroupName="test-mpg",+ Parameters=[{"ParameterName": "max_connections", "ParameterValue": "100", "ApplyMethod": "immediate"}],+ )+ assert resp["DBParameterGroupName"] == "test-mpg"+++def test_rds_cluster_snapshot(rds):+ rds.create_db_cluster(+ DBClusterIdentifier="snap-cl",+ Engine="aurora-mysql",+ MasterUsername="admin",+ MasterUserPassword="password123",+ )+ rds.create_db_cluster_snapshot(+ DBClusterSnapshotIdentifier="snap-cl-snap",+ DBClusterIdentifier="snap-cl",+ )+ resp = rds.describe_db_cluster_snapshots(DBClusterSnapshotIdentifier="snap-cl-snap")+ snaps = resp["DBClusterSnapshots"]+ assert len(snaps) >= 1+ assert snaps[0]["DBClusterSnapshotIdentifier"] == "snap-cl-snap"+ rds.delete_db_cluster_snapshot(DBClusterSnapshotIdentifier="snap-cl-snap")+++def test_rds_option_group(rds):+ rds.create_option_group(+ OptionGroupName="test-og",+ EngineName="mysql",+ MajorEngineVersion="8.0",+ OptionGroupDescription="Test option group",+ )+ resp = rds.describe_option_groups(OptionGroupName="test-og")+ groups = resp["OptionGroupsList"]+ assert len(groups) >= 1+ assert groups[0]["OptionGroupName"] == "test-og"+ rds.delete_option_group(OptionGroupName="test-og")+++def test_rds_start_stop_cluster(rds):+ rds.create_db_cluster(+ DBClusterIdentifier="ss-cl",+ Engine="aurora-mysql",+ MasterUsername="admin",+ MasterUserPassword="password123",+ )+ rds.stop_db_cluster(DBClusterIdentifier="ss-cl")+ resp = rds.describe_db_clusters(DBClusterIdentifier="ss-cl")+ assert resp["DBClusters"][0]["Status"] == "stopped"+ rds.start_db_cluster(DBClusterIdentifier="ss-cl")+ resp2 = rds.describe_db_clusters(DBClusterIdentifier="ss-cl")+ assert resp2["DBClusters"][0]["Status"] == "available"+++def test_rds_modify_subnet_group(rds):+ rds.create_db_subnet_group(+ DBSubnetGroupName="test-mod-sg",+ DBSubnetGroupDescription="Test SG",+ SubnetIds=["subnet-111"],+ )+ rds.modify_db_subnet_group(+ DBSubnetGroupName="test-mod-sg",+ DBSubnetGroupDescription="Updated SG",+ SubnetIds=["subnet-222", "subnet-333"],+ )+ resp = rds.describe_db_subnet_groups(DBSubnetGroupName="test-mod-sg")+ assert resp["DBSubnetGroups"][0]["DBSubnetGroupDescription"] == "Updated SG"+++# ========== ElastiCache New Operations ==========+++def test_elasticache_modify_subnet_group(ec):+ ec.create_cache_subnet_group(+ CacheSubnetGroupName="test-mod-ecsg",+ CacheSubnetGroupDescription="Test EC SG",+ SubnetIds=["subnet-aaa"],+ )+ ec.modify_cache_subnet_group(+ CacheSubnetGroupName="test-mod-ecsg",+ CacheSubnetGroupDescription="Updated EC SG",+ SubnetIds=["subnet-bbb"],+ )+ resp = ec.describe_cache_subnet_groups(CacheSubnetGroupName="test-mod-ecsg")+ assert resp["CacheSubnetGroups"][0]["CacheSubnetGroupDescription"] == "Updated EC SG"+++def test_elasticache_user_crud(ec):+ ec.create_user(+ UserId="test-user-1",+ UserName="test-user-1",+ Engine="redis",+ AccessString="on ~* +@all",+ NoPasswordRequired=True,+ )+ resp = ec.describe_users(UserId="test-user-1")+ assert len(resp["Users"]) >= 1+ assert resp["Users"][0]["UserId"] == "test-user-1"+ ec.modify_user(UserId="test-user-1", AccessString="on ~keys:* +get")+ ec.delete_user(UserId="test-user-1")+++def test_elasticache_user_group_crud(ec):+ ec.create_user(UserId="ug-usr-1", UserName="ug-usr-1", Engine="redis", AccessString="on ~* +@all", NoPasswordRequired=True)+ ec.create_user_group(UserGroupId="test-ug-1", Engine="redis", UserIds=["ug-usr-1"])+ resp = ec.describe_user_groups(UserGroupId="test-ug-1")+ assert len(resp["UserGroups"]) >= 1+ assert resp["UserGroups"][0]["UserGroupId"] == "test-ug-1"+ ec.delete_user_group(UserGroupId="test-ug-1")+ ec.delete_user(UserId="ug-usr-1")+++# ========== ECS New Operations ==========+++def test_ecs_capacity_provider(ecs):+ resp = ecs.create_capacity_provider(+ name="test-cp",+ autoScalingGroupProvider={+ "autoScalingGroupArn": "arn:aws:autoscaling:us-east-1:000000000000:autoScalingGroup:xxx:autoScalingGroupName/asg-1",+ "managedScaling": {"status": "ENABLED"},+ },+ )+ assert resp["capacityProvider"]["name"] == "test-cp"+ desc = ecs.describe_capacity_providers(capacityProviders=["test-cp"])+ assert any(cp["name"] == "test-cp" for cp in desc["capacityProviders"])+ ecs.delete_capacity_provider(capacityProvider="test-cp")+++def test_ecs_update_cluster(ecs):+ ecs.create_cluster(clusterName="upd-cl")+ resp = ecs.update_cluster(+ cluster="upd-cl",+ settings=[{"name": "containerInsights", "value": "enabled"}],+ )+ assert resp["cluster"]["clusterName"] == "upd-cl"+++# ========== CloudWatch Logs New Operations ==========+++def test_cloudwatch_logs_metric_filter(logs):+ logs.create_log_group(logGroupName="/test/mf")+ logs.put_metric_filter(+ logGroupName="/test/mf",+ filterName="err-count",+ filterPattern="ERROR",+ metricTransformations=[{"metricName": "ErrorCount", "metricNamespace": "Test", "metricValue": "1"}],+ )+ resp = logs.describe_metric_filters(logGroupName="/test/mf")+ assert len(resp["metricFilters"]) == 1+ assert resp["metricFilters"][0]["filterName"] == "err-count"+ logs.delete_metric_filter(logGroupName="/test/mf", filterName="err-count")+ resp2 = logs.describe_metric_filters(logGroupName="/test/mf")+ assert len(resp2["metricFilters"]) == 0+++def test_cloudwatch_logs_insights_stub(logs):+ logs.create_log_group(logGroupName="/test/insights")+ resp = logs.start_query(+ logGroupName="/test/insights",+ startTime=0,+ endTime=9999999999,+ queryString="fields @timestamp | limit 10",+ )+ query_id = resp["queryId"]+ assert query_id+ results = logs.get_query_results(queryId=query_id)+ assert results["status"] in ("Complete", "Running")+++# ========== CloudWatch Dashboards ==========+++def test_cloudwatch_dashboard(cw):+ body = json.dumps({"widgets": [{"type": "text", "properties": {"markdown": "Hello"}}]})+ cw.put_dashboard(DashboardName="test-dash", DashboardBody=body)+ resp = cw.get_dashboard(DashboardName="test-dash")+ assert resp["DashboardName"] == "test-dash"+ assert "DashboardBody" in resp+ listed = cw.list_dashboards()+ assert any(d["DashboardName"] == "test-dash" for d in listed["DashboardEntries"])+ cw.delete_dashboards(DashboardNames=["test-dash"])+++# ========== EventBridge New Operations ==========+++def test_eventbridge_permission(eb):+ eb.create_event_bus(Name="perm-bus")+ eb.put_permission(+ EventBusName="perm-bus",+ Action="events:PutEvents",+ Principal="123456789012",+ StatementId="AllowAcct",+ )+ eb.remove_permission(EventBusName="perm-bus", StatementId="AllowAcct")+++def test_eventbridge_connection(eb):+ resp = eb.create_connection(+ Name="test-conn",+ AuthorizationType="API_KEY",+ AuthParameters={"ApiKeyAuthParameters": {"ApiKeyName": "x-api-key", "ApiKeyValue": "secret"}},+ )+ assert "ConnectionArn" in resp+ desc = eb.describe_connection(Name="test-conn")+ assert desc["Name"] == "test-conn"+ eb.delete_connection(Name="test-conn")+++def test_eventbridge_api_destination(eb):+ eb.create_connection(Name="apid-conn", AuthorizationType="API_KEY", AuthParameters={"ApiKeyAuthParameters": {"ApiKeyName": "k", "ApiKeyValue": "v"}})+ resp = eb.create_api_destination(+ Name="test-apid",+ ConnectionArn="arn:aws:events:us-east-1:000000000000:connection/apid-conn",+ InvocationEndpoint="https://example.com/webhook",+ HttpMethod="POST",+ )+ assert "ApiDestinationArn" in resp+ desc = eb.describe_api_destination(Name="test-apid")+ assert desc["Name"] == "test-apid"+ eb.delete_api_destination(Name="test-apid")+++# ========== Glue Triggers / Workflows ==========+++def test_glue_trigger(glue):+ glue.create_trigger(Name="test-trig", Type="ON_DEMAND", Actions=[{"JobName": "nonexistent-job"}])+ resp = glue.get_trigger(Name="test-trig")+ assert resp["Trigger"]["Name"] == "test-trig"+ assert resp["Trigger"]["State"] == "CREATED"+ glue.start_trigger(Name="test-trig")+ resp2 = glue.get_trigger(Name="test-trig")+ assert resp2["Trigger"]["State"] == "ACTIVATED"+ glue.stop_trigger(Name="test-trig")+ resp3 = glue.get_trigger(Name="test-trig")+ assert resp3["Trigger"]["State"] == "DEACTIVATED"+ glue.delete_trigger(Name="test-trig")+++def test_glue_workflow(glue):+ glue.create_workflow(Name="test-wf", Description="Test workflow")+ resp = glue.get_workflow(Name="test-wf")+ assert resp["Workflow"]["Name"] == "test-wf"+ run = glue.start_workflow_run(Name="test-wf")+ assert "RunId" in run+ glue.delete_workflow(Name="test-wf")+++# ========== Kinesis Encryption / Monitoring ==========+++def test_kinesis_stream_encryption(kin):+ import uuid as _uuid+ sname = f"intg-enc-str-{_uuid.uuid4().hex[:8]}"+ kin.create_stream(StreamName=sname, ShardCount=1)+ time.sleep(0.5)+ kin.start_stream_encryption(StreamName=sname, EncryptionType="KMS", KeyId="alias/aws/kinesis")+ resp = kin.describe_stream(StreamName=sname)+ assert resp["StreamDescription"]["EncryptionType"] == "KMS"+ kin.stop_stream_encryption(StreamName=sname, EncryptionType="KMS", KeyId="alias/aws/kinesis")+ resp2 = kin.describe_stream(StreamName=sname)+ assert resp2["StreamDescription"]["EncryptionType"] == "NONE"+ kin.delete_stream(StreamName=sname)+++def test_kinesis_enhanced_monitoring(kin):+ import uuid as _uuid+ sname = f"intg-mon-str-{_uuid.uuid4().hex[:8]}"+ kin.create_stream(StreamName=sname, ShardCount=1)+ time.sleep(0.5)+ resp = kin.enable_enhanced_monitoring(StreamName=sname, ShardLevelMetrics=["IncomingBytes", "OutgoingBytes"])+ assert "IncomingBytes" in resp.get("DesiredShardLevelMetrics", [])+ resp2 = kin.disable_enhanced_monitoring(StreamName=sname, ShardLevelMetrics=["IncomingBytes"])+ assert "IncomingBytes" not in resp2.get("DesiredShardLevelMetrics", [])+ kin.delete_stream(StreamName=sname)+++# ========== Step Functions New Operations ==========+++def test_sfn_start_sync_execution(sfn_sync):+ import uuid as _uuid+ sm_name = f"intg-sync-sm-{_uuid.uuid4().hex[:8]}"+ sm_arn = sfn_sync.create_state_machine(+ name=sm_name,+ definition=json.dumps({+ "StartAt": "Pass",+ "States": {"Pass": {"Type": "Pass", "Result": {"msg": "done"}, "End": True}},+ }),+ roleArn="arn:aws:iam::000000000000:role/sfn-role",+ )["stateMachineArn"]+ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input=json.dumps({"test": True}))+ assert resp["status"] == "SUCCEEDED"+ assert "output" in resp+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)+++def test_sfn_describe_state_machine_for_execution(sfn):+ import uuid as _uuid+ sm_name = f"intg-desc-sm-exec-{_uuid.uuid4().hex[:8]}"+ sm_arn = sfn.create_state_machine(+ name=sm_name,+ definition=json.dumps({+ "StartAt": "Pass",+ "States": {"Pass": {"Type": "Pass", "End": True}},+ }),+ roleArn="arn:aws:iam::000000000000:role/sfn-role",+ )["stateMachineArn"]+ exec_resp = sfn.start_execution(stateMachineArn=sm_arn)+ time.sleep(0.5)+ resp = sfn.describe_state_machine_for_execution(executionArn=exec_resp["executionArn"])+ assert resp["stateMachineArn"] == sm_arn+ assert "definition" in resp+ sfn.delete_state_machine(stateMachineArn=sm_arn)+++# ========== API Gateway v2 ==========+++def test_apigw_create_api(apigw):+ resp = apigw.create_api(Name="test-api", ProtocolType="HTTP")+ assert "ApiId" in resp+ assert resp["Name"] == "test-api"+ assert resp["ProtocolType"] == "HTTP"+++def test_apigw_get_api(apigw):+ create = apigw.create_api(Name="get-api-test", ProtocolType="HTTP")+ api_id = create["ApiId"]+ resp = apigw.get_api(ApiId=api_id)+ assert resp["ApiId"] == api_id+ assert resp["Name"] == "get-api-test"+++def test_apigw_get_apis(apigw):+ apigw.create_api(Name="list-api-a", ProtocolType="HTTP")+ apigw.create_api(Name="list-api-b", ProtocolType="HTTP")+ resp = apigw.get_apis()+ names = [a["Name"] for a in resp["Items"]]+ assert "list-api-a" in names+ assert "list-api-b" in names+++def test_apigw_update_api(apigw):+ api_id = apigw.create_api(Name="update-api-before", ProtocolType="HTTP")["ApiId"]+ apigw.update_api(ApiId=api_id, Name="update-api-after")+ resp = apigw.get_api(ApiId=api_id)+ assert resp["Name"] == "update-api-after"+++def test_apigw_delete_api(apigw):+ from botocore.exceptions import ClientError+ api_id = apigw.create_api(Name="delete-api-test", ProtocolType="HTTP")["ApiId"]+ apigw.delete_api(ApiId=api_id)+ with pytest.raises(ClientError) as exc:+ apigw.get_api(ApiId=api_id)+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404+++def test_apigw_create_route(apigw):+ api_id = apigw.create_api(Name="route-api", ProtocolType="HTTP")["ApiId"]+ resp = apigw.create_route(ApiId=api_id, RouteKey="GET /items")+ assert "RouteId" in resp+ assert resp["RouteKey"] == "GET /items"+++def test_apigw_get_routes(apigw):+ api_id = apigw.create_api(Name="routes-list-api", ProtocolType="HTTP")["ApiId"]+ apigw.create_route(ApiId=api_id, RouteKey="GET /a")+ apigw.create_route(ApiId=api_id, RouteKey="POST /b")+ resp = apigw.get_routes(ApiId=api_id)+ keys = [r["RouteKey"] for r in resp["Items"]]+ assert "GET /a" in keys+ assert "POST /b" in keys+++def test_apigw_get_route(apigw):+ api_id = apigw.create_api(Name="get-route-api", ProtocolType="HTTP")["ApiId"]+ route_id = apigw.create_route(ApiId=api_id, RouteKey="DELETE /things")["RouteId"]+ resp = apigw.get_route(ApiId=api_id, RouteId=route_id)+ assert resp["RouteId"] == route_id+ assert resp["RouteKey"] == "DELETE /things"+++def test_apigw_update_route(apigw):+ api_id = apigw.create_api(Name="update-route-api", ProtocolType="HTTP")["ApiId"]+ route_id = apigw.create_route(ApiId=api_id, RouteKey="GET /old")["RouteId"]+ apigw.update_route(ApiId=api_id, RouteId=route_id, RouteKey="GET /new")+ resp = apigw.get_route(ApiId=api_id, RouteId=route_id)+ assert resp["RouteKey"] == "GET /new"+++def test_apigw_delete_route(apigw):+ api_id = apigw.create_api(Name="del-route-api", ProtocolType="HTTP")["ApiId"]+ route_id = apigw.create_route(ApiId=api_id, RouteKey="GET /gone")["RouteId"]+ apigw.delete_route(ApiId=api_id, RouteId=route_id)+ resp = apigw.get_routes(ApiId=api_id)+ assert not any(r["RouteId"] == route_id for r in resp["Items"])+++def test_apigw_create_integration(apigw):+ api_id = apigw.create_api(Name="integ-api", ProtocolType="HTTP")["ApiId"]+ resp = apigw.create_integration(+ ApiId=api_id,+ IntegrationType="AWS_PROXY",+ IntegrationUri="arn:aws:lambda:us-east-1:000000000000:function:my-fn",+ PayloadFormatVersion="2.0",+ )+ assert "IntegrationId" in resp+ assert resp["IntegrationType"] == "AWS_PROXY"+ assert resp["PayloadFormatVersion"] == "2.0"+++def test_apigw_get_integrations(apigw):+ api_id = apigw.create_api(Name="integ-list-api", ProtocolType="HTTP")["ApiId"]+ apigw.create_integration(ApiId=api_id, IntegrationType="AWS_PROXY",+ IntegrationUri="arn:aws:lambda:us-east-1:000000000000:function:fn1")+ resp = apigw.get_integrations(ApiId=api_id)+ assert len(resp["Items"]) >= 1+++def test_apigw_get_integration(apigw):+ api_id = apigw.create_api(Name="get-integ-api", ProtocolType="HTTP")["ApiId"]+ int_id = apigw.create_integration(+ ApiId=api_id, IntegrationType="HTTP_PROXY",+ IntegrationUri="https://example.com",+ IntegrationMethod="GET",+ )["IntegrationId"]+ resp = apigw.get_integration(ApiId=api_id, IntegrationId=int_id)+ assert resp["IntegrationId"] == int_id+ assert resp["IntegrationType"] == "HTTP_PROXY"+++def test_apigw_delete_integration(apigw):+ api_id = apigw.create_api(Name="del-integ-api", ProtocolType="HTTP")["ApiId"]+ int_id = apigw.create_integration(+ ApiId=api_id, IntegrationType="AWS_PROXY",+ IntegrationUri="arn:aws:lambda:us-east-1:000000000000:function:fn2",+ )["IntegrationId"]+ apigw.delete_integration(ApiId=api_id, IntegrationId=int_id)+ resp = apigw.get_integrations(ApiId=api_id)+ assert not any(i["IntegrationId"] == int_id for i in resp["Items"])+++def test_apigw_create_stage(apigw):+ api_id = apigw.create_api(Name="stage-api", ProtocolType="HTTP")["ApiId"]+ resp = apigw.create_stage(ApiId=api_id, StageName="prod")+ assert resp["StageName"] == "prod"+++def test_apigw_get_stages(apigw):+ api_id = apigw.create_api(Name="stages-list-api", ProtocolType="HTTP")["ApiId"]+ apigw.create_stage(ApiId=api_id, StageName="v1")+ apigw.create_stage(ApiId=api_id, StageName="v2")+ resp = apigw.get_stages(ApiId=api_id)+ names = [s["StageName"] for s in resp["Items"]]+ assert "v1" in names+ assert "v2" in names+++def test_apigw_get_stage(apigw):+ api_id = apigw.create_api(Name="get-stage-api", ProtocolType="HTTP")["ApiId"]+ apigw.create_stage(ApiId=api_id, StageName="dev")+ resp = apigw.get_stage(ApiId=api_id, StageName="dev")+ assert resp["StageName"] == "dev"+++def test_apigw_update_stage(apigw):+ api_id = apigw.create_api(Name="update-stage-api", ProtocolType="HTTP")["ApiId"]+ apigw.create_stage(ApiId=api_id, StageName="staging")+ apigw.update_stage(ApiId=api_id, StageName="staging", Description="updated")+ resp = apigw.get_stage(ApiId=api_id, StageName="staging")+ assert resp.get("Description") == "updated"+++def test_apigw_delete_stage(apigw):+ api_id = apigw.create_api(Name="del-stage-api", ProtocolType="HTTP")["ApiId"]+ apigw.create_stage(ApiId=api_id, StageName="temp")+ apigw.delete_stage(ApiId=api_id, StageName="temp")+ resp = apigw.get_stages(ApiId=api_id)+ assert not any(s["StageName"] == "temp" for s in resp["Items"])+++def test_apigw_create_deployment(apigw):+ api_id = apigw.create_api(Name="deploy-api", ProtocolType="HTTP")["ApiId"]+ resp = apigw.create_deployment(ApiId=api_id)+ assert "DeploymentId" in resp+ assert resp["DeploymentStatus"] == "DEPLOYED"+++def test_apigw_get_deployments(apigw):+ api_id = apigw.create_api(Name="deployments-list-api", ProtocolType="HTTP")["ApiId"]+ apigw.create_deployment(ApiId=api_id, Description="first")+ apigw.create_deployment(ApiId=api_id, Description="second")+ resp = apigw.get_deployments(ApiId=api_id)+ assert len(resp["Items"]) >= 2+++def test_apigw_get_deployment(apigw):+ api_id = apigw.create_api(Name="get-deploy-api", ProtocolType="HTTP")["ApiId"]+ dep_id = apigw.create_deployment(ApiId=api_id, Description="single")["DeploymentId"]+ resp = apigw.get_deployment(ApiId=api_id, DeploymentId=dep_id)+ assert resp["DeploymentId"] == dep_id+++def test_apigw_delete_deployment(apigw):+ api_id = apigw.create_api(Name="del-deploy-api", ProtocolType="HTTP")["ApiId"]+ dep_id = apigw.create_deployment(ApiId=api_id)["DeploymentId"]+ apigw.delete_deployment(ApiId=api_id, DeploymentId=dep_id)+ resp = apigw.get_deployments(ApiId=api_id)+ assert not any(d["DeploymentId"] == dep_id for d in resp["Items"])+++def test_apigw_tag_resource(apigw):+ api_id = apigw.create_api(Name="tag-api", ProtocolType="HTTP")["ApiId"]+ resource_arn = f"arn:aws:apigateway:us-east-1::/apis/{api_id}"+ apigw.tag_resource(ResourceArn=resource_arn, Tags={"env": "test", "owner": "team-a"})+ resp = apigw.get_tags(ResourceArn=resource_arn)+ assert resp["Tags"].get("env") == "test"+ assert resp["Tags"].get("owner") == "team-a"+++def test_apigw_untag_resource(apigw):+ api_id = apigw.create_api(Name="untag-api", ProtocolType="HTTP")["ApiId"]+ resource_arn = f"arn:aws:apigateway:us-east-1::/apis/{api_id}"+ apigw.tag_resource(ResourceArn=resource_arn, Tags={"remove-me": "yes", "keep-me": "yes"})+ apigw.untag_resource(ResourceArn=resource_arn, TagKeys=["remove-me"])+ resp = apigw.get_tags(ResourceArn=resource_arn)+ assert "remove-me" not in resp["Tags"]+ assert resp["Tags"].get("keep-me") == "yes"+++def test_apigw_api_not_found(apigw):+ from botocore.exceptions import ClientError+ with pytest.raises(ClientError) as exc:+ apigw.get_api(ApiId="00000000")+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404+++def test_apigw_route_on_deleted_api(apigw):+ from botocore.exceptions import ClientError+ with pytest.raises(ClientError) as exc:+ apigw.create_route(ApiId="00000000", RouteKey="GET /x")+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404+++def test_apigw_http_protocol_type(apigw):+ resp = apigw.create_api(Name="http-proto-api", ProtocolType="HTTP")+ assert resp["ProtocolType"] == "HTTP"+ api_id = resp["ApiId"]+ fetched = apigw.get_api(ApiId=api_id)+ assert fetched["ProtocolType"] == "HTTP"+++# ========== Health endpoint ==========+++def test_health_endpoint():+ import urllib.request+ resp = urllib.request.urlopen("http://localhost:4566/_localstack/health")+ assert resp.status == 200+ data = json.loads(resp.read())+ assert "services" in data+ assert "s3" in data["services"]+++def test_health_endpoint_ministack():+ import urllib.request+ resp = urllib.request.urlopen("http://localhost:4566/_ministack/health")+ assert resp.status == 200+ data = json.loads(resp.read())+ assert data["edition"] == "light"+++# ========== STS GetSessionToken ==========+++def test_sts_get_session_token(sts):+ resp = sts.get_session_token(DurationSeconds=900)+ creds = resp["Credentials"]+ assert "AccessKeyId" in creds+ assert "SecretAccessKey" in creds+ assert "SessionToken" in creds+ assert "Expiration" in creds+++# ========== DynamoDB TTL ==========+++def test_ddb_ttl(ddb):+ import uuid as _uuid+ table = f"intg-ttl-{_uuid.uuid4().hex[:8]}"+ ddb.create_table(+ TableName=table,+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ # Initially disabled+ resp = ddb.describe_time_to_live(TableName=table)+ assert resp["TimeToLiveDescription"]["TimeToLiveStatus"] == "DISABLED"++ # Enable TTL+ ddb.update_time_to_live(+ TableName=table,+ TimeToLiveSpecification={"Enabled": True, "AttributeName": "expires_at"},+ )+ resp = ddb.describe_time_to_live(TableName=table)+ assert resp["TimeToLiveDescription"]["TimeToLiveStatus"] == "ENABLED"+ assert resp["TimeToLiveDescription"]["AttributeName"] == "expires_at"++ # Disable TTL+ ddb.update_time_to_live(+ TableName=table,+ TimeToLiveSpecification={"Enabled": False, "AttributeName": "expires_at"},+ )+ resp = ddb.describe_time_to_live(TableName=table)+ assert resp["TimeToLiveDescription"]["TimeToLiveStatus"] == "DISABLED"+ ddb.delete_table(TableName=table)+++# ========== Lambda warm start ==========+++def test_lambda_warm_start(lam, apigw):+ """Warm worker via API Gateway execute-api: module-level state persists across invocations."""+ import uuid as _uuid+ import urllib.request as _urlreq+ fname = f"intg-warm-{_uuid.uuid4().hex[:8]}"+ code = (+ b"import time\n"+ b"_boot_time = time.time()\n"+ b"def handler(event, context):\n"+ b" return {'statusCode': 200, 'body': str(_boot_time)}\n"+ )+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ lam.create_function(+ FunctionName=fname,+ Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/test-role",+ Handler="index.handler",+ Code={"ZipFile": buf.getvalue()},+ )+ api_id = apigw.create_api(Name=f"warm-api-{fname}", ProtocolType="HTTP")["ApiId"]+ int_id = apigw.create_integration(+ ApiId=api_id, IntegrationType="AWS_PROXY",+ IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{fname}",+ PayloadFormatVersion="2.0",+ )["IntegrationId"]+ apigw.create_route(ApiId=api_id, RouteKey="GET /ping", Target=f"integrations/{int_id}")+ apigw.create_stage(ApiId=api_id, StageName="$default")++ def call():+ req = _urlreq.Request(+ f"http://{api_id}.execute-api.localhost:4566/$default/ping", method="GET"+ )+ req.add_header("Host", f"{api_id}.execute-api.localhost:4566")+ return _urlreq.urlopen(req).read().decode()++ t1 = call() # cold start — spawns worker, imports module+ t2 = call() # warm — reuses worker, same module state+ assert t1 == t2, f"Warm worker should reuse module state: {t1} != {t2}"++ apigw.delete_api(ApiId=api_id)+ lam.delete_function(FunctionName=fname)+++# ========== API Gateway execute-api data plane ==========+++def test_apigw_execute_lambda_proxy(apigw, lam):+ """API Gateway execute-api routes a request through Lambda proxy integration."""+ import uuid as _uuid+ import urllib.request as _urlreq+ import urllib.error as _urlerr++ fname = f"intg-apigw-fn-{_uuid.uuid4().hex[:8]}"+ code = (+ b"import json\n"+ b"def handler(event, context):\n"+ b" return {\n"+ b" 'statusCode': 200,\n"+ b" 'headers': {'Content-Type': 'application/json'},\n"+ b" 'body': json.dumps({'path': event.get('rawPath', '/')}),\n"+ b" }\n"+ )+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ lam.create_function(+ FunctionName=fname,+ Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/test-role",+ Handler="index.handler",+ Code={"ZipFile": buf.getvalue()},+ )++ api_id = apigw.create_api(Name=f"exec-api-{fname}", ProtocolType="HTTP")["ApiId"]+ int_id = apigw.create_integration(+ ApiId=api_id,+ IntegrationType="AWS_PROXY",+ IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{fname}",+ PayloadFormatVersion="2.0",+ )["IntegrationId"]+ route_id = apigw.create_route(+ ApiId=api_id,+ RouteKey="GET /hello",+ Target=f"integrations/{int_id}",+ )["RouteId"]+ apigw.create_stage(ApiId=api_id, StageName="$default")++ url = f"http://{api_id}.execute-api.localhost:4566/$default/hello"+ req = _urlreq.Request(url, method="GET")+ req.add_header("Host", f"{api_id}.execute-api.localhost:4566")+ resp = _urlreq.urlopen(req)+ assert resp.status == 200+ body = json.loads(resp.read())+ assert body["path"] == "/hello"++ # Cleanup+ apigw.delete_route(ApiId=api_id, RouteId=route_id)+ apigw.delete_integration(ApiId=api_id, IntegrationId=int_id)+ apigw.delete_api(ApiId=api_id)+ lam.delete_function(FunctionName=fname)+++def test_apigw_execute_no_route(apigw):+ """execute-api returns 404 when no matching route exists."""+ import urllib.request as _urlreq+ import urllib.error as _urlerr++ api_id = apigw.create_api(Name="no-route-api", ProtocolType="HTTP")["ApiId"]+ apigw.create_stage(ApiId=api_id, StageName="$default")+ url = f"http://{api_id}.execute-api.localhost:4566/$default/nonexistent"+ req = _urlreq.Request(url, method="GET")+ req.add_header("Host", f"{api_id}.execute-api.localhost:4566")+ try:+ _urlreq.urlopen(req)+ assert False, "Expected 404"+ except _urlerr.HTTPError as e:+ assert e.code == 404+ apigw.delete_api(ApiId=api_id)+++def test_apigw_execute_default_route(apigw, lam):+ """$default catch-all route matches any path."""+ import uuid as _uuid+ import urllib.request as _urlreq++ fname = f"intg-default-fn-{_uuid.uuid4().hex[:8]}"+ code = b"def handler(event, context):\n return {'statusCode': 200, 'body': 'ok'}\n"+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ lam.create_function(+ FunctionName=fname, Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/test-role",+ Handler="index.handler", Code={"ZipFile": buf.getvalue()},+ )+ api_id = apigw.create_api(Name=f"default-route-{fname}", ProtocolType="HTTP")["ApiId"]+ int_id = apigw.create_integration(+ ApiId=api_id, IntegrationType="AWS_PROXY",+ IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{fname}",+ PayloadFormatVersion="2.0",+ )["IntegrationId"]+ apigw.create_route(ApiId=api_id, RouteKey="$default", Target=f"integrations/{int_id}")+ apigw.create_stage(ApiId=api_id, StageName="$default")++ url = f"http://{api_id}.execute-api.localhost:4566/$default/any/path/here"+ req = _urlreq.Request(url, method="POST")+ req.add_header("Host", f"{api_id}.execute-api.localhost:4566")+ resp = _urlreq.urlopen(req)+ assert resp.status == 200++ apigw.delete_api(ApiId=api_id)+ lam.delete_function(FunctionName=fname)+++# ========== EventBridge → Lambda dispatch ==========+++def test_eventbridge_lambda_target(eb, lam):+ """PutEvents dispatches to a Lambda target when the rule matches."""+ import uuid as _uuid++ fname = f"intg-eb-fn-{_uuid.uuid4().hex[:8]}"+ bus_name = f"intg-eb-bus-{_uuid.uuid4().hex[:8]}"+ rule_name = f"intg-eb-rule-{_uuid.uuid4().hex[:8]}"++ code = (+ b"events = []\n"+ b"def handler(event, context):\n"+ b" events.append(event)\n"+ b" return {'processed': True}\n"+ )+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ lam.create_function(+ FunctionName=fname, Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/test-role",+ Handler="index.handler", Code={"ZipFile": buf.getvalue()},+ )+ fn_arn = lam.get_function(FunctionName=fname)["Configuration"]["FunctionArn"]++ eb.create_event_bus(Name=bus_name)+ eb.put_rule(+ Name=rule_name, EventBusName=bus_name,+ EventPattern=json.dumps({"source": ["myapp.test"]}),+ State="ENABLED",+ )+ eb.put_targets(+ Rule=rule_name, EventBusName=bus_name,+ Targets=[{"Id": "lambda-target", "Arn": fn_arn}],+ )++ resp = eb.put_events(Entries=[{+ "Source": "myapp.test",+ "DetailType": "TestEvent",+ "Detail": json.dumps({"key": "value"}),+ "EventBusName": bus_name,+ }])+ assert resp["FailedEntryCount"] == 0++ # Cleanup+ eb.remove_targets(Rule=rule_name, EventBusName=bus_name, Ids=["lambda-target"])+ eb.delete_rule(Name=rule_name, EventBusName=bus_name)+ eb.delete_event_bus(Name=bus_name)+ lam.delete_function(FunctionName=fname)+++# ========== API Gateway path parameter matching ==========+++def test_apigw_path_param_route(apigw, lam):+ """Route with {id} path parameter matches requests correctly."""+ import uuid as _uuid+ import urllib.request as _urlreq++ fname = f"intg-param-fn-{_uuid.uuid4().hex[:8]}"+ code = (+ b"import json\n"+ b"def handler(event, context):\n"+ b" return {'statusCode': 200, 'body': json.dumps({'rawPath': event.get('rawPath')})}\n"+ )+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ lam.create_function(+ FunctionName=fname, Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/test-role",+ Handler="index.handler", Code={"ZipFile": buf.getvalue()},+ )+ api_id = apigw.create_api(Name=f"param-api-{fname}", ProtocolType="HTTP")["ApiId"]+ int_id = apigw.create_integration(+ ApiId=api_id, IntegrationType="AWS_PROXY",+ IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{fname}",+ PayloadFormatVersion="2.0",+ )["IntegrationId"]+ apigw.create_route(ApiId=api_id, RouteKey="GET /items/{id}", Target=f"integrations/{int_id}")+ apigw.create_stage(ApiId=api_id, StageName="$default")++ url = f"http://{api_id}.execute-api.localhost:4566/$default/items/abc123"+ req = _urlreq.Request(url, method="GET")+ req.add_header("Host", f"{api_id}.execute-api.localhost:4566")+ resp = _urlreq.urlopen(req)+ assert resp.status == 200+ body = json.loads(resp.read())+ assert body["rawPath"] == "/items/abc123"++ apigw.delete_api(ApiId=api_id)+ lam.delete_function(FunctionName=fname)+++def test_apigw_greedy_path_param(apigw, lam):+ """{proxy+} greedy path parameter matches paths with multiple segments."""+ import uuid as _uuid_mod+ import urllib.request as _urlreq+ fname = f"intg-greedy-{_uuid_mod.uuid4().hex[:8]}"+ code = 'def handler(event, context):\n return {"statusCode": 200, "body": event["rawPath"]}\n'+ lam.create_function(+ FunctionName=fname, Runtime="python3.9", Role=_LAMBDA_ROLE,+ Handler="index.handler", Code={"ZipFile": _make_zip(code)},+ )+ func_arn = f"arn:aws:lambda:us-east-1:000000000000:function:{fname}"+ api_id = apigw.create_api(Name="greedy-test", ProtocolType="HTTP")["ApiId"]+ int_id = apigw.create_integration(+ ApiId=api_id, IntegrationType="AWS_PROXY", IntegrationUri=func_arn,+ PayloadFormatVersion="2.0",+ )["IntegrationId"]+ apigw.create_route(ApiId=api_id, RouteKey="GET /files/{proxy+}", Target=f"integrations/{int_id}")+ apigw.create_stage(ApiId=api_id, StageName="$default")++ # Path with multiple segments should match {proxy+}+ url = f"http://{api_id}.execute-api.localhost:4566/$default/files/a/b/c"+ req = _urlreq.Request(url, method="GET")+ req.add_header("Host", f"{api_id}.execute-api.localhost:4566")+ resp = _urlreq.urlopen(req)+ assert resp.status == 200+ # handler returns rawPath as body string+ assert resp.read().decode() == "/files/a/b/c"++ apigw.delete_api(ApiId=api_id)+ lam.delete_function(FunctionName=fname)+++def test_apigw_authorizer_crud(apigw):+ """CreateAuthorizer / GetAuthorizer / GetAuthorizers / UpdateAuthorizer / DeleteAuthorizer."""+ import uuid as _uuid_mod+ api_id = apigw.create_api(Name=f"auth-test-{_uuid_mod.uuid4().hex[:8]}", ProtocolType="HTTP")["ApiId"]++ # Create JWT authorizer+ resp = apigw.create_authorizer(+ ApiId=api_id,+ AuthorizerType="JWT",+ Name="my-jwt-auth",+ IdentitySource=["$request.header.Authorization"],+ JwtConfiguration={"Audience": ["https://example.com"], "Issuer": "https://idp.example.com"},+ )+ assert resp["AuthorizerType"] == "JWT"+ assert resp["Name"] == "my-jwt-auth"+ auth_id = resp["AuthorizerId"]++ # Get single+ got = apigw.get_authorizer(ApiId=api_id, AuthorizerId=auth_id)+ assert got["AuthorizerId"] == auth_id+ assert got["JwtConfiguration"]["Issuer"] == "https://idp.example.com"++ # List+ listed = apigw.get_authorizers(ApiId=api_id)+ assert any(a["AuthorizerId"] == auth_id for a in listed["Items"])++ # Update+ updated = apigw.update_authorizer(ApiId=api_id, AuthorizerId=auth_id, Name="renamed-auth")+ assert updated["Name"] == "renamed-auth"++ # Delete+ apigw.delete_authorizer(ApiId=api_id, AuthorizerId=auth_id)+ listed2 = apigw.get_authorizers(ApiId=api_id)+ assert not any(a["AuthorizerId"] == auth_id for a in listed2["Items"])++ apigw.delete_api(ApiId=api_id)+++def test_apigw_routekey_in_lambda_event(apigw, lam):+ """routeKey in Lambda event should reflect the matched route, not hardcoded $default."""+ import uuid as _uuid_mod+ import urllib.request as _urlreq+ fname = f"intg-rk-{_uuid_mod.uuid4().hex[:8]}"+ code = 'def handler(event, context):\n return {"statusCode": 200, "body": event["routeKey"]}\n'+ lam.create_function(+ FunctionName=fname, Runtime="python3.9", Role=_LAMBDA_ROLE,+ Handler="index.handler", Code={"ZipFile": _make_zip(code)},+ )+ func_arn = f"arn:aws:lambda:us-east-1:000000000000:function:{fname}"+ api_id = apigw.create_api(Name="rk-test", ProtocolType="HTTP")["ApiId"]+ int_id = apigw.create_integration(+ ApiId=api_id, IntegrationType="AWS_PROXY", IntegrationUri=func_arn,+ PayloadFormatVersion="2.0",+ )["IntegrationId"]+ apigw.create_route(ApiId=api_id, RouteKey="GET /ping", Target=f"integrations/{int_id}")+ apigw.create_stage(ApiId=api_id, StageName="$default")++ url = f"http://{api_id}.execute-api.localhost:4566/$default/ping"+ req = _urlreq.Request(url, method="GET")+ req.add_header("Host", f"{api_id}.execute-api.localhost:4566")+ resp = _urlreq.urlopen(req)+ assert resp.status == 200+ assert resp.read().decode() == "GET /ping"++ apigw.delete_api(ApiId=api_id)+ lam.delete_function(FunctionName=fname)+++# ========== Kinesis: shard operations ==========+++def test_kinesis_split_shard(kin):+ import uuid as _uuid+ sname = f"intg-split-{_uuid.uuid4().hex[:8]}"+ kin.create_stream(StreamName=sname, ShardCount=1)+ time.sleep(0.3)+ desc = kin.describe_stream(StreamName=sname)+ shard_id = desc["StreamDescription"]["Shards"][0]["ShardId"]+ start_hash = int(desc["StreamDescription"]["Shards"][0]["HashKeyRange"]["StartingHashKey"])+ end_hash = int(desc["StreamDescription"]["Shards"][0]["HashKeyRange"]["EndingHashKey"])+ mid = str((start_hash + end_hash) // 2)+ kin.split_shard(StreamName=sname, ShardToSplit=shard_id, NewStartingHashKey=mid)+ time.sleep(0.3)+ desc2 = kin.describe_stream(StreamName=sname)+ assert len(desc2["StreamDescription"]["Shards"]) == 2+ kin.delete_stream(StreamName=sname)+++def test_kinesis_merge_shards(kin):+ import uuid as _uuid+ sname = f"intg-merge-{_uuid.uuid4().hex[:8]}"+ kin.create_stream(StreamName=sname, ShardCount=2)+ time.sleep(0.3)+ desc = kin.describe_stream(StreamName=sname)+ shards = desc["StreamDescription"]["Shards"]+ assert len(shards) == 2+ # Sort by starting hash key to get adjacent shards+ shards_sorted = sorted(shards, key=lambda s: int(s["HashKeyRange"]["StartingHashKey"]))+ kin.merge_shards(+ StreamName=sname,+ ShardToMerge=shards_sorted[0]["ShardId"],+ AdjacentShardToMerge=shards_sorted[1]["ShardId"],+ )+ time.sleep(0.3)+ desc2 = kin.describe_stream(StreamName=sname)+ assert len(desc2["StreamDescription"]["Shards"]) == 1+ kin.delete_stream(StreamName=sname)+++def test_kinesis_update_shard_count(kin):+ import uuid as _uuid+ sname = f"intg-usc-{_uuid.uuid4().hex[:8]}"+ kin.create_stream(StreamName=sname, ShardCount=1)+ time.sleep(0.3)+ resp = kin.update_shard_count(StreamName=sname, TargetShardCount=2, ScalingType="UNIFORM_SCALING")+ assert resp["TargetShardCount"] == 2+ kin.delete_stream(StreamName=sname)+++def test_kinesis_register_deregister_consumer(kin):+ import uuid as _uuid+ sname = f"intg-consumer-{_uuid.uuid4().hex[:8]}"+ kin.create_stream(StreamName=sname, ShardCount=1)+ time.sleep(0.3)+ desc = kin.describe_stream(StreamName=sname)+ stream_arn = desc["StreamDescription"]["StreamARN"]+ resp = kin.register_stream_consumer(StreamARN=stream_arn, ConsumerName="my-consumer")+ assert resp["Consumer"]["ConsumerName"] == "my-consumer"+ assert resp["Consumer"]["ConsumerStatus"] == "ACTIVE"+ consumer_arn = resp["Consumer"]["ConsumerARN"]+ consumers = kin.list_stream_consumers(StreamARN=stream_arn)+ assert any(c["ConsumerName"] == "my-consumer" for c in consumers["Consumers"])+ desc_c = kin.describe_stream_consumer(ConsumerARN=consumer_arn)+ assert desc_c["ConsumerDescription"]["ConsumerName"] == "my-consumer"+ kin.deregister_stream_consumer(ConsumerARN=consumer_arn)+ consumers2 = kin.list_stream_consumers(StreamARN=stream_arn)+ assert not any(c["ConsumerName"] == "my-consumer" for c in consumers2["Consumers"])+ kin.delete_stream(StreamName=sname)+++# ========== SSM: label, resource tags ==========+++def test_ssm_label_parameter_version(ssm):+ import uuid as _uuid+ pname = f"/intg/label/{_uuid.uuid4().hex[:8]}"+ ssm.put_parameter(Name=pname, Value="v1", Type="String")+ ssm.put_parameter(Name=pname, Value="v2", Type="String", Overwrite=True)+ resp = ssm.label_parameter_version(Name=pname, ParameterVersion=1, Labels=["stable"])+ assert resp["ParameterVersion"] == 1+ assert resp["InvalidLabels"] == []+++def test_ssm_add_remove_tags(ssm):+ import uuid as _uuid+ pname = f"/intg/tagged/{_uuid.uuid4().hex[:8]}"+ ssm.put_parameter(Name=pname, Value="hello", Type="String")+ ssm.add_tags_to_resource(+ ResourceType="Parameter",+ ResourceId=pname,+ Tags=[{"Key": "env", "Value": "prod"}, {"Key": "team", "Value": "backend"}],+ )+ tags = ssm.list_tags_for_resource(ResourceType="Parameter", ResourceId=pname)+ tag_map = {t["Key"]: t["Value"] for t in tags["TagList"]}+ assert tag_map.get("env") == "prod"+ assert tag_map.get("team") == "backend"+ ssm.remove_tags_from_resource(ResourceType="Parameter", ResourceId=pname, TagKeys=["team"])+ tags2 = ssm.list_tags_for_resource(ResourceType="Parameter", ResourceId=pname)+ tag_map2 = {t["Key"]: t["Value"] for t in tags2["TagList"]}+ assert "team" not in tag_map2+ assert tag_map2.get("env") == "prod"+++# ========== CloudWatch Logs: retention, subscription filters, metric filters ==========+++def test_logs_retention_policy(logs):+ import uuid as _uuid+ group = f"/intg/retention/{_uuid.uuid4().hex[:8]}"+ logs.create_log_group(logGroupName=group)+ logs.put_retention_policy(logGroupName=group, retentionInDays=7)+ groups = logs.describe_log_groups(logGroupNamePrefix=group)["logGroups"]+ assert groups[0].get("retentionInDays") == 7+ logs.delete_retention_policy(logGroupName=group)+ groups2 = logs.describe_log_groups(logGroupNamePrefix=group)["logGroups"]+ assert groups2[0].get("retentionInDays") is None+++def test_logs_subscription_filter(logs):+ import uuid as _uuid+ group = f"/intg/subfilter/{_uuid.uuid4().hex[:8]}"+ logs.create_log_group(logGroupName=group)+ logs.put_subscription_filter(+ logGroupName=group,+ filterName="my-filter",+ filterPattern="ERROR",+ destinationArn="arn:aws:lambda:us-east-1:000000000000:function:log-handler",+ )+ resp = logs.describe_subscription_filters(logGroupName=group)+ assert any(f["filterName"] == "my-filter" for f in resp["subscriptionFilters"])+ logs.delete_subscription_filter(logGroupName=group, filterName="my-filter")+ resp2 = logs.describe_subscription_filters(logGroupName=group)+ assert not any(f["filterName"] == "my-filter" for f in resp2["subscriptionFilters"])+++def test_logs_metric_filter(logs):+ import uuid as _uuid+ group = f"/intg/metricfilter/{_uuid.uuid4().hex[:8]}"+ logs.create_log_group(logGroupName=group)+ logs.put_metric_filter(+ logGroupName=group,+ filterName="error-count",+ filterPattern="[ERROR]",+ metricTransformations=[{+ "metricName": "ErrorCount",+ "metricNamespace": "MyApp",+ "metricValue": "1",+ }],+ )+ resp = logs.describe_metric_filters(logGroupName=group)+ assert any(f["filterName"] == "error-count" for f in resp["metricFilters"])+ logs.delete_metric_filter(logGroupName=group, filterName="error-count")+ resp2 = logs.describe_metric_filters(logGroupName=group)+ assert not any(f["filterName"] == "error-count" for f in resp2.get("metricFilters", []))+++def test_logs_tag_log_group(logs):+ import uuid as _uuid+ group = f"/intg/tagging/{_uuid.uuid4().hex[:8]}"+ logs.create_log_group(logGroupName=group)+ logs.tag_log_group(logGroupName=group, tags={"project": "ministack", "env": "test"})+ resp = logs.list_tags_log_group(logGroupName=group)+ assert resp["tags"].get("project") == "ministack"+ logs.untag_log_group(logGroupName=group, tags=["project"])+ resp2 = logs.list_tags_log_group(logGroupName=group)+ assert "project" not in resp2["tags"]+++def test_logs_insights_start_query(logs):+ import uuid as _uuid+ group = f"/intg/insights/{_uuid.uuid4().hex[:8]}"+ logs.create_log_group(logGroupName=group)+ resp = logs.start_query(+ logGroupName=group,+ startTime=int(time.time()) - 3600,+ endTime=int(time.time()),+ queryString="fields @timestamp, @message | limit 10",+ )+ assert "queryId" in resp+ results = logs.get_query_results(queryId=resp["queryId"])+ assert results["status"] in ("Complete", "Running", "Scheduled")+++# ========== CloudWatch: composite alarm, describe_alarms_for_metric, alarm history ==========+++def test_cw_composite_alarm(cw):+ import uuid as _uuid+ child = f"intg-child-alarm-{_uuid.uuid4().hex[:8]}"+ composite = f"intg-comp-alarm-{_uuid.uuid4().hex[:8]}"+ cw.put_metric_alarm(+ AlarmName=child,+ ComparisonOperator="GreaterThanThreshold",+ EvaluationPeriods=1,+ MetricName="CPUUtilization",+ Namespace="AWS/EC2",+ Period=60,+ Statistic="Average",+ Threshold=80.0,+ )+ child_arn = cw.describe_alarms(AlarmNames=[child])["MetricAlarms"][0]["AlarmArn"]+ cw.put_composite_alarm(+ AlarmName=composite,+ AlarmRule=f"ALARM({child_arn})",+ AlarmDescription="composite test",+ )+ resp = cw.describe_alarms(AlarmNames=[composite], AlarmTypes=["CompositeAlarm"])+ assert any(a["AlarmName"] == composite for a in resp.get("CompositeAlarms", []))+ cw.delete_alarms(AlarmNames=[child, composite])+++def test_cw_describe_alarms_for_metric(cw):+ import uuid as _uuid+ alarm_name = f"intg-afm-{_uuid.uuid4().hex[:8]}"+ cw.put_metric_alarm(+ AlarmName=alarm_name,+ ComparisonOperator="GreaterThanThreshold",+ EvaluationPeriods=1,+ MetricName="NetworkIn",+ Namespace="AWS/EC2",+ Period=60,+ Statistic="Sum",+ Threshold=1000.0,+ )+ resp = cw.describe_alarms_for_metric(+ MetricName="NetworkIn",+ Namespace="AWS/EC2",+ )+ assert any(a["AlarmName"] == alarm_name for a in resp.get("MetricAlarms", []))+ cw.delete_alarms(AlarmNames=[alarm_name])+++def test_cw_describe_alarm_history(cw):+ import uuid as _uuid+ alarm_name = f"intg-hist-{_uuid.uuid4().hex[:8]}"+ cw.put_metric_alarm(+ AlarmName=alarm_name,+ ComparisonOperator="GreaterThanThreshold",+ EvaluationPeriods=1,+ MetricName="DiskReadOps",+ Namespace="AWS/EC2",+ Period=60,+ Statistic="Average",+ Threshold=50.0,+ )+ cw.set_alarm_state(AlarmName=alarm_name, StateValue="ALARM", StateReason="test")+ resp = cw.describe_alarm_history(AlarmName=alarm_name)+ assert "AlarmHistoryItems" in resp+ cw.delete_alarms(AlarmNames=[alarm_name])+++# ========== EventBridge: archives, permissions ==========+++def test_eb_archive(eb):+ import uuid as _uuid+ archive_name = f"intg-archive-{_uuid.uuid4().hex[:8]}"+ resp = eb.create_archive(+ ArchiveName=archive_name,+ EventSourceArn="arn:aws:events:us-east-1:000000000000:event-bus/default",+ Description="test archive",+ RetentionDays=7,+ )+ assert "ArchiveArn" in resp+ desc = eb.describe_archive(ArchiveName=archive_name)+ assert desc["ArchiveName"] == archive_name+ assert desc["RetentionDays"] == 7+ archives = eb.list_archives()+ assert any(a["ArchiveName"] == archive_name for a in archives["Archives"])+ eb.delete_archive(ArchiveName=archive_name)+ archives2 = eb.list_archives()+ assert not any(a["ArchiveName"] == archive_name for a in archives2["Archives"])+++def test_eb_put_remove_permission(eb):+ import uuid as _uuid+ bus_name = f"intg-perm-bus-{_uuid.uuid4().hex[:8]}"+ eb.create_event_bus(Name=bus_name)+ eb.put_permission(+ EventBusName=bus_name,+ StatementId="AllowAccount123",+ Action="events:PutEvents",+ Principal="123456789012",+ )+ # Describe bus — policy should be set (no explicit DescribeEventBus assert needed, just no error)+ eb.remove_permission(EventBusName=bus_name, StatementId="AllowAccount123")+ eb.delete_event_bus(Name=bus_name)+++# ========== DynamoDB: UpdateTable ==========+++def test_ddb_update_table(ddb):+ import uuid as _uuid+ table = f"intg-updtbl-{_uuid.uuid4().hex[:8]}"+ ddb.create_table(+ TableName=table,+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ resp = ddb.update_table(+ TableName=table,+ BillingMode="PROVISIONED",+ ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},+ )+ assert resp["TableDescription"]["TableName"] == table+ ddb.delete_table(TableName=table)+++# ========== S3: versioning, encryption, lifecycle, CORS, ACL ==========+++def test_s3_bucket_versioning(s3):+ s3.create_bucket(Bucket="intg-s3-versioning")+ s3.put_bucket_versioning(+ Bucket="intg-s3-versioning",+ VersioningConfiguration={"Status": "Enabled"},+ )+ resp = s3.get_bucket_versioning(Bucket="intg-s3-versioning")+ assert resp["Status"] == "Enabled"+++def test_s3_bucket_encryption(s3):+ s3.create_bucket(Bucket="intg-s3-enc")+ s3.put_bucket_encryption(+ Bucket="intg-s3-enc",+ ServerSideEncryptionConfiguration={+ "Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"}}]+ },+ )+ resp = s3.get_bucket_encryption(Bucket="intg-s3-enc")+ rules = resp["ServerSideEncryptionConfiguration"]["Rules"]+ assert rules[0]["ApplyServerSideEncryptionByDefault"]["SSEAlgorithm"] == "AES256"+ s3.delete_bucket_encryption(Bucket="intg-s3-enc")+ with pytest.raises(ClientError) as exc:+ s3.get_bucket_encryption(Bucket="intg-s3-enc")+ assert exc.value.response["Error"]["Code"] == "ServerSideEncryptionConfigurationNotFoundError"+++def test_s3_bucket_lifecycle(s3):+ s3.create_bucket(Bucket="intg-s3-lifecycle")+ s3.put_bucket_lifecycle_configuration(+ Bucket="intg-s3-lifecycle",+ LifecycleConfiguration={+ "Rules": [{+ "ID": "expire-old",+ "Status": "Enabled",+ "Filter": {"Prefix": "logs/"},+ "Expiration": {"Days": 30},+ }]+ },+ )+ resp = s3.get_bucket_lifecycle_configuration(Bucket="intg-s3-lifecycle")+ assert resp["Rules"][0]["ID"] == "expire-old"+ s3.delete_bucket_lifecycle(Bucket="intg-s3-lifecycle")+ with pytest.raises(ClientError) as exc:+ s3.get_bucket_lifecycle_configuration(Bucket="intg-s3-lifecycle")+ assert exc.value.response["Error"]["Code"] == "NoSuchLifecycleConfiguration"+++def test_s3_bucket_cors(s3):+ s3.create_bucket(Bucket="intg-s3-cors")+ s3.put_bucket_cors(+ Bucket="intg-s3-cors",+ CORSConfiguration={+ "CORSRules": [{+ "AllowedHeaders": ["*"],+ "AllowedMethods": ["GET", "PUT"],+ "AllowedOrigins": ["https://example.com"],+ "MaxAgeSeconds": 3000,+ }]+ },+ )+ resp = s3.get_bucket_cors(Bucket="intg-s3-cors")+ assert resp["CORSRules"][0]["AllowedOrigins"] == ["https://example.com"]+ s3.delete_bucket_cors(Bucket="intg-s3-cors")+ with pytest.raises(ClientError) as exc:+ s3.get_bucket_cors(Bucket="intg-s3-cors")+ assert exc.value.response["Error"]["Code"] == "NoSuchCORSConfiguration"+++def test_s3_bucket_acl(s3):+ s3.create_bucket(Bucket="intg-s3-acl")+ resp = s3.get_bucket_acl(Bucket="intg-s3-acl")+ assert "Owner" in resp+ assert "Grants" in resp+++# ========== Athena: UpdateWorkGroup, BatchGetNamedQuery, BatchGetQueryExecution ==========+++def test_athena_update_workgroup(athena):+ import uuid as _uuid+ wg = f"intg-wg-update-{_uuid.uuid4().hex[:8]}"+ athena.create_work_group(Name=wg, Description="before")+ athena.update_work_group(WorkGroup=wg, Description="after")+ resp = athena.get_work_group(WorkGroup=wg)+ assert resp["WorkGroup"]["Description"] == "after"+ athena.delete_work_group(WorkGroup=wg, RecursiveDeleteOption=True)+++def test_athena_batch_get_named_query(athena):+ import uuid as _uuid+ wg = f"intg-wg-batch-{_uuid.uuid4().hex[:8]}"+ athena.create_work_group(Name=wg)+ nq1 = athena.create_named_query(+ Name="q1", Database="default",+ QueryString="SELECT 1", WorkGroup=wg,+ )["NamedQueryId"]+ nq2 = athena.create_named_query(+ Name="q2", Database="default",+ QueryString="SELECT 2", WorkGroup=wg,+ )["NamedQueryId"]+ resp = athena.batch_get_named_query(NamedQueryIds=[nq1, nq2, "nonexistent-id"])+ assert len(resp["NamedQueries"]) == 2+ assert len(resp["UnprocessedNamedQueryIds"]) == 1+ athena.delete_work_group(WorkGroup=wg, RecursiveDeleteOption=True)+++def test_athena_batch_get_query_execution(athena):+ qid1 = athena.start_query_execution(+ QueryString="SELECT 42",+ ResultConfiguration={"OutputLocation": "s3://athena-results/"},+ )["QueryExecutionId"]+ qid2 = athena.start_query_execution(+ QueryString="SELECT 99",+ ResultConfiguration={"OutputLocation": "s3://athena-results/"},+ )["QueryExecutionId"]+ time.sleep(1.0)+ resp = athena.batch_get_query_execution(QueryExecutionIds=[qid1, qid2, "nonexistent-id"])+ assert len(resp["QueryExecutions"]) == 2+ assert len(resp["UnprocessedQueryExecutionIds"]) == 1+++# ===================================================================+# SNS → Lambda fanout+# ===================================================================++import uuid as _uuid_mod+++def test_sns_to_lambda_fanout(lam, sns):+ """SNS publish with lambda protocol invokes the function synchronously."""+ import uuid as _uuid_mod+ fn = f"intg-sns-lam-{_uuid_mod.uuid4().hex[:8]}"+ # Handler records the event on a module-level list so we can inspect it+ code = (+ "received = []\n"+ "def handler(event, context):\n"+ " received.append(event)\n"+ " return {'ok': True}\n"+ )+ lam.create_function(+ FunctionName=fn,+ Runtime="python3.9",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(code)},+ )+ func_arn = f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"++ topic_arn = sns.create_topic(Name=f"intg-sns-lam-topic-{_uuid_mod.uuid4().hex[:8]}")["TopicArn"]+ sns.subscribe(TopicArn=topic_arn, Protocol="lambda", Endpoint=func_arn)++ # Publish — should not raise; Lambda invoked synchronously+ resp = sns.publish(TopicArn=topic_arn, Message="hello-lambda")+ assert "MessageId" in resp+++# ===================================================================+# DynamoDB TTL expiry enforcement+# ===================================================================++def test_ddb_ttl_expiry(ddb):+ """TTL setting is stored and reported correctly; expiry enforcement is in the background reaper."""+ import uuid as _uuid_mod+ table = f"intg-ttl-exp-{_uuid_mod.uuid4().hex[:8]}"+ ddb.create_table(+ TableName=table,+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ ddb.update_time_to_live(+ TableName=table,+ TimeToLiveSpecification={"Enabled": True, "AttributeName": "expires_at"},+ )+ past = int(time.time()) - 10+ ddb.put_item(+ TableName=table,+ Item={+ "pk": {"S": "expired-item"},+ "expires_at": {"N": str(past)},+ "data": {"S": "should-be-gone"},+ },+ )+ # Item present immediately (reaper hasn't run yet)+ resp = ddb.get_item(TableName=table, Key={"pk": {"S": "expired-item"}})+ assert "Item" in resp++ # TTL setting is correctly reflected in DescribeTimeToLive+ desc = ddb.describe_time_to_live(TableName=table)["TimeToLiveDescription"]+ assert desc["TimeToLiveStatus"] == "ENABLED"+ assert desc["AttributeName"] == "expires_at"+++# ===================================================================+# Lambda Function URL Config+# ===================================================================++def test_lambda_function_url_config(lam):+ """CreateFunctionUrlConfig / Get / Update / Delete / List lifecycle."""+ import uuid as _uuid_mod+ fn = f"intg-url-cfg-{_uuid_mod.uuid4().hex[:8]}"+ lam.create_function(+ FunctionName=fn,+ Runtime="python3.9",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(_LAMBDA_CODE)},+ )++ # Create+ resp = lam.create_function_url_config(FunctionName=fn, AuthType="NONE")+ assert resp["AuthType"] == "NONE"+ assert "FunctionUrl" in resp+ url = resp["FunctionUrl"]++ # Get+ got = lam.get_function_url_config(FunctionName=fn)+ assert got["FunctionUrl"] == url++ # Update+ updated = lam.update_function_url_config(+ FunctionName=fn,+ AuthType="AWS_IAM",+ Cors={"AllowOrigins": ["*"]},+ )+ assert updated["AuthType"] == "AWS_IAM"+ assert updated["Cors"]["AllowOrigins"] == ["*"]++ # List+ listed = lam.list_function_url_configs(FunctionName=fn)+ assert any(c["FunctionUrl"] == url for c in listed["FunctionUrlConfigs"])++ # Delete+ lam.delete_function_url_config(FunctionName=fn)+ with pytest.raises(ClientError) as exc:+ lam.get_function_url_config(FunctionName=fn)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"