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(appconfig): gradual rollout, alarm rollback and polling behavior (#2075)
Luke Dutton1738d8b8d630
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6f8899c6..4ce6c0a5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,13 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added+- **AppConfig — gradual rollout and alarm rollback** — deployments used to complete as soon as they started. They now move through `DEPLOYING`, `BAKING` and `COMPLETE` on the strategy's schedule, and `PercentageComplete`, `EventLog` and the environment `State` follow along. A CloudWatch alarm in the environment's `Monitors` that goes to `ALARM` before the bake ends rolls the deployment back. Starting a deployment while another is in progress, or with a stale `LatestDeploymentNumber`, returns `ConflictException`. Each configuration session switches to the new version once the rollout reaches it, so a fleet of AppConfig Agent sidecars picks it up gradually. `APPCONFIG_DEPLOYMENT_MINUTE_SECONDS` sets the real seconds per strategy minute; the default `0` keeps the old behavior. Contributed by @Jolley71717.++### Fixed++- **AppConfig — `GetLatestConfiguration` returns an empty body when nothing changed** — it returned the full configuration on every poll. It now also returns `Version-Label` and uses `RequiredMinimumPollIntervalInSeconds` as the poll interval, and `CreateHostedConfigurationVersion` stores `VersionLabel`. Contributed by @Jolley71717.+- **AppConfig — `StopDeployment` follows the documented states** — it marked any deployment `ROLLED_BACK`. It now rolls back an in-progress deployment, reverts a completed one only with `AllowRevert` and within 72 hours (`REVERTED`), and returns `BadRequestException` otherwise. Contributed by @Jolley71717.+- **API Gateway v1 — `AWS` integrations targeting SQS** — non-proxy integrations whose URI names `sqs:path/{account}/{queue}` now reach the queue: the matching `requestTemplates` entry is rendered with the `$input.body`, `$input.json('<json-path>')`, `$input.params('<name>')` and `$util.urlEncode(...)` subset (a request with no matching template passes its body through as the form-encoded Query call), the rendered `Action` dispatch runs against the queue's own account and region, and the backend reply or error flows through `integrationResponses` — `selectionPattern` matched against the backend status code or error body, else the default response — including `responseTemplates` and `method.response.header.*` parameters. Other `AWS` service URIs still take the Lambda path. Closes #2045. Contributed by @pingedbrain.- **IoT — domain configurations** — `CreateDomainConfiguration`, `DescribeDomainConfiguration`, `ListDomainConfigurations`, `UpdateDomainConfiguration` and `DeleteDomainConfiguration`, and the CloudFormation type `AWS::IoT::DomainConfiguration`, were missing. The list now shows the `iot:Data-ATS` and `iot:CredentialProvider` configurations IoT owns (their `domainName` is the `DescribeEndpoint` address). A configuration without a server certificate is AWS-managed with a generated `-ats` host, one with an ACM certificate is customer-managed, and requests are validated with AWS's messages (TLS security policy, authentication type and protocol combinations, certificates, the IoT-owned entries). As on AWS, only a DISABLED configuration can be deleted, and an AWS-managed one only seven days after it was disabled; CloudFormation leaves a configuration DISABLED unless the template enables it, and disables it before deleting it, so the stack delete of an AWS-managed one fails with `DELETE_FAILED`. The broker does not serve a configured domain. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex eb8d1933..5b1f6b70 100644--- a/README.md+++ b/README.md@@ -118,6 +118,7 @@ The config endpoint supports these keys:| `athena.ATHENA_DATA_DIR` | Directory for Athena DuckDB data files || `stepfunctions._sfn_mock_config` | SFN mock config (AWS SFN Local compatible) || `stepfunctions._SFN_WAIT_SCALE` | Scale factor for Wait state durations and retry sleeps (`0` = skip all waits) |+| `appconfig._DEPLOYMENT_MINUTE_SECONDS` | Real seconds per minute of an AppConfig deployment strategy (`0` = deployments complete as they start, `60` = AWS pace) |To set region or account ID, use environment variables at startup:@@ -641,7 +642,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i| **S3 Files** | CreateFileSystem, GetFileSystem, ListFileSystems, DeleteFileSystem, CreateMountTarget, GetMountTarget, ListMountTargets, UpdateMountTarget, DeleteMountTarget, CreateAccessPoint, GetAccessPoint, ListAccessPoints, DeleteAccessPoint, GetFileSystemPolicy, PutFileSystemPolicy, DeleteFileSystemPolicy, GetSynchronizationConfiguration, PutSynchronizationConfiguration, TagResource, UntagResource, ListTagsForResource | 21 operations; control plane for the new S3 Files service (launched April 2026); file systems, mount targets, access points, policies || **AutoScaling** | CreateAutoScalingGroup, DescribeAutoScalingGroups, UpdateAutoScalingGroup, DeleteAutoScalingGroup, SetDesiredCapacity, DescribeAutoScalingInstances, CreateLaunchConfiguration, DescribeLaunchConfigurations, DeleteLaunchConfiguration, PutScalingPolicy, DescribePolicies, DeletePolicy, PutLifecycleHook, DescribeLifecycleHooks, DeleteLifecycleHook, CompleteLifecycleAction, RecordLifecycleActionHeartbeat, PutScheduledUpdateGroupAction, DescribeScheduledActions, DeleteScheduledAction, CreateOrUpdateTags, DescribeTags, DeleteTags | 24 actions; in-memory state — no real instances, but groups report `DesiredCapacity` in-service instances so Terraform's `aws_autoscaling_group` capacity waiter converges; full ASG lifecycle (launch configs, scaling policies, lifecycle hooks, scheduled actions, tags); CDK/Terraform compatible || **CodeBuild** | CreateProject, BatchGetProjects, ListProjects, UpdateProject, DeleteProject, StartBuild, BatchGetBuilds, StopBuild, ListBuilds, ListBuildsForProject, BatchDeleteBuilds | 11 actions; project and build metadata stored in-memory; builds complete immediately with SUCCEEDED status by default. Set `MINISTACK_CODEBUILD_EXECUTE=1` and mount the Docker socket to **really run them**: the project's inline buildspec goes to the official AWS CodeBuild local agent, which runs the phases in `environment.image`, and `BatchGetBuilds` reports live `phases` with a real `SUCCEEDED`/`FAILED` outcome. Execution needs the workspace shared with the host at the **same path** (`-v /tmp/ministack-codebuild:/tmp/ministack-codebuild`), because the agent bind-mounts it into the build container; a build gets `AWS_ENDPOINT_URL` pointing back at MiniStack, honours `timeoutInMinutes`, and is stopped by `StopBuild`. An executed build streams the agent output into its `logs.groupName` / `logs.streamName`, so `aws logs tail` reads the build log back |-| **AppConfig** | CreateApplication, GetApplication, ListApplications, UpdateApplication, DeleteApplication, CreateEnvironment, GetEnvironment, ListEnvironments, UpdateEnvironment, DeleteEnvironment, CreateConfigurationProfile, GetConfigurationProfile, ListConfigurationProfiles, UpdateConfigurationProfile, DeleteConfigurationProfile, CreateHostedConfigurationVersion, GetHostedConfigurationVersion, ListHostedConfigurationVersions, DeleteHostedConfigurationVersion, CreateDeploymentStrategy, GetDeploymentStrategy, ListDeploymentStrategies, UpdateDeploymentStrategy, DeleteDeploymentStrategy, StartDeployment, GetDeployment, ListDeployments, StopDeployment, TagResource, UntagResource, ListTagsForResource, StartConfigurationSession, GetLatestConfiguration | 33 operations; control plane + data plane; hosted configuration versions; the AWS-predefined deployment strategies (4) are listed and immutable; deployments complete immediately; session-based configuration retrieval with token rotation |+| **AppConfig** | CreateApplication, GetApplication, ListApplications, UpdateApplication, DeleteApplication, CreateEnvironment, GetEnvironment, ListEnvironments, UpdateEnvironment, DeleteEnvironment, CreateConfigurationProfile, GetConfigurationProfile, ListConfigurationProfiles, UpdateConfigurationProfile, DeleteConfigurationProfile, CreateHostedConfigurationVersion, GetHostedConfigurationVersion, ListHostedConfigurationVersions, DeleteHostedConfigurationVersion, CreateDeploymentStrategy, GetDeploymentStrategy, ListDeploymentStrategies, UpdateDeploymentStrategy, DeleteDeploymentStrategy, StartDeployment, GetDeployment, ListDeployments, StopDeployment, TagResource, UntagResource, ListTagsForResource, StartConfigurationSession, GetLatestConfiguration | 33 operations; control plane + data plane; hosted configuration versions; the AWS-predefined deployment strategies (4) are listed and immutable; deployments move through `DEPLOYING`, `BAKING` and `COMPLETE` on the strategy's schedule (`LINEAR` or `EXPONENTIAL` steps, then the bake time), with `PercentageComplete`, the event log and the environment `State` reported along the way; `APPCONFIG_DEPLOYMENT_MINUTE_SECONDS` sets the real seconds per strategy minute (default `0`, deployments complete immediately); a `Monitors` alarm that goes to `ALARM` before the bake ends rolls the deployment back; one deployment per environment at a time (`ConflictException`, also for a stale `LatestDeploymentNumber`); `StopDeployment` rolls back an in-progress deployment and, with `AllowRevert`, reverts a completed one within 72 hours; during a rollout a session gets the new version once the rollout reaches its fixed slot (MiniStack's choice, since AWS does not document how it picks targets); `GetLatestConfiguration` returns an empty body when the session already has the latest version, plus `Version-Label`, and uses `RequiredMinimumPollIntervalInSeconds` as the poll interval || **Transfer Family** | CreateServer, DescribeServer, DeleteServer, ListServers, StartServer, StopServer, CreateUser, DescribeUser, DeleteUser, ListUsers, ImportSshPublicKey, DeleteSshPublicKey | 12 operations; **real SFTP listener** on `:2222` (override with `SFTP_PORT`) backed by S3 — `ls`, `put`, `get`, `mkdir`, `rename` work end-to-end against the local S3 emulator; `SFTP_PORT_PER_SERVER=1` allocates one port per `CreateServer` from `SFTP_BASE_PORT` (default 2300); SSH key auth scans every user across every server and account; `LOGICAL` and `PATH` home-directory mappings; host key persists across restarts when `PERSIST_STATE=1` || **IoT Jobs** | Control plane (`iot`): CreateJob, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, DescribeJobExecution, CancelJobExecution, CreateJobTemplate, DescribeJobTemplate, ListJobTemplates, DeleteJobTemplate; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 13 control-plane + 4 device data-plane operations sharing one store. A job created with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a request member replaces the template's. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED, TIMED_OUT}`; an execution past its `timeoutConfig.inProgressTimeoutInMinutes`, or past the `stepTimeoutInMinutes` the device reported, becomes `TIMED_OUT`, and the device plane reports `approximateSecondsBeforeTimedOut` while it runs. `REMOVED` is modeled and counted in `jobProcessDetails` but nothing sets it: deleting a thing DELETES its executions (freeing a job that was only waiting on that thing) rather than marking them `REMOVED`. `versionNumber` gives optimistic concurrency: every transition bumps it and a stale `expectedVersion` is rejected with a 409 whose message carries the current version — coded `VersionConflictException` on the control plane and `InvalidStateTransitionException` on the device plane, each as its own service model declares. `executionNumber` is write-once (always 1: an execution is never re-queued). Devices may only report `IN_PROGRESS` / `SUCCEEDED` / `FAILED` / `REJECTED` via `UpdateJobExecution`; targets are thing or thing-group ARNs — `SNAPSHOT` jobs resolve group membership once at creation, `CONTINUOUS` jobs also pick up things added to a target group later, and a target must name a thing or thing group in the caller's own account and region (anything else is `ResourceNotFoundException`, since it would resolve to no devices at all); a non-continuous job auto-`COMPLETED`s (with `jobProcessDetails` counts) once every execution is terminal. **`documentSource` is not fetched**: a job created with an S3 `documentSource` serves a `{"documentSource": "<url>"}` placeholder as its document rather than the object's content, so the lifecycle still runs — pass `document` when the content matters; a job template with a `documentSource` stores the same placeholder. **Timestamps are epoch seconds on every plane, as AWS documents**: control-plane responses use `timestamp` shapes (boto3 parses them to datetimes) while `iot-jobs-data` responses carry whole-second integer `long`s. **Jobs over MQTT**: the reserved `$aws/things/<thing>/jobs/#` request topics (`get`, `start-next`, `<jobId>/get` incl. `$next`, `<jobId>/update`) answer on their `accepted`/`rejected` topics from the same store as the HTTP plane (`jobDocument` as a JSON object over MQTT, a string over HTTP, as on AWS; rejections carry the string `ErrorCode` values and the execution's state on version and state-transition conflicts); `notify` fires when the pending set changes and `notify-next` when the queue front changes; `stepTimeoutInMinutes` and `executionNumber` are accepted but ignored. Job state persists with the IoT store when `PERSIST_STATE=1` || **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, ListThingGroupsForThing, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, ListCertificatesByCA, CreateProvisioningTemplate, DescribeProvisioningTemplate, ListProvisioningTemplates, UpdateProvisioningTemplate, DeleteProvisioningTemplate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub, DescribeEventConfigurations, UpdateEventConfigurations | 57 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; a **provisioning-template registry** (`CreateProvisioningTemplate` and friends) — storage + CRUD only, so `provisioningRoleArn` is presence-checked but not resolved and the fleet-provisioning MQTT workflow (`$aws/provisioning-templates/...`) is not implemented; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry; the broker publishes the presence and subscription lifecycle events (`$aws/events/presence/connected\|disconnected/{clientId}`, `$aws/events/subscriptions/subscribed\|unsubscribed/{clientId}`) |@@ -930,6 +931,7 @@ come from `repositoryCredentials.credentialsParameter` (a Secrets Manager secret| `MINISTACK_MSK_BOOTSTRAP_TLS` | _(unset)_ | TLS bootstrap string (`BootstrapBrokerStringTls`) || `MINISTACK_MSK_BOOTSTRAP_SASL_SCRAM` | _(unset)_ | SASL/SCRAM bootstrap string (`BootstrapBrokerStringSaslScram`) || `MINISTACK_MSK_BOOTSTRAP_SASL_IAM` | _(unset)_ | SASL/IAM bootstrap string (`BootstrapBrokerStringSaslIam`) |+| `APPCONFIG_DEPLOYMENT_MINUTE_SECONDS` | `0` | Real seconds that stand in for one minute of an AppConfig deployment strategy's `DeploymentDurationInMinutes` and `FinalBakeTimeInMinutes`. `0` completes every deployment as it starts; `60` runs at AWS's pace; `1` runs a 30-minute strategy in 30 seconds. Also settable without a restart by posting `{"appconfig._DEPLOYMENT_MINUTE_SECONDS": 1}` to `/_ministack/config` || `TRANSLATE_JOB_RUN_SECONDS` | `2` | Wall-clock time a Translate batch job spends between `SUBMITTED` and `COMPLETED`. Set `0` to complete immediately, or raise it when a test needs to observe `IN_PROGRESS` or stop a running job. Also settable without a restart by posting `{"translate._JOB_RUN_SECONDS": 10}` to `/_ministack/config` |### API Gateway HTTP proxy execution modeldiff --git a/ministack/app.py b/ministack/app.pyindex 8ec88c67..d951c8b4 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1367,6 +1367,7 @@ async def _handle_admin_config_request(path: str, method: str, body: bytes):"stepfunctions._SFN_WAIT_SCALE","translate._JOB_RUN_SECONDS","transcribe._JOB_RUN_SECONDS",+ "appconfig._DEPLOYMENT_MINUTE_SECONDS","lambda_svc.LAMBDA_EXECUTOR","cloudtrail._recording_enabled","alb.TARGET_CONNECT_TIMEOUT",@@ -1392,6 +1393,7 @@ async def _handle_admin_config_request(path: str, method: str, body: bytes):"stepfunctions._SFN_WAIT_SCALE","translate._JOB_RUN_SECONDS","transcribe._JOB_RUN_SECONDS",+ "appconfig._DEPLOYMENT_MINUTE_SECONDS",):try:float_value = float(value)diff --git a/ministack/services/appconfig.py b/ministack/services/appconfig.pyindex e026c522..af8605c9 100644--- a/ministack/services/appconfig.py+++ b/ministack/services/appconfig.py@@ -28,6 +28,7 @@ Data Plane (appconfigdata):"""import copy+import hashlibimport jsonimport loggingimport os@@ -42,6 +43,15 @@ logger = logging.getLogger("appconfig")REGION = os.environ.get("MINISTACK_REGION", "us-east-1")+# APPCONFIG_DEPLOYMENT_MINUTE_SECONDS: real seconds that stand in for one minute of a+# deployment strategy's DeploymentDurationInMinutes and FinalBakeTimeInMinutes. 0 (the+# default) runs every deployment to COMPLETE as it starts; 60 keeps AWS's pace. Also+# settable at runtime through /_ministack/config, so a test can pin the pace.+_DEPLOYMENT_MINUTE_SECONDS = float(os.environ.get("APPCONFIG_DEPLOYMENT_MINUTE_SECONDS", "0"))++# Next-Poll-Interval-In-Seconds for a session that set no RequiredMinimumPollIntervalInSeconds.+_DEFAULT_POLL_INTERVAL_SECONDS = 30+# ---------------------------------------------------------------------------# State# ---------------------------------------------------------------------------@@ -103,6 +113,10 @@ def _now_iso():return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())+def _iso(epoch):+ return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(epoch)) + f".{int(epoch * 1000) % 1000:03d}Z"++def _app_arn(app_id):return f"arn:aws:appconfig:{get_region()}:{get_account_id()}:application/{app_id}"@@ -384,7 +398,7 @@ def _next_hosted_version_number(app_id, profile_id):return number-def _create_hosted_configuration_version(app_id, profile_id, body, content_type):+def _create_hosted_configuration_version(app_id, profile_id, body, content_type, version_label=None):if f"{app_id}/{profile_id}" not in _config_profiles:return _error(404, "ResourceNotFoundException", f"Configuration profile {profile_id} not found")@@ -398,6 +412,8 @@ def _create_hosted_configuration_version(app_id, profile_id, body, content_type)"Content": body,"Description": "",}+ if version_label:+ record["VersionLabel"] = version_label_hosted_versions[f"{app_id}/{profile_id}/{version_number}"] = recordlogger.info("CreateHostedConfigurationVersion: %s/%s v%d", app_id, profile_id, version_number)@@ -407,6 +423,8 @@ def _create_hosted_configuration_version(app_id, profile_id, body, content_type)"Configuration-Profile-Id": profile_id,"Version-Number": str(version_number),}+ if version_label:+ resp_headers["VersionLabel"] = version_labelreturn 201, resp_headers, body if isinstance(body, bytes) else body.encode("utf-8")@@ -423,6 +441,8 @@ def _get_hosted_configuration_version(app_id, profile_id, version_number):"Configuration-Profile-Id": profile_id,"Version-Number": str(version_number),}+ if record.get("VersionLabel"):+ resp_headers["VersionLabel"] = record["VersionLabel"]return 200, resp_headers, content if isinstance(content, bytes) else content.encode("utf-8")@@ -439,6 +459,7 @@ def _list_hosted_configuration_versions(app_id, profile_id, query):"VersionNumber": v["VersionNumber"],"ContentType": v["ContentType"],"Description": v.get("Description", ""),+ **({"VersionLabel": v["VersionLabel"]} if v.get("VersionLabel") else {}),})return _json(200, {"Items": items[:max_results]})@@ -569,6 +590,146 @@ def _delete_deployment_strategy(strategy_id):# ---------------------------------------------------------------------------+_IN_PROGRESS_STATES = ("DEPLOYING", "BAKING")+_ENVIRONMENT_STATE_BY_DEPLOYMENT_STATE = {+ "DEPLOYING": "DEPLOYING",+ "BAKING": "DEPLOYING",+ "COMPLETE": "READY_FOR_DEPLOYMENT",+ "ROLLED_BACK": "ROLLED_BACK",+ "REVERTED": "REVERTED",+}+# StopDeployment's docs: "AppConfig only allows a revert within 72 hours of+# deployment completion."+_REVERT_WINDOW_SECONDS = 72 * 3600+++def _rollout_steps(growth_type, growth_factor):+ """The percentages a deployment passes through, ending at 100.++ LINEAR adds GrowthFactor each step; EXPONENTIAL follows the G*(2^N) formula+ from the CreateDeploymentStrategy docs.+ """+ # The model's floor for GrowthFactor; CreateDeploymentStrategy stores what it is given.+ growth_factor = max(float(growth_factor or 100.0), 1.0)+ steps = []+ step = 1+ while True:+ if growth_type == "EXPONENTIAL":+ pct = growth_factor * (2 ** (step - 1))+ else:+ pct = growth_factor * step+ if pct >= 100.0:+ break+ steps.append(round(pct, 2))+ step += 1+ steps.append(100.0)+ return steps+++def _add_deployment_event(record, event_type, triggered_by, description, at):+ record.setdefault("_Events", []).append({+ "EventType": event_type,+ "TriggeredBy": triggered_by,+ "Description": description,+ "ActionInvocations": [],+ "OccurredAt": _iso(at),+ })+++def _first_monitor_alarm(app_id, env_id, start, end):+ """The (alarm ARN, time) of the first environment monitor in ALARM in [start, end]."""+ from ministack.services import cloudwatch++ env = _environments.get(f"{app_id}/{env_id}") or {}+ fired = []+ for monitor in env.get("Monitors") or []:+ alarm_arn = monitor.get("AlarmArn", "")+ at = cloudwatch.first_alarm_time(alarm_arn, start, end)+ if at is not None:+ fired.append((at, alarm_arn))+ if not fired:+ return None+ at, alarm_arn = min(fired)+ return alarm_arn, at+++def _roll_back(record, triggered_by, initiator, at):+ record["State"] = "ROLLED_BACK"+ _add_deployment_event(record, "ROLLBACK_STARTED", triggered_by, f"Rollback initiated by {initiator}", at)+ _add_deployment_event(record, "ROLLBACK_COMPLETED", triggered_by, "Rollback completed", at)+++def _advance_deployment(record, now):+ """Bring an in-progress deployment up to ``now``.++ Steps are spread evenly over DeploymentDurationInMinutes, the last one+ reaching 100% when the duration ends; the deployment then bakes for+ FinalBakeTimeInMinutes. A monitored alarm in ALARM at any point before the+ bake ends rolls it back at that moment.+ """+ if record.get("State") not in _IN_PROGRESS_STATES or "_StartedEpoch" not in record:+ return+ minute = _DEPLOYMENT_MINUTE_SECONDS+ started = record["_StartedEpoch"]+ steps = _rollout_steps(record["GrowthType"], record["GrowthFactor"])+ duration = float(record["DeploymentDurationInMinutes"]) * minute+ step_gap = duration / len(steps)+ bake = float(record["FinalBakeTimeInMinutes"]) * minute+ complete_at = started + duration + bake++ alarm = _first_monitor_alarm(record["ApplicationId"], record["EnvironmentId"],+ started, min(now, complete_at))+ horizon = alarm[1] if alarm else now++ for index, pct in enumerate(steps, start=1):+ at = started + index * step_gap+ # A step due at the moment an alarm fires is not taken.+ if at > horizon or (alarm and at >= horizon):+ break+ if pct > record["PercentageComplete"]:+ record["PercentageComplete"] = pct+ _add_deployment_event(record, "PERCENTAGE_UPDATED", "APPCONFIG",+ f"Deployed to {pct:g}% of targets", at)+ if record["State"] == "DEPLOYING" and record["PercentageComplete"] >= 100.0:+ record["State"] = "BAKING"+ if bake > 0:+ _add_deployment_event(record, "BAKE_TIME_STARTED", "APPCONFIG", "Bake time started",+ started + duration)++ if alarm:+ _roll_back(record, "CLOUDWATCH_ALARM", alarm[0], alarm[1])+ return+ if complete_at <= now:+ record["State"] = "COMPLETE"+ record["_CompletedEpoch"] = complete_at+ record["CompletedAt"] = _iso(complete_at)+ _add_deployment_event(record, "DEPLOYMENT_COMPLETED", "APPCONFIG", "Deployment completed", complete_at)+++def _environment_deployments(app_id, env_id):+ prefix = f"{app_id}/{env_id}/"+ return sorted((v for k, v in _deployments.items() if k.startswith(prefix)),+ key=lambda d: d["DeploymentNumber"])+++def _refresh_environment(app_id, env_id):+ """Advance the environment's deployments to now and derive its State from the latest."""+ deployments = _environment_deployments(app_id, env_id)+ now = time.time()+ for deployment in deployments:+ _advance_deployment(deployment, now)+ env = _environments.get(f"{app_id}/{env_id}")+ if env is not None and deployments:+ env["State"] = _ENVIRONMENT_STATE_BY_DEPLOYMENT_STATE.get(deployments[-1]["State"], env["State"])+ return deployments+++def _deployment_view(record):+ view = {k: v for k, v in record.items() if not k.startswith("_")}+ view["EventLog"] = list(reversed(record.get("_Events", []))) # most recent first+ return view++def _start_deployment(app_id, env_id, body):if app_id not in _applications:return _error(404, "ResourceNotFoundException", f"Application {app_id} not found")@@ -587,13 +748,21 @@ def _start_deployment(app_id, env_id, body):return _error(404, "ResourceNotFoundException",f"DeploymentStrategy with Id {strategy_id} could not be found.")- existing = [- v for k, v in _deployments.items()- if k.startswith(f"{app_id}/{env_id}/")- ]- deploy_num = len(existing) + 1-- now = _now_iso()+ existing = _refresh_environment(app_id, env_id)+ latest_number = existing[-1]["DeploymentNumber"] if existing else 0+ expected = body.get("LatestDeploymentNumber")+ if expected is not None and expected != latest_number:+ return _error(409, "ConflictException",+ f"LatestDeploymentNumber {expected} does not match the latest deployment "+ f"number {latest_number}.")+ in_progress = [d for d in existing if d["State"] in _IN_PROGRESS_STATES]+ if in_progress:+ return _error(409, "ConflictException",+ f"Deployment {in_progress[-1]['DeploymentNumber']} is already in progress "+ f"in environment {env_id}.")+ deploy_num = latest_number + 1++ now = time.time()record = {"ApplicationId": app_id,"EnvironmentId": env_id,@@ -605,22 +774,28 @@ def _start_deployment(app_id, env_id, body):"ConfigurationVersion": version,"Description": body.get("Description", ""),**_deployment_params_from_strategy(strategy),- "State": "COMPLETE",- "PercentageComplete": 100.0,- "StartedAt": now,- "CompletedAt": now,+ "State": "DEPLOYING",+ "PercentageComplete": 0.0,+ "StartedAt": _iso(now),+ "_StartedEpoch": now,}+ version_label = _hosted_versions.get(f"{app_id}/{profile_id}/{version}", {}).get("VersionLabel")+ if version_label:+ record["VersionLabel"] = version_label+ _add_deployment_event(record, "DEPLOYMENT_STARTED", "USER", "Deployment started", now)_deployments[f"{app_id}/{env_id}/{deploy_num}"] = record+ _refresh_environment(app_id, env_id)logger.info("StartDeployment: %s/%s #%d (profile=%s, version=%s)",app_id, env_id, deploy_num, profile_id, version)- return _json(201, record)+ return _json(201, _deployment_view(record))def _get_deployment(app_id, env_id, deploy_num):+ _refresh_environment(app_id, env_id)record = _deployments.get(f"{app_id}/{env_id}/{deploy_num}")if not record:return _error(404, "ResourceNotFoundException", f"Deployment {deploy_num} not found")- return _json(200, record)+ return _json(200, _deployment_view(record))def _list_deployments(app_id, env_id, query):@@ -628,30 +803,48 @@ def _list_deployments(app_id, env_id, query):return _error(404, "ResourceNotFoundException", f"Environment {env_id} not found")max_results = int(query.get("max_results", 50))items = []- for k, v in _deployments.items():- if k.startswith(f"{app_id}/{env_id}/"):- items.append({- "DeploymentNumber": v["DeploymentNumber"],- "ConfigurationName": v.get("ConfigurationName", ""),- "ConfigurationVersion": v.get("ConfigurationVersion", ""),- "DeploymentDurationInMinutes": v.get("DeploymentDurationInMinutes", 0),- "GrowthType": v.get("GrowthType", "LINEAR"),- "GrowthFactor": v.get("GrowthFactor", 100.0),- "FinalBakeTimeInMinutes": v.get("FinalBakeTimeInMinutes", 0),- "State": v.get("State", "COMPLETE"),- "PercentageComplete": v.get("PercentageComplete", 100.0),- "StartedAt": v.get("StartedAt", ""),- "CompletedAt": v.get("CompletedAt", ""),- })+ for v in _refresh_environment(app_id, env_id):+ item = {+ "DeploymentNumber": v["DeploymentNumber"],+ "ConfigurationName": v.get("ConfigurationName", ""),+ "ConfigurationVersion": v.get("ConfigurationVersion", ""),+ "DeploymentDurationInMinutes": v.get("DeploymentDurationInMinutes", 0),+ "GrowthType": v.get("GrowthType", "LINEAR"),+ "GrowthFactor": v.get("GrowthFactor", 100.0),+ "FinalBakeTimeInMinutes": v.get("FinalBakeTimeInMinutes", 0),+ "State": v.get("State", "COMPLETE"),+ "PercentageComplete": v.get("PercentageComplete", 100.0),+ "StartedAt": v.get("StartedAt", ""),+ }+ for optional in ("CompletedAt", "VersionLabel"):+ if v.get(optional):+ item[optional] = v[optional]+ items.append(item)return _json(200, {"Items": items[:max_results]})-def _stop_deployment(app_id, env_id, deploy_num):+def _stop_deployment(app_id, env_id, deploy_num, allow_revert=False):+ _refresh_environment(app_id, env_id)record = _deployments.get(f"{app_id}/{env_id}/{deploy_num}")if not record:return _error(404, "ResourceNotFoundException", f"Deployment {deploy_num} not found")- record["State"] = "ROLLED_BACK"- return _json(202, record)+ now = time.time()+ state = record["State"]+ if state in _IN_PROGRESS_STATES:+ _roll_back(record, "USER", get_account_id(), now)+ elif state == "COMPLETE" and allow_revert:+ completed = record.get("_CompletedEpoch")+ if completed is not None and now - completed > _REVERT_WINDOW_SECONDS:+ return _error(400, "BadRequestException",+ f"Deployment {deploy_num} completed more than 72 hours ago and can no longer be reverted.")+ record["State"] = "REVERTED"+ _add_deployment_event(record, "REVERT_COMPLETED", "USER", f"Revert initiated by {get_account_id()}", now)+ else:+ return _error(400, "BadRequestException",+ f"Deployment {deploy_num} is in state {state} and cannot be stopped."+ + ("" if state != "COMPLETE" else " Pass AllowRevert to revert a completed deployment."))+ _refresh_environment(app_id, env_id)+ return _json(202, _deployment_view(record))# ---------------------------------------------------------------------------@@ -778,6 +971,11 @@ def _start_configuration_session(body):"ApplicationIdentifier, EnvironmentIdentifier, and ""ConfigurationProfileIdentifier are required")+ poll_interval = body.get("RequiredMinimumPollIntervalInSeconds")+ if poll_interval is not None and (not isinstance(poll_interval, int) or not 15 <= poll_interval <= 86400):+ return _error(400, "BadRequestException",+ "RequiredMinimumPollIntervalInSeconds must be between 15 and 86400")+app_id = _resolve_application_id(app_identifier)if not app_id:return _error(404, "ResourceNotFoundException", f"Application {app_identifier} not found")@@ -795,11 +993,36 @@ def _start_configuration_session(body):"ApplicationIdentifier": app_id,"EnvironmentIdentifier": env_id,"ConfigurationProfileIdentifier": profile_id,+ # Survives token rotation, so a client keeps its place in a gradual rollout.+ "SessionId": token,+ "PollIntervalInSeconds": poll_interval or _DEFAULT_POLL_INTERVAL_SECONDS,+ "LastServedVersion": None,}logger.info("StartConfigurationSession: app=%s env=%s profile=%s", app_id, env_id, profile_id)return _json(201, {"InitialConfigurationToken": token})+def _rollout_bucket(session_id):+ """A stable 0-99 slot for a session; it receives a DEPLOYING version once+ PercentageComplete passes its slot. AWS does not document how it picks+ targets, so this is MiniStack's choice."""+ return int(hashlib.sha256(session_id.encode("utf-8")).hexdigest(), 16) % 100+++def _served_deployment(app_id, env_id, profile_id, session_id):+ """The deployment whose configuration this session receives: the newest+ one that is COMPLETE or BAKING, or DEPLOYING far enough to reach the session."""+ deployments = [d for d in _refresh_environment(app_id, env_id)+ if d.get("ConfigurationProfileId") == profile_id]+ for deployment in reversed(deployments):+ state = deployment.get("State")+ if state in ("COMPLETE", "BAKING"):+ return deployment+ if state == "DEPLOYING" and _rollout_bucket(session_id) < deployment.get("PercentageComplete", 0.0):+ return deployment+ return None++def _retrieval_time_content(app_id, profile_id, content: bytes) -> bytes:"""Feature flags are served in retrieval-time format: the `values` maplifted to the top level. Anything else is served verbatim."""@@ -820,42 +1043,43 @@ def _get_latest_configuration(token):if not session:return _error(400, "BadRequestException", "Invalid or expired configuration token")- # Remove the used token+ # Each token is good for one call.del _sessions[token]app_id = session["ApplicationIdentifier"]env_id = session["EnvironmentIdentifier"]profile_id = session["ConfigurationProfileIdentifier"]-- # Find the latest completed deployment for this app/env- latest_deploy = None- for k, v in _deployments.items():- if (k.startswith(f"{app_id}/{env_id}/")- and v.get("State") == "COMPLETE"- and v.get("ConfigurationProfileId") == profile_id):- if latest_deploy is None or v["DeploymentNumber"] > latest_deploy["DeploymentNumber"]:- latest_deploy = v+ session_id = session.get("SessionId", token)+ session = {**session, "SessionId": session_id}content = b""content_type = "application/octet-stream"- if latest_deploy:- cfg_version = latest_deploy.get("ConfigurationVersion", "")- version_key = f"{app_id}/{profile_id}/{cfg_version}"- version_record = _hosted_versions.get(version_key)+ version_label = None+ deployment = _served_deployment(app_id, env_id, profile_id, session_id)+ if deployment:+ cfg_version = deployment.get("ConfigurationVersion", "")+ version_record = _hosted_versions.get(f"{app_id}/{profile_id}/{cfg_version}")if version_record:- raw = version_record["Content"]- content = raw if isinstance(raw, bytes) else raw.encode("utf-8")content_type = version_record.get("ContentType", "application/octet-stream")- content = _retrieval_time_content(app_id, profile_id, content)+ version_label = version_record.get("VersionLabel")+ # GetLatestConfiguration "may return empty configuration data if the+ # client already has the latest version".+ if session.get("LastServedVersion") != cfg_version:+ raw = version_record["Content"]+ content = raw if isinstance(raw, bytes) else raw.encode("utf-8")+ content = _retrieval_time_content(app_id, profile_id, content)+ session["LastServedVersion"] = cfg_versionnext_token = uuid.uuid4().hex- _sessions[next_token] = session.copy()+ _sessions[next_token] = sessionresp_headers = {"Content-Type": content_type,"Next-Poll-Configuration-Token": next_token,- "Next-Poll-Interval-In-Seconds": "30",+ "Next-Poll-Interval-In-Seconds": str(session.get("PollIntervalInSeconds", _DEFAULT_POLL_INTERVAL_SECONDS)),}+ if version_label:+ resp_headers["Version-Label"] = version_labelreturn 200, resp_headers, content@@ -909,7 +1133,8 @@ async def handle_request(method, path, headers, body_bytes, query_params):if m and method == "POST":app_id, profile_id = m.group(1), m.group(2)ct = content_type or "application/octet-stream"- return await _a(_create_hosted_configuration_version(app_id, profile_id, body_bytes, ct))+ return await _a(_create_hosted_configuration_version(app_id, profile_id, body_bytes, ct,+ headers.get("versionlabel")))m = re.fullmatch(r"/applications/([^/]+)/configurationprofiles/([^/]+)/hostedconfigurationversions/(\d+)",@@ -968,7 +1193,8 @@ async def handle_request(method, path, headers, body_bytes, query_params):if method == "GET":return await _a(_get_deployment(app_id, env_id, deploy_num))if method == "DELETE":- return await _a(_stop_deployment(app_id, env_id, deploy_num))+ allow_revert = str(headers.get("allow-revert", "")).lower() == "true"+ return await _a(_stop_deployment(app_id, env_id, deploy_num, allow_revert))# --- Environments ---m = re.fullmatch(r"/applications/([^/]+)/environments", path)diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.pyindex ef9ce977..8c817d51 100644--- a/ministack/services/cloudwatch.py+++ b/ministack/services/cloudwatch.py@@ -330,6 +330,44 @@ def _record_history(alarm_name, old_state, new_state, reason):)+def first_alarm_time(alarm_arn: str, start: float, end: float) -> float | None:+ """The earliest moment in ``[start, end]`` at which the alarm named by+ ``alarm_arn`` was in ``ALARM``, or None if it never was (or the ARN names no+ alarm of the current account and region).++ Internal entry point for AppConfig's environment monitors. The alarm's state+ over time is rebuilt from its StateUpdate history, so an alarm that fired+ and recovered inside the window still counts. History timestamps carry+ whole seconds.+ """+ name = _alarm_name_from_local_arn(alarm_arn)+ alarm = (_alarms.get(name) or _composite_alarms.get(name)) if name else None+ if not alarm:+ return None+ transitions = []+ for entry in _history_entries():+ if entry.get("AlarmName") != name or entry.get("HistoryItemType") != "StateUpdate":+ continue+ try:+ data = json.loads(entry["HistoryData"])+ at = datetime.strptime(entry["Timestamp"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp()+ transitions.append((at, data["oldState"]["stateValue"], data["newState"]["stateValue"]))+ except (KeyError, TypeError, ValueError):+ continue+ transitions.sort(key=lambda t: t[0])+ state_at_start = transitions[0][1] if transitions else alarm["StateValue"]+ for at, _old, new in transitions:+ if at > start:+ break+ state_at_start = new+ if state_at_start == "ALARM":+ return start+ for at, _old, new in transitions:+ if start < at <= end and new == "ALARM":+ return at+ return None++def record_metric(namespace: str, metric_name: str, value: float,unit: str = "None", dimensions: dict | None = None) -> None:"""Internal entry point for other services to publish CloudWatch metricsdiff --git a/tests/test_appconfig.py b/tests/test_appconfig.pyindex e71827aa..a75ec790 100644--- a/tests/test_appconfig.py+++ b/tests/test_appconfig.py@@ -596,12 +596,27 @@ def test_appconfig_stop_deployment(appconfig_client):ConfigurationProfileId=profile["Id"],ConfigurationVersion="1",)+ assert deploy["State"] == "COMPLETE"+ # StopDeployment "works only on deployments that have a status of+ # DEPLOYING, unless an AllowRevert parameter is supplied" (botocore docs).+ with pytest.raises(ClientError) as exc:+ appconfig_client.stop_deployment(+ ApplicationId=app["Id"],+ EnvironmentId=env["Id"],+ DeploymentNumber=deploy["DeploymentNumber"],+ )+ assert exc.value.response["Error"]["Code"] == "BadRequestException"+resp = appconfig_client.stop_deployment(ApplicationId=app["Id"],EnvironmentId=env["Id"],DeploymentNumber=deploy["DeploymentNumber"],+ AllowRevert=True,)- assert resp["State"] == "ROLLED_BACK"+ assert resp["State"] == "REVERTED"+ assert resp["EventLog"][0]["EventType"] == "REVERT_COMPLETED"+ environment = appconfig_client.get_environment(ApplicationId=app["Id"], EnvironmentId=env["Id"])+ assert environment["State"] == "REVERTED"def _deployment_target(appconfig_client, name):diff --git a/tests/test_appconfig_rollout.py b/tests/test_appconfig_rollout.pynew file mode 100644index 00000000..7c218589--- /dev/null+++ b/tests/test_appconfig_rollout.py@@ -0,0 +1,460 @@+"""+AppConfig gradual rollout: deployments walk DEPLOYING -> BAKING -> COMPLETE+over their strategy, environment monitors roll them back, and the data plane+serves each client the version the rollout has reached.++Most tests drive the handlers in-process against a fake clock with one+strategy minute lasting 60 real seconds (AWS's pace), so a 30-minute strategy+can be stepped through without sleeping. The boto3 tests at the end run+against the shared server at its default pace, where deployments finish as+they start.+"""++import asyncio+import json+import time++import pytest+from botocore.exceptions import ClientError++from ministack.core.responses import get_account_id+from ministack.services import appconfig as appconfig_service+from ministack.services import cloudwatch as cloudwatch_service++MINUTE = 60.0+START = 1_800_000_000.0+++def clock(monkeypatch):+ now = [START]+ monkeypatch.setattr(time, "time", lambda: now[0])+ monkeypatch.setattr(appconfig_service, "_DEPLOYMENT_MINUTE_SECONDS", MINUTE)+ appconfig_service.reset()+ cloudwatch_service.reset()+ yield now+ appconfig_service.reset()+ cloudwatch_service.reset()+++def _appconfig(method, path, body=None, headers=None, query=None):+ raw = json.dumps(body).encode() if isinstance(body, dict) else (body or b"")+ status, resp_headers, resp_body = asyncio.run(appconfig_service.handle_request(+ method, path, {k.lower(): v for k, v in (headers or {}).items()}, raw, query or {}))+ return status, resp_headers, resp_body+++def _appconfig_json(method, path, body=None, headers=None):+ status, _, resp_body = _appconfig(method, path, body, headers)+ return status, json.loads(resp_body) if resp_body else {}+++def _cloudwatch(action, body):+ headers = {"x-amz-target": f"GraniteServiceVersion20100801.{action}",+ "content-type": "application/x-amz-json-1.0"}+ status, _, _ = asyncio.run(cloudwatch_service.handle_request(+ "POST", "/", headers, json.dumps(body).encode(), {}))+ assert status == 200+++def _alarm(name):+ _cloudwatch("PutMetricAlarm", {+ "AlarmName": name, "Namespace": "Orders", "MetricName": "Errors",+ "Statistic": "Sum", "Period": 60, "EvaluationPeriods": 1,+ "Threshold": 1.0, "ComparisonOperator": "GreaterThanOrEqualToThreshold",+ })+ return f"arn:aws:cloudwatch:us-east-1:{get_account_id()}:alarm:{name}"+++def _set_alarm(name, state):+ _cloudwatch("SetAlarmState", {"AlarmName": name, "StateValue": state, "StateReason": "test"})+++class Target:+ """An application, environment and hosted profile holding versions 1 and 2."""++ def __init__(self, monitors=None):+ _, app = _appconfig_json("POST", "/applications", {"Name": "orders"})+ _, env = _appconfig_json("POST", f"/applications/{app['Id']}/environments",+ {"Name": "prod", "Monitors": monitors or []})+ _, profile = _appconfig_json("POST", f"/applications/{app['Id']}/configurationprofiles",+ {"Name": "settings", "LocationUri": "hosted"})+ self.app, self.env, self.profile = app["Id"], env["Id"], profile["Id"]+ for version in (1, 2):+ status, _, _ = _appconfig(+ "POST",+ f"/applications/{self.app}/configurationprofiles/{self.profile}/hostedconfigurationversions",+ json.dumps({"version": version}).encode(),+ {"Content-Type": "application/json", "VersionLabel": f"v{version}"},+ )+ assert status == 201++ @property+ def deployments_path(self):+ return f"/applications/{self.app}/environments/{self.env}/deployments"++ def deploy(self, version, strategy="AppConfig.Linear20PercentEvery6Minutes", **extra):+ return _appconfig_json("POST", self.deployments_path, {+ "DeploymentStrategyId": strategy, "ConfigurationProfileId": self.profile,+ "ConfigurationVersion": str(version), **extra,+ })++ def deployment(self, number):+ status, body = _appconfig_json("GET", f"{self.deployments_path}/{number}")+ assert status == 200+ return body++ def stop(self, number, allow_revert=False):+ headers = {"Allow-Revert": "true"} if allow_revert else {}+ return _appconfig_json("DELETE", f"{self.deployments_path}/{number}", headers=headers)++ def environment_state(self):+ return _appconfig_json("GET", f"/applications/{self.app}/environments/{self.env}")[1]["State"]++ def session(self, **extra):+ status, body = _appconfig_json("POST", "/configurationsessions", {+ "ApplicationIdentifier": self.app, "EnvironmentIdentifier": self.env,+ "ConfigurationProfileIdentifier": self.profile, **extra,+ })+ assert status == 201+ return Client(body["InitialConfigurationToken"])+++class Client:+ """One configuration session, polling with the token it was last handed."""++ def __init__(self, token):+ self.session_id = token+ self.token = token++ def poll(self):+ status, headers, body = _appconfig("GET", "/configuration", query={"configuration_token": self.token})+ assert status == 200+ self.token = headers["Next-Poll-Configuration-Token"]+ return headers, json.loads(body) if body else None+++def _event_types(deployment):+ return [event["EventType"] for event in deployment["EventLog"]]+++def test_rollout_steps_follow_the_growth_type():+ assert appconfig_service._rollout_steps("LINEAR", 20.0) == [20.0, 40.0, 60.0, 80.0, 100.0]+ assert appconfig_service._rollout_steps("LINEAR", 100.0) == [100.0]+ # G*(2^N) from the CreateDeploymentStrategy docs.+ assert appconfig_service._rollout_steps("EXPONENTIAL", 10.0) == [10.0, 20.0, 40.0, 80.0, 100.0]+ assert appconfig_service._rollout_steps("EXPONENTIAL", 2.0) == [2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 100.0]+ # Below the model's 1.0 minimum (stored unvalidated) still terminates.+ assert appconfig_service._rollout_steps("LINEAR", -5.0)[-1] == 100.0+++def test_linear_deployment_steps_bakes_and_completes(clock):+ target = Target()+ status, deployment = target.deploy(1)+ assert status == 201+ assert deployment["State"] == "DEPLOYING"+ assert deployment["PercentageComplete"] == 0.0+ assert _event_types(deployment) == ["DEPLOYMENT_STARTED"]+ assert target.environment_state() == "DEPLOYING"++ # Linear20PercentEvery6Minutes: five 20% steps over 30 minutes, then a 30-minute bake.+ clock[0] = START + 6 * MINUTE+ assert target.deployment(1)["PercentageComplete"] == 20.0+ clock[0] = START + 12 * MINUTE - 1+ assert target.deployment(1)["PercentageComplete"] == 20.0+ clock[0] = START + 12 * MINUTE+ assert target.deployment(1)["PercentageComplete"] == 40.0++ clock[0] = START + 30 * MINUTE+ deployment = target.deployment(1)+ assert (deployment["State"], deployment["PercentageComplete"]) == ("BAKING", 100.0)+ assert target.environment_state() == "DEPLOYING"++ clock[0] = START + 60 * MINUTE+ deployment = target.deployment(1)+ assert deployment["State"] == "COMPLETE"+ assert deployment["CompletedAt"] == appconfig_service._iso(START + 60 * MINUTE)+ assert target.environment_state() == "READY_FOR_DEPLOYMENT"+ # Most recent first.+ assert _event_types(deployment) == [+ "DEPLOYMENT_COMPLETED", "BAKE_TIME_STARTED",+ *["PERCENTAGE_UPDATED"] * 5,+ "DEPLOYMENT_STARTED",+ ]+ first_step = deployment["EventLog"][-2]+ assert first_step["OccurredAt"] == appconfig_service._iso(START + 6 * MINUTE)+ assert first_step["TriggeredBy"] == "APPCONFIG"+++def test_list_deployments_reports_rollout_progress(clock):+ target = Target()+ target.deploy(1, strategy="AppConfig.Canary10Percent20Minutes")+ clock[0] = START + 4 * MINUTE+ status, body = _appconfig_json("GET", target.deployments_path)+ assert status == 200+ [summary] = body["Items"]+ assert (summary["State"], summary["PercentageComplete"]) == ("DEPLOYING", 10.0)+ assert summary["VersionLabel"] == "v1"+ assert "CompletedAt" not in summary+++def test_start_deployment_conflicts_with_one_in_progress(clock):+ target = Target()+ target.deploy(1)+ status, body = target.deploy(2)+ assert status == 409+ assert body["__type"] == "ConflictException"++ # Still in progress while baking.+ clock[0] = START + 30 * MINUTE+ assert target.deploy(2)[0] == 409++ clock[0] = START + 60 * MINUTE+ status, body = target.deploy(2)+ assert status == 201+ assert body["DeploymentNumber"] == 2+++def test_start_deployment_checks_latest_deployment_number(clock):+ target = Target()+ assert target.deploy(1, strategy="AppConfig.AllAtOnce", LatestDeploymentNumber=0)[0] == 201+ clock[0] = START + 10 * MINUTE+ status, body = target.deploy(2, strategy="AppConfig.AllAtOnce", LatestDeploymentNumber=0)+ assert status == 409+ assert body["__type"] == "ConflictException"+ assert target.deploy(2, strategy="AppConfig.AllAtOnce", LatestDeploymentNumber=1)[0] == 201+++def test_stop_rolls_back_an_in_progress_deployment(clock):+ target = Target()+ target.deploy(1, strategy="AppConfig.AllAtOnce")+ clock[0] = START + 10 * MINUTE+ client = target.session()+ assert client.poll()[1] == {"version": 1}++ target.deploy(2)+ clock[0] = START + 40 * MINUTE # 100%, baking+ assert client.poll()[1] == {"version": 2}++ status, deployment = target.stop(2)+ assert status == 202+ assert deployment["State"] == "ROLLED_BACK"+ assert _event_types(deployment)[:2] == ["ROLLBACK_COMPLETED", "ROLLBACK_STARTED"]+ assert deployment["EventLog"][0]["TriggeredBy"] == "USER"+ assert target.environment_state() == "ROLLED_BACK"+ assert client.poll()[1] == {"version": 1}++ # A stopped deployment cannot be stopped again, and the environment takes a new one.+ assert target.stop(2)[0] == 400+ assert target.deploy(2)[0] == 201+++def test_revert_requires_allow_revert_and_the_72_hour_window(clock):+ target = Target()+ target.deploy(1, strategy="AppConfig.AllAtOnce")+ clock[0] = START + 10 * MINUTE+ target.deploy(2, strategy="AppConfig.AllAtOnce")+ clock[0] = START + 20 * MINUTE+ assert target.deployment(2)["State"] == "COMPLETE"++ status, body = target.stop(2)+ assert status == 400+ assert body["__type"] == "BadRequestException"++ clock[0] = START + 20 * MINUTE + 72 * 3600 + 1+ assert target.stop(2, allow_revert=True)[0] == 400++ clock[0] = START + 20 * MINUTE + 72 * 3600+ status, deployment = target.stop(2, allow_revert=True)+ assert status == 202+ assert deployment["State"] == "REVERTED"+ assert target.environment_state() == "REVERTED"+ assert target.session().poll()[1] == {"version": 1}+++def test_monitor_alarm_rolls_back_at_the_moment_it_fires(clock):+ alarm_arn = _alarm("orders-errors")+ target = Target(monitors=[{"AlarmArn": alarm_arn}])+ target.deploy(1, strategy="AppConfig.AllAtOnce")+ clock[0] = START + 10 * MINUTE+ target.deploy(2)+ deploy_start = clock[0]++ clock[0] = deploy_start + 7 * MINUTE+ _cloudwatch("PutMetricData", {"Namespace": "Orders", "MetricData": [{"MetricName": "Errors", "Value": 5}]})+ clock[0] = deploy_start + 20 * MINUTE++ deployment = target.deployment(2)+ assert deployment["State"] == "ROLLED_BACK"+ assert deployment["PercentageComplete"] == 20.0 # the 12-minute step never came+ rollback_started = deployment["EventLog"][1]+ assert rollback_started["EventType"] == "ROLLBACK_STARTED"+ assert rollback_started["TriggeredBy"] == "CLOUDWATCH_ALARM"+ assert alarm_arn in rollback_started["Description"]+ assert rollback_started["OccurredAt"] == appconfig_service._iso(deploy_start + 7 * MINUTE)+ assert target.environment_state() == "ROLLED_BACK"+ assert target.session().poll()[1] == {"version": 1}+++def test_alarm_that_recovers_during_the_bake_still_rolls_back(clock):+ target = Target(monitors=[{"AlarmArn": _alarm("orders-errors")}])+ target.deploy(1)+ clock[0] = START + 35 * MINUTE+ _set_alarm("orders-errors", "ALARM")+ clock[0] = START + 36 * MINUTE+ _set_alarm("orders-errors", "OK")++ clock[0] = START + 90 * MINUTE+ deployment = target.deployment(1)+ assert deployment["State"] == "ROLLED_BACK"+ assert deployment["PercentageComplete"] == 100.0+ assert "BAKE_TIME_STARTED" in _event_types(deployment)+++def test_alarm_after_completion_does_not_roll_back(clock):+ target = Target(monitors=[{"AlarmArn": _alarm("orders-errors")}])+ target.deploy(1)+ clock[0] = START + 61 * MINUTE+ _set_alarm("orders-errors", "ALARM")+ clock[0] = START + 62 * MINUTE+ assert target.deployment(1)["State"] == "COMPLETE"+++def test_alarm_already_firing_rolls_back_before_any_step(clock, monkeypatch):+ monkeypatch.setattr(appconfig_service, "_DEPLOYMENT_MINUTE_SECONDS", 0.0)+ target = Target(monitors=[{"AlarmArn": _alarm("orders-errors")}])+ _set_alarm("orders-errors", "ALARM")+ status, deployment = target.deploy(1, strategy="AppConfig.AllAtOnce")+ assert status == 201+ assert deployment["State"] == "ROLLED_BACK"+ assert deployment["PercentageComplete"] == 0.0+++def test_monitor_on_an_unknown_alarm_is_ignored(clock):+ target = Target(monitors=[{"AlarmArn": "arn:aws:cloudwatch:us-east-1:000000000000:alarm:missing"}])+ target.deploy(1, strategy="AppConfig.AllAtOnce")+ clock[0] = START + 10 * MINUTE+ assert target.deployment(1)["State"] == "COMPLETE"+++def test_gradual_rollout_reaches_each_client_once_its_slot_is_covered(clock):+ target = Target()+ target.deploy(1, strategy="AppConfig.AllAtOnce")+ clock[0] = START + 10 * MINUTE+ clients = [target.session() for _ in range(60)]+ for client in clients:+ assert client.poll()[1] == {"version": 1}++ target.deploy(2)+ deploy_start = clock[0]+ clock[0] = deploy_start + 12 * MINUTE # 40%+ reached = set()+ for client in clients:+ served = client.poll()[1]+ if appconfig_service._rollout_bucket(client.session_id) < 40:+ assert served == {"version": 2}+ reached.add(client.session_id)+ else:+ assert served is None # still on version 1, which it already has+ assert 0 < len(reached) < len(clients)++ clock[0] = deploy_start + 30 * MINUTE # 100%+ for client in clients:+ served = client.poll()[1]+ assert served == (None if client.session_id in reached else {"version": 2})+++def test_poll_returns_empty_configuration_until_it_changes(clock):+ target = Target()+ client = target.session()+ headers, served = client.poll()+ assert served is None # nothing deployed yet++ target.deploy(1, strategy="AppConfig.AllAtOnce")+ headers, served = client.poll()+ assert served == {"version": 1}+ assert headers["Version-Label"] == "v1"+ headers, served = client.poll()+ assert served is None+ assert headers["Version-Label"] == "v1"+++def test_session_poll_interval(clock):+ target = Target()+ assert target.session().poll()[0]["Next-Poll-Interval-In-Seconds"] == "30"+ assert target.session(RequiredMinimumPollIntervalInSeconds=90).poll()[0]["Next-Poll-Interval-In-Seconds"] == "90"+ status, body = _appconfig_json("POST", "/configurationsessions", {+ "ApplicationIdentifier": target.app, "EnvironmentIdentifier": target.env,+ "ConfigurationProfileIdentifier": target.profile, "RequiredMinimumPollIntervalInSeconds": 5,+ })+ assert status == 400+ assert body["__type"] == "BadRequestException"+++# ---------------------------------------------------------------------------+# boto3 against the shared server (deployments finish as they start)+# ---------------------------------------------------------------------------+++def _live_target(appconfig_client, name, monitors=None):+ app = appconfig_client.create_application(Name=name)+ env = appconfig_client.create_environment(ApplicationId=app["Id"], Name="prod", Monitors=monitors or [])+ profile = appconfig_client.create_configuration_profile(+ ApplicationId=app["Id"], Name="settings", LocationUri="hosted")+ appconfig_client.create_hosted_configuration_version(+ ApplicationId=app["Id"], ConfigurationProfileId=profile["Id"],+ Content=b'{"version": 1}', ContentType="application/json", VersionLabel="v1")+ return app["Id"], env["Id"], profile["Id"]+++def test_live_alarm_in_alarm_rolls_back_deployment(appconfig_client, cw):+ alarm_name = "appconfig-rollout-live-errors"+ cw.put_metric_alarm(+ AlarmName=alarm_name, Namespace="Orders", MetricName="Errors", Statistic="Sum",+ Period=60, EvaluationPeriods=1, Threshold=1.0, ComparisonOperator="GreaterThanOrEqualToThreshold")+ alarm_arn = cw.describe_alarms(AlarmNames=[alarm_name])["MetricAlarms"][0]["AlarmArn"]+ cw.set_alarm_state(AlarmName=alarm_name, StateValue="ALARM", StateReason="test")+ try:+ app_id, env_id, profile_id = _live_target(+ appconfig_client, "rollout-live-alarm", monitors=[{"AlarmArn": alarm_arn}])+ deployment = appconfig_client.start_deployment(+ ApplicationId=app_id, EnvironmentId=env_id, DeploymentStrategyId="AppConfig.AllAtOnce",+ ConfigurationProfileId=profile_id, ConfigurationVersion="1")+ assert deployment["State"] == "ROLLED_BACK"+ assert deployment["EventLog"][0]["TriggeredBy"] == "CLOUDWATCH_ALARM"+ environment = appconfig_client.get_environment(ApplicationId=app_id, EnvironmentId=env_id)+ assert environment["State"] == "ROLLED_BACK"+ finally:+ cw.delete_alarms(AlarmNames=[alarm_name])+++def test_live_data_plane_version_label_and_unchanged_poll(appconfig_client, appconfigdata_client):+ app_id, env_id, profile_id = _live_target(appconfig_client, "rollout-live-poll")+ appconfig_client.start_deployment(+ ApplicationId=app_id, EnvironmentId=env_id, DeploymentStrategyId="AppConfig.AllAtOnce",+ ConfigurationProfileId=profile_id, ConfigurationVersion="1")+ token = appconfigdata_client.start_configuration_session(+ ApplicationIdentifier=app_id, EnvironmentIdentifier=env_id,+ ConfigurationProfileIdentifier=profile_id, RequiredMinimumPollIntervalInSeconds=45,+ )["InitialConfigurationToken"]++ first = appconfigdata_client.get_latest_configuration(ConfigurationToken=token)+ assert json.loads(first["Configuration"].read()) == {"version": 1}+ assert first["VersionLabel"] == "v1"+ assert first["NextPollIntervalInSeconds"] == 45++ second = appconfigdata_client.get_latest_configuration(+ ConfigurationToken=first["NextPollConfigurationToken"])+ assert second["Configuration"].read() == b""+++def test_live_concurrent_deployment_conflicts(appconfig_client):+ app_id, env_id, profile_id = _live_target(appconfig_client, "rollout-live-conflict")+ appconfig_client.start_deployment(+ ApplicationId=app_id, EnvironmentId=env_id, DeploymentStrategyId="AppConfig.AllAtOnce",+ ConfigurationProfileId=profile_id, ConfigurationVersion="1")+ with pytest.raises(ClientError) as exc:+ appconfig_client.start_deployment(+ ApplicationId=app_id, EnvironmentId=env_id, DeploymentStrategyId="AppConfig.AllAtOnce",+ ConfigurationProfileId=profile_id, ConfigurationVersion="1", LatestDeploymentNumber=0)+ assert exc.value.response["Error"]["Code"] == "ConflictException"