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(cloudformation): WaitCondition waits for its signals, SignalResource (#1656)
iot-rockete114a053f631
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6d6b51af..60c0b533 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **S3 — the Multi-Region Access Point alias starts with a letter and follows the documented pattern** — the alias was the first 13 hex characters of a uuid, so it could come out as digits only (`1240729989764.mrap`), which is not what S3 mints (`mfzwi23gnjvgw.mrap`) and made `test_cfn_s3_multi_region_access_point` fail whenever no letter was drawn (`str.islower()` is False without a cased character). The alias now follows the documented pattern `^[a-z][a-z0-9]*[.]mrap$`: a letter, then twelve lowercase letters or digits; the test checks that pattern. Contributed by @iot-rocket.### Added- **CloudFormation — `ListImports`, `UpdateTerminationProtection`, `SetStackPolicy`, `GetStackPolicy`, `CancelUpdateStack` and `ContinueUpdateRollback`** — the first four were routed to the service and answered `InvalidAction`, the last two did not exist, so a stack in `UPDATE_ROLLBACK_FAILED` had no way out short of a reset. `ListImports` names the stacks importing an export (a `ValidationError` when none does); termination protection is set on create or later and makes `DeleteStack` refuse with the stack unchanged (`DescribeStacks` reports `EnableTerminationProtection`); a stack policy is stored and returned (it is not enforced); `CancelUpdateStack` stops an `UPDATE_IN_PROGRESS` update before its next resource and rolls it back ("User Initiated"); `ContinueUpdateRollback` retries the deletes that failed the rollback, skips the `ResourcesToSkip` (their status becomes `UPDATE_COMPLETE`, the resource stays) and lands the stack in `UPDATE_ROLLBACK_COMPLETE`. Contributed by @iot-rocket.+- **CloudFormation — a `WaitCondition` waits for its signals** — `AWS::CloudFormation::WaitCondition` completed at once and `AWS::CloudFormation::WaitConditionHandle` answered a URL nothing served, so a stack never waited for the configuration step it was written to wait for. The handle's `Ref` (and physical id) is now a URL the emulator serves (`PUT` the AWS signal JSON, `Status`, `UniqueId`, `Data`, `Reason`, to it with an empty `Content-Type`; `Id` is its token); the wait condition stays `CREATE_IN_PROGRESS` until `Count` SUCCESS signals with distinct `UniqueId`s arrived (a repeated id is a retransmission and is ignored), a FAILURE signal or the `Timeout` fails it and rolls the stack back, every signal is published to the stack events, and `Fn::GetAtt Wait.Data` is the `{UniqueId: Data}` map. A wait condition with a `CreationPolicy` (`ResourceSignal` with `Count` and an ISO 8601 `Timeout`, default `PT5M`) needs no handle and is signalled through `SignalResource`. Without a `CreationPolicy` a missing `Timeout`, a `Timeout` outside 1..43200 seconds, a `Count` below 1 or a handle of another stack fail the resource. A nested stack now deploys on a worker thread, so a wait condition or custom resource inside it no longer blocks the server. The custom-resource `ResponseURL` honours `EDGE_PORT` like the rest of the emulator. Contributed by @iot-rocket.+- **CloudFormation — `SignalResource`** — the action did not exist (`InvalidAction`). It now delivers a `SUCCESS` or `FAILURE` signal with a `UniqueId` to the wait condition that is waiting under the given logical id, addressed by stack name or id; a missing field, a stack that is not in progress, a resource that is not waiting, a `Status` outside the enum or a `UniqueId` longer than 64 characters are a `ValidationError`. Contributed by @iot-rocket.- **CloudFormation — the `Tags` property of a queue, topic, table, function, log group and stream reaches the service** — `AWS::SQS::Queue`, `AWS::SNS::Topic`, `AWS::DynamoDB::Table`, `AWS::Lambda::Function`, `AWS::Logs::LogGroup` and `AWS::Kinesis::Stream` stored their tags nowhere, so the service's own list-tags call answered an empty set for a tagged resource. The tags now land where `ListQueueTags`, `ListTagsForResource`, `ListTagsOfResource`, `ListTags`, `ListTagsLogGroup` and `ListTagsForStream` read them; a template change is reconciled on update (dropped keys removed, the rest set) and tags added through the service API stay. Contributed by @iot-rocket.- **CloudFormation — stack-level tags propagate to the resources** — the `Tags` of `CreateStack` and `UpdateStack` were stored on the stack record and went nowhere, and no resource carried the `aws:cloudformation:stack-name`, `aws:cloudformation:stack-id` and `aws:cloudformation:logical-id` tags a real deploy adds. For the 44 types whose provisioner stores a tag property (list-shaped `Tags`, the map-shaped `Tags` of SSM and API Gateway v2, `UserPoolTags`, `IdentityPoolTags`, `BackupVaultTags`, `BackupPlanTags`), the stack tags and the three `aws:cloudformation:` tags are merged into that property before the resource is created or updated; a key the template sets wins. A stack-tag change on `UpdateStack` reaches the resources whose type has an update handler (the 20 types without one keep their tags and are not re-created), a nested stack passes the tags on, an empty `Tags` on `UpdateStack` or a change set removes the stack's tags (as the API documents for an empty value), more than 50 tags or an `aws:` prefixed key are refused before a stack exists, and the stack record keeps the template's own properties, so change sets and the no-change check still compare templates. Contributed by @iot-rocket.- **CloudFormation — the list and describe actions page their results** — `DescribeStacks`, `ListStacks`, `DescribeStackEvents`, `ListStackResources`, `ListExports`, `ListImports` and `ListChangeSets` answered the whole store in one response and ignored `NextToken`, so a paginator drained nothing and a caller that pages (`ListExports` pages at 100 values on AWS, the others at 1 MB) never saw a second page. They now return 100 items per page with a `NextToken` for the rest; a token the service did not hand out is a `ValidationError`. `DescribeStackEvents` also orders events of one millisecond newest first, so the pages are strictly reverse-chronological. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex 92ebf949..b5484780 100644--- a/README.md+++ b/README.md@@ -556,8 +556,8 @@ subnet = ec2.create_subnet(| `AWS::AutoScaling::ScheduledAction` | Action ARN | Arn, ScheduledActionName || `AWS::Scheduler::Schedule` | Schedule name | Arn || `AWS::Scheduler::ScheduleGroup` | Group name | Arn |-| `AWS::CloudFormation::WaitCondition` | Condition ID | — |-| `AWS::CloudFormation::WaitConditionHandle` | Handle URL | — |+| `AWS::CloudFormation::WaitCondition` | Condition ID | Data, Id |+| `AWS::CloudFormation::WaitConditionHandle` | Signal URL | Id || `AWS::CloudFormation::Stack` (nested) | Child stack ARN | `Outputs.<Name>` — each child stack Output |Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if rollback is enabled), so templates with unsupported types won't silently succeed.diff --git a/ministack/app.py b/ministack/app.pyindex c7636b99..3f850a79 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1279,6 +1279,27 @@ async def _handle_post_body_shortcuts(logging.getLogger("cloudformation").warning("CFN ResponseURL PUT for unknown token %r — ignoring", token)return 200, {}, b""+ # CloudFormation WaitConditionHandle signal URL (the presigned S3 URL on AWS)+ from ministack.services.cloudformation import wait_conditions as _cfn_wc++ if method == "PUT" and path.startswith(_cfn_wc.SIGNAL_PATH):+ token = path[len(_cfn_wc.SIGNAL_PATH) :]+ if not _cfn_wc.has_handle(token):+ logging.getLogger("cloudformation").warning("CFN wait condition signal for unknown token %r", token)+ return 404, {"Content-Type": "application/json"}, b'{"message": "unknown wait condition handle"}'+ if headers.get("content-type"):+ # The user guide, "To send a signal", step 3: the request method must+ # be PUT and the Content-Type header must be an empty string or omitted.+ return 403, {"Content-Type": "application/json"}, json.dumps(+ {"message": "the Content-Type header must be an empty string or omitted"}+ ).encode()+ try:+ payload = json.loads(body) if body else {}+ _cfn_wc.deliver_signal(token, payload)+ except (json.JSONDecodeError, ValueError) as exc:+ return 400, {"Content-Type": "application/json"}, json.dumps({"message": str(exc)}).encode()+ return 200, {}, b""+response = await _handle_cognito_body_request(method, path, headers, body, query_params)if response is not None:# See _handle_pre_body_request: browser-based OIDC clients need CORS.diff --git a/ministack/core/router.py b/ministack/core/router.pyindex 34fd508d..e51a8c09 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -1057,6 +1057,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"UpdateTerminationProtection": "cloudformation","SetStackPolicy": "cloudformation","GetStackPolicy": "cloudformation",+ "SignalResource": "cloudformation",# EBS Snapshots# Note: CreateSnapshot, DeleteSnapshot, DescribeSnapshots are intentionally# omitted here because they conflict with ElastiCache actions of the samediff --git a/ministack/services/cloudformation/__init__.py b/ministack/services/cloudformation/__init__.pyindex a1accfe4..0996d522 100644--- a/ministack/services/cloudformation/__init__.py+++ b/ministack/services/cloudformation/__init__.py@@ -72,6 +72,8 @@ def reset():_change_sets.clear()from ministack.services.cloudformation import custom_resource as _cr_cr.reset()+ from ministack.services.cloudformation import wait_conditions as _wc+ _wc.reset()# Stores that need to survive a PERSIST_STATE=1 stop/restore cycle. The actualdiff --git a/ministack/services/cloudformation/custom_resource.py b/ministack/services/cloudformation/custom_resource.pyindex 60fa2141..d27ef6bb 100644--- a/ministack/services/cloudformation/custom_resource.py+++ b/ministack/services/cloudformation/custom_resource.py@@ -10,7 +10,8 @@ import threadinglogger = logging.getLogger("cloudformation")_HOST = os.environ.get("MINISTACK_HOST", "localhost")-_PORT = os.environ.get("GATEWAY_PORT", "4566")+# The gateway port as the app resolves it: GATEWAY_PORT > EDGE_PORT > 4566.+_PORT = os.environ.get("GATEWAY_PORT") or os.environ.get("EDGE_PORT") or "4566"_lock = threading.Lock()# token → {"event": threading.Event, "result": dict | None}diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.pyindex 78d82d58..0564ec6d 100644--- a/ministack/services/cloudformation/handlers.py+++ b/ministack/services/cloudformation/handlers.py@@ -9,6 +9,7 @@ import jsonimport loggingfrom ministack.core.responses import get_account_id, get_region, new_uuid, now_iso+from ministack.services.cloudformation import wait_conditions as _wcfrom .changesets import (_create_change_set,@@ -1093,6 +1094,41 @@ def _continue_update_rollback(params):"<ContinueUpdateRollbackResult></ContinueUpdateRollbackResult>")+# --- SignalResource ---++def _signal_resource(params):+ """Deliver a SUCCESS or FAILURE signal to the wait condition of a stack+ that is waiting under the logical id, from anywhere other than the+ handle URL (the only way in for a wait condition with a CreationPolicy)."""+ stack_name = _p(params, "StackName")+ logical_id = _p(params, "LogicalResourceId")+ unique_id = _p(params, "UniqueId")+ status = _p(params, "Status")+ for name, value in (("StackName", stack_name), ("LogicalResourceId", logical_id),+ ("UniqueId", unique_id), ("Status", status)):+ if not value:+ return _error("ValidationError", f"{name} is required")+ if status not in ("SUCCESS", "FAILURE"):+ return _error("ValidationError",+ f"1 validation error detected: Value '{status}' at 'status' failed to satisfy "+ "constraint: Member must satisfy enum value set: [FAILURE, SUCCESS]")+ if len(unique_id) > 64:+ return _error("ValidationError",+ f"1 validation error detected: Value '{unique_id}' at 'uniqueId' failed to "+ "satisfy constraint: Member must have length less than or equal to 64")+ stack = _resolve_stack(stack_name)+ if not stack or stack.get("StackStatus") == "DELETE_COMPLETE":+ return _error("ValidationError", f"Stack [{stack_name}] does not exist")+ stack_name = stack.get("StackName", stack_name)+ if stack.get("StackStatus") not in ("CREATE_IN_PROGRESS", "UPDATE_IN_PROGRESS"):+ return _error("ValidationError",+ f"Stack [{stack_name}] is in {stack.get('StackStatus')} state and cannot be signaled")+ if not _wc.signal_resource(stack["StackId"], logical_id, unique_id, status):+ return _error("ValidationError",+ f"Resource [{logical_id}] in stack [{stack_name}] is not waiting for signals")+ return _xml(200, "SignalResourceResponse", "")++# ===========================================================================# Action Handler Registry# ===========================================================================@@ -1122,4 +1158,5 @@ _ACTION_HANDLERS = {"GetStackPolicy": _get_stack_policy,"CancelUpdateStack": _cancel_update_stack,"ContinueUpdateRollback": _continue_update_rollback,+ "SignalResource": _signal_resource,}diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 571bcd91..65638d92 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -2962,19 +2962,86 @@ def _lambda_version_delete(physical_id, props):func["versions"].pop(version, None)-# --- CloudFormation WaitCondition / WaitConditionHandle (no-ops) ---+# --- CloudFormation WaitCondition / WaitConditionHandle ---++def _cfn_wait_condition_definition(stack_name: str, logical_id: str) -> dict:+ """The resource definition as the running operation sees it: the stack+ record's ``_template_body`` is the template being deployed (create,+ update and change-set execution set it before the run starts)."""+ from ministack.services.cloudformation import _stacks+ from ministack.services.cloudformation.engine import _parse_template+ stack = _stacks.get(stack_name) or {}+ template = None+ body = stack.get("_template_body")+ if body:+ try:+ template = _parse_template(body)+ except Exception:+ template = None+ if not isinstance(template, dict):+ template = stack.get("_template") or {}+ res_def = (template.get("Resources") or {}).get(logical_id) or {}+ return res_def if isinstance(res_def, dict) else {}+def _cfn_wait_condition_create(logical_id, props, stack_name):- """WaitCondition — no-op, return immediately (no real signalling in local emulation)."""+ """WaitCondition: block the stack until ``Count`` SUCCESS signals arrived,+ a FAILURE signal arrived, or the timeout passed. With a ``CreationPolicy``+ the signals come through SignalResource only; otherwise through the+ handle's URL (and SignalResource). Runs on a worker thread (see+ ``_is_custom_resource`` in stacks.py)."""+ from ministack.services.cloudformation import wait_conditions as _wc+ stack_id = _cr_stack_id(stack_name)+ res_def = _cfn_wait_condition_definition(stack_name, logical_id)+ if "CreationPolicy" in res_def:+ creation_policy = res_def.get("CreationPolicy")+ if not isinstance(creation_policy, dict):+ raise ValueError(f"WaitCondition {logical_id!r}: CreationPolicy must be an object")+ signal = creation_policy.get("ResourceSignal")+ if signal is None:+ signal = {}+ if not isinstance(signal, dict):+ raise ValueError(f"WaitCondition {logical_id!r}: CreationPolicy ResourceSignal must be an object")+ count = _wc.validate_count(signal.get("Count"), logical_id)+ timeout_s = _wc.validate_resource_signal_timeout(signal.get("Timeout"), logical_id)+ token = _wc.register_slot(stack_id)+ else:+ token = _wc.token_from_url(props.get("Handle"))+ if token is None or _wc.handle_owner(token) != stack_id:+ raise ValueError(+ f"WaitCondition {logical_id!r}: Handle must be the Ref of an "+ "AWS::CloudFormation::WaitConditionHandle of this stack"+ )+ if props.get("Timeout") in (None, ""):+ raise ValueError(f"WaitCondition {logical_id!r}: Timeout is required")+ count = _wc.validate_count(props.get("Count"), logical_id)+ timeout_s = _wc.validate_timeout_seconds(props.get("Timeout"), logical_id)+ data = _wc.wait_for(token, stack_id, stack_name, logical_id,+ "AWS::CloudFormation::WaitCondition", count, timeout_s)pid = f"{stack_name}-{logical_id}-{new_uuid()[:8]}"- return pid, {"Data": "{}"}+ attrs = {"Data": json.dumps(data), "Id": pid}+ _wc.remember_result(pid, attrs)+ return pid, attrs+++def _cfn_wait_condition_update(physical_id, old_props, new_props, stack_name):+ """Updates are not supported on AWS; the resource keeps its id and data."""+ from ministack.services.cloudformation import wait_conditions as _wc+ return physical_id, _wc.recall_result(physical_id) or {"Data": "{}", "Id": physical_id}def _cfn_wait_condition_handle_create(logical_id, props, stack_name):- """WaitConditionHandle — no-op, return a presigned-style URL."""- pid = f"{stack_name}-{logical_id}-{new_uuid()[:8]}"- url = f"https://cloudformation-waitcondition-{get_region()}.s3.amazonaws.com/{pid}"- return pid, {"Ref": url}+ """WaitConditionHandle: the physical id (and ``Ref``) is the URL a signal+ is PUT to, served under ``/_ministack/cfn-signal/``; ``Id`` is its token."""+ from ministack.services.cloudformation import wait_conditions as _wc+ url, token = _wc.register_handle(_cr_stack_id(stack_name))+ return url, {"Ref": url, "Id": token}+++def _cfn_wait_condition_handle_delete(physical_id, props):+ """Forget the handle: a later PUT to its URL is a 404."""+ from ministack.services.cloudformation import wait_conditions as _wc+ _wc.discard_handle(physical_id)def _cfn_noop_delete(physical_id, props):@@ -8579,8 +8646,8 @@ _RESOURCE_HANDLERS = {"delete_with_logical_id": True,},"AWS::Lambda::Version": {"create": _lambda_version_create, "delete": _lambda_version_delete},- "AWS::CloudFormation::WaitCondition": {"create": _cfn_wait_condition_create, "delete": _cfn_noop_delete},- "AWS::CloudFormation::WaitConditionHandle": {"create": _cfn_wait_condition_handle_create, "delete": _cfn_noop_delete},+ "AWS::CloudFormation::WaitCondition": {"create": _cfn_wait_condition_create, "update": _cfn_wait_condition_update, "delete": _cfn_noop_delete},+ "AWS::CloudFormation::WaitConditionHandle": {"create": _cfn_wait_condition_handle_create, "delete": _cfn_wait_condition_handle_delete},"AWS::CloudFormation::Stack": {"create": _cfn_nested_stack_create,"update": _cfn_nested_stack_update,diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.pyindex 2c692608..ecd33d0b 100644--- a/ministack/services/cloudformation/stacks.py+++ b/ministack/services/cloudformation/stacks.py@@ -62,7 +62,14 @@ def _create_stack_task_in_region(coro, stack: dict | None, stack_id: str | Nonedef _is_custom_resource(resource_type: str) -> bool:- return resource_type.startswith("Custom::") or resource_type == "AWS::CloudFormation::CustomResource"+ """The types whose provisioning blocks on a callback into this server, so+ they run on a worker thread: custom resources wait for the ResponseURL+ PUT, a WaitCondition for the signals on its handle, and a nested stack+ deploys inline and may contain either."""+ return (resource_type.startswith("Custom::")+ or resource_type in ("AWS::CloudFormation::CustomResource",+ "AWS::CloudFormation::WaitCondition",+ "AWS::CloudFormation::Stack"))# ===========================================================================diff --git a/ministack/services/cloudformation/wait_conditions.py b/ministack/services/cloudformation/wait_conditions.pynew file mode 100644index 00000000..8ac84ad1--- /dev/null+++ b/ministack/services/cloudformation/wait_conditions.py@@ -0,0 +1,273 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).+"""+CloudFormation WaitCondition / WaitConditionHandle — the signal store.++A ``WaitConditionHandle`` registers a token and returns the URL a signal is+PUT to; a ``WaitCondition`` blocks its stack until ``Count`` SUCCESS signals+arrived, a FAILURE signal arrived, or its timeout passed. A wait condition+with a ``CreationPolicy`` has no handle; its signals come through+``SignalResource``, which delivers to the wait condition that is waiting+under the stack id and logical id. Every valid signal is published to the+stack events, as the CreationPolicy reference documents.+"""++import logging+import re+import threading+import time+from urllib.parse import urlparse++from ministack.core.responses import new_uuid++from .custom_resource import _HOST, _PORT++logger = logging.getLogger("cloudformation")++SIGNAL_PATH = "/_ministack/cfn-signal/"+MAX_TIMEOUT_SECONDS = 43200+_ISO8601_DURATION_RE = re.compile(r"^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$")++_lock = threading.Lock()+_changed = threading.Condition(_lock)+_generation = 0+# token → {"stack_id": owning stack, "url": bool, "signals": {UniqueId: {"Status", "Reason", "Data"}}}+_handles: dict = {}+# (stack id, logical id) → {"token", "stack_name", "resource_type"}, while that wait condition waits+_waiting: dict = {}+# physical id of a completed wait condition → its attributes (updates are not+# supported on AWS, so an update returns what the create produced)+_results: dict = {}+++# --- validation of the template values -------------------------------------+++def validate_count(value, logical_id: str) -> int:+ """``Count`` of a WaitCondition or of ``CreationPolicy.ResourceSignal``:+ an integer of at least 1, quoted or not; absent means 1."""+ if value in (None, ""):+ return 1+ try:+ count = int(str(value).strip())+ except (TypeError, ValueError):+ count = 0+ if count < 1:+ raise ValueError(f"WaitCondition {logical_id!r}: Count must be an integer of at least 1")+ return count+++def validate_timeout_seconds(value, logical_id: str) -> int:+ """The WaitCondition ``Timeout`` property: seconds, 1 to 43200."""+ try:+ timeout_s = int(str(value).strip())+ except (TypeError, ValueError):+ timeout_s = -1+ if not 0 < timeout_s <= MAX_TIMEOUT_SECONDS:+ raise ValueError(+ f"WaitCondition {logical_id!r}: Timeout must be a number of seconds between 1 and {MAX_TIMEOUT_SECONDS}"+ )+ return timeout_s+++def validate_resource_signal_timeout(value, logical_id: str) -> int:+ """``CreationPolicy.ResourceSignal.Timeout``: an ISO 8601 duration of the+ form ``PT#H#M#S``, default PT5M, at least one second, at most 12 hours."""+ if value in (None, ""):+ value = "PT5M"+ match = _ISO8601_DURATION_RE.match(value.strip()) if isinstance(value, str) else None+ if not match or not any(match.groups()):+ raise ValueError(+ f"WaitCondition {logical_id!r}: CreationPolicy ResourceSignal Timeout must be an "+ "ISO 8601 duration of the form PT#H#M#S"+ )+ hours, minutes, seconds = (int(g) if g else 0 for g in match.groups())+ timeout_s = hours * 3600 + minutes * 60 + seconds+ if timeout_s < 1:+ raise ValueError(+ f"WaitCondition {logical_id!r}: CreationPolicy ResourceSignal Timeout must be at least one second"+ )+ if timeout_s > MAX_TIMEOUT_SECONDS:+ raise ValueError(+ f"WaitCondition {logical_id!r}: CreationPolicy ResourceSignal Timeout must be at most 12 hours"+ )+ return timeout_s+++# --- handles ------------------------------------------------------------------+++def handle_url(token: str) -> str:+ return f"http://{_HOST}:{_PORT}{SIGNAL_PATH}{token}"+++def _token_of(url) -> str | None:+ if not isinstance(url, str):+ return None+ path = urlparse(url).path+ if not path.startswith(SIGNAL_PATH):+ return None+ return path[len(SIGNAL_PATH) :] or None+++def token_from_url(url) -> str | None:+ """The token of a handle URL this store issued, else None."""+ token = _token_of(url)+ with _lock:+ return token if token in _handles else None+++def has_handle(token: str) -> bool:+ with _lock:+ return token in _handles+++def handle_owner(token: str) -> str | None:+ with _lock:+ entry = _handles.get(token)+ return entry["stack_id"] if entry else None+++def register_slot(stack_id: str, url: bool = False) -> str:+ """A signal slot for a stack. Without ``url`` only SignalResource reaches+ it (the CreationPolicy form) and it is discarded when its wait ends."""+ token = new_uuid()+ with _lock:+ _handles[token] = {"stack_id": stack_id, "url": url, "signals": {}}+ return token+++def register_handle(stack_id: str) -> tuple:+ """Create a handle for a stack: ``(URL, token)``. The URL is the handle's+ physical id and ``Ref``, the token its ``Id`` attribute."""+ token = register_slot(stack_id, url=True)+ return handle_url(token), token+++def discard_handle(url) -> None:+ token = _token_of(url)+ with _lock:+ _handles.pop(token, None)+++# --- signals ------------------------------------------------------------------+++def deliver_signal(token: str, payload: dict) -> bool:+ """Store one signal and publish it to the events of the stack that waits+ on the token. Returns False for an unknown token.++ Raises ValueError for a body without a valid ``Status`` or ``UniqueId``.+ A repeated ``UniqueId`` is a retransmission and is ignored, as on AWS.+ """+ status = payload.get("Status") if isinstance(payload, dict) else None+ if status not in ("SUCCESS", "FAILURE"):+ raise ValueError("Status must be SUCCESS or FAILURE")+ unique_id = payload.get("UniqueId")+ if not isinstance(unique_id, str) or not 1 <= len(unique_id) <= 64:+ raise ValueError("UniqueId must be a string of 1 to 64 characters")+ with _changed:+ entry = _handles.get(token)+ if entry is None:+ return False+ if unique_id in entry["signals"]:+ return True+ entry["signals"][unique_id] = {+ "Status": status,+ "Reason": payload.get("Reason", ""),+ "Data": payload.get("Data", ""),+ }+ waiters = [(key, w) for key, w in _waiting.items() if w["token"] == token]+ _changed.notify_all()+ from .stacks import _add_event++ for (stack_id, logical_id), waiter in waiters:+ _add_event(+ stack_id,+ waiter["stack_name"],+ logical_id,+ waiter["resource_type"],+ "CREATE_IN_PROGRESS",+ f"Received {status} signal with UniqueId {unique_id}",+ )+ return True+++def signal_resource(stack_id: str, logical_id: str, unique_id: str, status: str) -> bool:+ """SignalResource: deliver to the wait condition currently waiting under+ that stack id and logical id. Returns False when nothing waits there."""+ with _lock:+ waiter = _waiting.get((stack_id, logical_id))+ if waiter is None:+ return False+ return deliver_signal(waiter["token"], {"Status": status, "UniqueId": unique_id})+++def wait_for(+ token: str,+ stack_id: str,+ stack_name: str,+ logical_id: str,+ resource_type: str,+ count: int,+ timeout_s: float,+) -> dict:+ """Block until ``count`` SUCCESS signals arrived on ``token``.++ CALLER CONTRACT: must run in a worker thread, never on the event loop; the+ loop has to stay free to receive the signal PUT or the SignalResource call.++ Returns the ``{UniqueId: Data}`` map of the SUCCESS signals.+ Raises RuntimeError on a FAILURE signal or a state reset, TimeoutError+ when the timeout passes first.+ """+ deadline = time.monotonic() + timeout_s+ key = (stack_id, logical_id)+ with _changed:+ generation = _generation+ _waiting[key] = {"token": token, "stack_name": stack_name, "resource_type": resource_type}+ try:+ while True:+ if _generation != generation:+ raise RuntimeError("WaitCondition aborted: the emulator state was reset")+ signals = _handles.get(token, {}).get("signals", {})+ failed = next((s for s in signals.items() if s[1]["Status"] == "FAILURE"), None)+ if failed is not None:+ raise RuntimeError(+ f"WaitCondition received failed message: '{failed[1]['Reason']}' for uniqueId: {failed[0]}"+ )+ successes = {uid: s["Data"] for uid, s in signals.items() if s["Status"] == "SUCCESS"}+ if len(successes) >= count:+ return successes+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise TimeoutError(+ f"WaitCondition timed out. Received {len(successes)} conditions when expecting {count}"+ )+ _changed.wait(timeout=min(remaining, 1.0))+ finally:+ if _waiting.get(key, {}).get("token") == token:+ _waiting.pop(key, None)+ entry = _handles.get(token)+ if entry is not None and not entry["url"]:+ _handles.pop(token, None)+++def remember_result(physical_id: str, attrs: dict) -> None:+ with _lock:+ _results[physical_id] = dict(attrs)+++def recall_result(physical_id: str) -> dict:+ with _lock:+ return dict(_results.get(physical_id, {}))+++def reset():+ global _generation+ with _changed:+ _generation += 1+ _handles.clear()+ _waiting.clear()+ _results.clear()+ _changed.notify_all()diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex bf58498b..1cb75fdf 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -3885,23 +3885,475 @@ def test_cfn_lambda_provisioners_reject_missing_bare_qualifier(cfn, lam):lam.delete_function(FunctionName=fn)-def test_cfn_wait_condition(cfn):- """AWS::CloudFormation::WaitCondition and WaitConditionHandle are no-ops."""- template = {+def _wait_condition_template(timeout="20", count=None):+ """A handle, a wait condition on it, a resource that must not start before+ the wait ends. The 20 s fuse keeps a failing test from parking a worker."""+ props = {"Handle": {"Ref": "Handle"}, "Timeout": timeout}+ if count is not None:+ props["Count"] = count+ return {"AWSTemplateFormatVersion": "2010-09-09","Resources": {"Handle": {"Type": "AWS::CloudFormation::WaitConditionHandle"},- "Wait": {- "Type": "AWS::CloudFormation::WaitCondition",- "Properties": {"Handle": {"Ref": "Handle"}, "Timeout": "10"},+ "Wait": {"Type": "AWS::CloudFormation::WaitCondition", "Properties": props},+ "After": {+ "Type": "AWS::SSM::Parameter",+ "DependsOn": "Wait",+ "Properties": {"Type": "String", "Name": {"Fn::Sub": "/${AWS::StackName}/after"}, "Value": "x"},},},+ "Outputs": {+ "Url": {"Value": {"Ref": "Handle"}},+ "HandleId": {"Value": {"Fn::GetAtt": ["Handle", "Id"]}},+ "Data": {"Value": {"Fn::GetAtt": ["Wait", "Data"]}},+ },}- cfn.create_stack(StackName="cfn-wait", TemplateBody=json.dumps(template))- stack = _wait_stack(cfn, "cfn-wait")- assert stack["StackStatus"] == "CREATE_COMPLETE"- cfn.delete_stack(StackName="cfn-wait")- _wait_stack(cfn, "cfn-wait")+++def _creation_policy_wait_template(policy):+ """The form the CreationPolicy attribute reference documents: no handle,+ no Properties, signals through SignalResource only."""+ return {+ "Resources": {+ "Wait": {"Type": "AWS::CloudFormation::WaitCondition", "CreationPolicy": policy},+ "After": {+ "Type": "AWS::SSM::Parameter",+ "DependsOn": "Wait",+ "Properties": {"Type": "String", "Name": {"Fn::Sub": "/${AWS::StackName}/after"}, "Value": "x"},+ },+ },+ "Outputs": {"Data": {"Value": {"Fn::GetAtt": ["Wait", "Data"]}}},+ }+++def _wait_condition_is_waiting(cfn, stack_name, logical_id="Wait"):+ events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]+ return any(e["LogicalResourceId"] == logical_id and e["ResourceStatus"] == "CREATE_IN_PROGRESS"+ for e in events)+++def _wait_for_wait_condition(cfn, stack_name, timeout=15):+ """Poll until the wait condition is CREATE_IN_PROGRESS; the handle URL, if any."""+ deadline = time.time() + timeout+ while time.time() < deadline:+ if _wait_condition_is_waiting(cfn, stack_name):+ events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]+ return next((e["PhysicalResourceId"] for e in events+ if e["LogicalResourceId"] == "Handle" and e["ResourceStatus"] == "CREATE_COMPLETE"), None)+ time.sleep(0.2)+ raise TimeoutError(f"{stack_name}: the wait condition never started waiting")+++def _assert_still_waiting(cfn, stack_name, seconds=1.0):+ """The stack stays CREATE_IN_PROGRESS for the whole window."""+ deadline = time.time() + seconds+ while time.time() < deadline:+ assert cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["StackStatus"] == "CREATE_IN_PROGRESS"+ time.sleep(0.2)+++def _signal_events(cfn, stack_name):+ return [e.get("ResourceStatusReason", "")+ for e in cfn.describe_stack_events(StackName=stack_name)["StackEvents"]+ if "signal with UniqueId" in e.get("ResourceStatusReason", "")]+++def _put_wait_condition_signal(url, status="SUCCESS", unique_id="ID1", data="", reason="",+ content_type="", body=None):+ """PUT the signal JSON to the handle URL, addressed at the test endpoint+ (the minted URL names the server's own host), with an empty Content-Type+ as the user guide asks for."""+ endpoint = urlparse(os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"))+ target = urlparse(url)._replace(scheme=endpoint.scheme, netloc=endpoint.netloc).geturl()+ if body is None:+ body = json.dumps({"Status": status, "UniqueId": unique_id, "Data": data, "Reason": reason}).encode()+ req = urllib.request.Request(target, data=body, method="PUT", headers={"Content-Type": content_type})+ with urllib.request.urlopen(req) as resp:+ return resp.status+++def _assert_validation_error(exc_info, message):+ assert exc_info.value.response["Error"]["Code"] == "ValidationError"+ assert message in exc_info.value.response["Error"]["Message"]+++def test_cfn_wait_condition(cfn):+ """A WaitCondition holds the stack until its handle receives the SUCCESS+ signal; the handle's Ref is the signal URL, Data carries the signal, the+ signal is published to the stack events, a deleted handle answers 404."""+ stack_name = f"cfn-wait-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_wait_condition_template()))+ try:+ url = _wait_for_wait_condition(cfn, stack_name)+ assert "/_ministack/cfn-signal/" in url+ events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]+ assert not any(e["LogicalResourceId"] == "After" for e in events)+ _assert_still_waiting(cfn, stack_name, 0.5)+ assert _put_wait_condition_signal(url, "SUCCESS", "ID1234", data="Application has completed configuration.") == 200+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ assert _output(stack, "Url") == url+ assert url.endswith("/" + _output(stack, "HandleId"))+ assert json.loads(_output(stack, "Data")) == {"ID1234": "Application has completed configuration."}+ resources = {r["LogicalResourceId"]: r for r in cfn.describe_stack_resources(StackName=stack_name)["StackResources"]}+ assert resources["Handle"]["PhysicalResourceId"] == url+ assert resources["After"]["ResourceStatus"] == "CREATE_COMPLETE"+ assert _signal_events(cfn, stack_name) == ["Received SUCCESS signal with UniqueId ID1234"]+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ with pytest.raises(urllib.error.HTTPError) as exc_info:+ _put_wait_condition_signal(url, "SUCCESS", "late")+ assert exc_info.value.code == 404+++def test_cfn_wait_condition_failure_signal_rolls_back(cfn):+ stack_name = f"cfn-wait-fail-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_wait_condition_template()))+ try:+ url = _wait_for_wait_condition(cfn, stack_name)+ assert _put_wait_condition_signal(url, "FAILURE", "node-1", reason="Setup failed") == 200+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "ROLLBACK_COMPLETE"+ reasons = _stack_event_reasons(cfn, stack_name)+ assert "WaitCondition received failed message: 'Setup failed' for uniqueId: node-1" in reasons+ assert "Received FAILURE signal with UniqueId node-1" in reasons+ assert not any(e["LogicalResourceId"] == "After"+ for e in cfn.describe_stack_events(StackName=stack_name)["StackEvents"])+ # The rollback deleted the handle: its URL is gone.+ with pytest.raises(urllib.error.HTTPError) as exc_info:+ _put_wait_condition_signal(url, "SUCCESS", "late")+ assert exc_info.value.code == 404+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++def test_cfn_wait_condition_timeout_rolls_back(cfn):+ stack_name = f"cfn-wait-timeout-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_wait_condition_template(timeout="1")))+ try:+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "ROLLBACK_COMPLETE"+ assert "WaitCondition timed out. Received 0 conditions when expecting 1" in _stack_event_reasons(cfn, stack_name)+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++def test_cfn_wait_condition_count_and_signal_endpoint_rules(cfn):+ """Count=2 needs two distinct UniqueIds; a repeated UniqueId is a+ retransmission and does not count. The endpoint refuses a non-empty+ Content-Type (403), a body that is not the signal JSON (400) and an+ unknown token (404)."""+ stack_name = f"cfn-wait-count-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_wait_condition_template(count=2)))+ try:+ url = _wait_for_wait_condition(cfn, stack_name)+ for kwargs, code in (+ ({"status": "DONE"}, 400),+ ({"body": b"not json"}, 400),+ ({"content_type": "application/json"}, 403),+ ({"url": url.rsplit("/", 1)[0] + "/no-such-token"}, 404),+ ):+ with pytest.raises(urllib.error.HTTPError) as exc_info:+ _put_wait_condition_signal(**{"url": url, "unique_id": "node-1", **kwargs})+ assert exc_info.value.code == code, kwargs+ assert "must be an empty string or omitted" in str(+ pytest.raises(urllib.error.HTTPError, _put_wait_condition_signal, url,+ unique_id="node-1", content_type="text/plain").value.read())+ _put_wait_condition_signal(url, "SUCCESS", "node-1", data="first")+ _put_wait_condition_signal(url, "SUCCESS", "node-1", data="again")+ _assert_still_waiting(cfn, stack_name)+ assert _signal_events(cfn, stack_name) == ["Received SUCCESS signal with UniqueId node-1"]+ _put_wait_condition_signal(url, "SUCCESS", "node-2", data="second")+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ assert json.loads(_output(stack, "Data")) == {"node-1": "first", "node-2": "second"}+ assert sorted(_signal_events(cfn, stack_name)) == [+ "Received SUCCESS signal with UniqueId node-1",+ "Received SUCCESS signal with UniqueId node-2",+ ]+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++def test_cfn_wait_condition_handle_must_be_a_handle_of_the_stack(cfn):+ """A Handle that is not a handle URL, or the handle of another stack, fails+ the resource; the other stack's handle stays usable."""+ other_name = f"cfn-wait-other-{_uuid_mod.uuid4().hex[:8]}"+ stack_name = f"cfn-wait-badhandle-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=other_name, TemplateBody=json.dumps(_wait_condition_template()))+ try:+ other_url = _wait_for_wait_condition(cfn, other_name)+ for handle, message in (+ (other_url, "Handle must be the Ref of an AWS::CloudFormation::WaitConditionHandle of this stack"),+ ("https://example.local/not-a-handle", "Handle must be the Ref of an AWS::CloudFormation::WaitConditionHandle"),+ ):+ template = _wait_condition_template()+ template["Resources"]["Wait"]["Properties"]["Handle"] = handle+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ try:+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "ROLLBACK_COMPLETE"+ assert message in _stack_event_reasons(cfn, stack_name)+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ _put_wait_condition_signal(other_url, "SUCCESS", "still-works")+ assert _wait_stack(cfn, other_name)["StackStatus"] == "CREATE_COMPLETE"+ finally:+ _delete_cfn_test_stack(cfn, other_name)+++ ("props", "message"),+ [+ ({"Count": 1}, "Timeout is required"),+ ({"Timeout": "30", "Count": "0"}, "Count must be an integer of at least 1"),+ ],+)+def test_cfn_wait_condition_refuses_invalid_properties(cfn, props, message):+ stack_name = f"cfn-wait-invalid-{_uuid_mod.uuid4().hex[:8]}"+ template = _wait_condition_template()+ template["Resources"]["Wait"]["Properties"] = {"Handle": {"Ref": "Handle"}, **props}+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ try:+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "ROLLBACK_COMPLETE"+ assert message in _stack_event_reasons(cfn, stack_name)+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++ ("validator", "value", "message"),+ [+ ("validate_timeout_seconds", "0", "Timeout must be a number of seconds between 1 and 43200"),+ ("validate_timeout_seconds", "43201", "Timeout must be a number of seconds between 1 and 43200"),+ ("validate_timeout_seconds", "PT5M", "Timeout must be a number of seconds between 1 and 43200"),+ ("validate_count", "two", "Count must be an integer of at least 1"),+ ("validate_resource_signal_timeout", "5 minutes", "ResourceSignal Timeout must be an ISO 8601 duration"),+ ("validate_resource_signal_timeout", "PT0S", "ResourceSignal Timeout must be at least one second"),+ ("validate_resource_signal_timeout", "PT13H", "ResourceSignal Timeout must be at most 12 hours"),+ ],+)+def test_cfn_wait_condition_validators(validator, value, message):+ from ministack.services.cloudformation import wait_conditions as wc++ with pytest.raises(ValueError, match=re.escape(message)):+ getattr(wc, validator)(value, "Wait")+ assert wc.validate_count("3", "Wait") == 3+ assert wc.validate_count(None, "Wait") == 1+ assert wc.validate_timeout_seconds(" 300 ", "Wait") == 300+ assert wc.validate_resource_signal_timeout(None, "Wait") == 300+ assert wc.validate_resource_signal_timeout("PT1H30M15S", "Wait") == 5415+++ "policy",+ [+ {"ResourceSignal": {"Timeout": "PT2M", "Count": "2"}},+ {"ResourceSignal": {"Count": 2}},+ ],+)+def test_cfn_wait_condition_creation_policy_waits_for_signal_resource(cfn, policy):+ """The CreationPolicy form: no handle, SignalResource only, Timeout+ defaults to PT5M; an update never waits again."""+ stack_name = f"cfn-wait-cp-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_creation_policy_wait_template(policy)))+ try:+ _wait_for_wait_condition(cfn, stack_name)+ cfn.signal_resource(StackName=stack_name, LogicalResourceId="Wait", UniqueId="i-1", Status="SUCCESS")+ _assert_still_waiting(cfn, stack_name)+ assert _signal_events(cfn, stack_name) == ["Received SUCCESS signal with UniqueId i-1"]+ cfn.signal_resource(StackName=stack_name, LogicalResourceId="Wait", UniqueId="i-2", Status="SUCCESS")+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ assert json.loads(_output(stack, "Data")) == {"i-1": "", "i-2": ""}+ assert len(_signal_events(cfn, stack_name)) == 2+ template = _creation_policy_wait_template({"ResourceSignal": {"Count": "5"}})+ template["Resources"]["After"]["Properties"]["Value"] = "y"+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE"+ assert json.loads(_output(stack, "Data")) == {"i-1": "", "i-2": ""}+ finally:+ _delete_cfn_test_stack(cfn, stack_name)++[email protected]("policy", [{}, {"ResourceSignal": {}}])+def test_cfn_wait_condition_creation_policy_defaults(cfn, policy):+ """An empty CreationPolicy or ResourceSignal means one signal, PT5M."""+ stack_name = f"cfn-wait-cpdef-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_creation_policy_wait_template(policy)))+ try:+ _wait_for_wait_condition(cfn, stack_name)+ _assert_still_waiting(cfn, stack_name, 0.5)+ cfn.signal_resource(StackName=stack_name, LogicalResourceId="Wait", UniqueId="only", Status="SUCCESS")+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++ ("policy", "expected"),+ [+ ({"ResourceSignal": {"Timeout": "PT1S"}}, "WaitCondition timed out. Received 0 conditions when expecting 1"),+ ("PT5M", "CreationPolicy must be an object"),+ ({"ResourceSignal": "PT5M"}, "CreationPolicy ResourceSignal must be an object"),+ ],+)+def test_cfn_wait_condition_creation_policy_timeout_and_shape(cfn, policy, expected):+ stack_name = f"cfn-wait-cpfail-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_creation_policy_wait_template(policy)))+ try:+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "ROLLBACK_COMPLETE"+ assert expected in _stack_event_reasons(cfn, stack_name)+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++def test_cfn_wait_condition_store_reset_releases_a_waiter():+ """The service's reset (what POST /_ministack/reset calls) must not leave+ a worker thread blocked in a wait that nothing can signal any more. Run+ in-process against this test's own copy of the stores."""+ import threading++ from ministack.services import cloudformation as cfn_service+ from ministack.services.cloudformation import wait_conditions as wc++ token = wc.register_slot("arn:aws:cloudformation:eu-central-1:000000000000:stack/reset-probe/1")+ outcome = {}++ def waiter():+ try:+ wc.wait_for(token, "arn:aws:cloudformation:eu-central-1:000000000000:stack/reset-probe/1",+ "reset-probe", "Wait", "AWS::CloudFormation::WaitCondition", 1, 30)+ except Exception as exc:+ outcome["error"] = exc++ thread = threading.Thread(target=waiter, daemon=True)+ thread.start()+ time.sleep(0.2)+ cfn_service.reset()+ thread.join(timeout=5)+ assert not thread.is_alive()+ assert "state was reset" in str(outcome.get("error"))+++def test_cfn_signal_resource_completes_the_wait_condition(cfn):+ """SignalResource delivers a signal without the handle URL; the stack name+ or its id addresses the stack."""+ stack_name = f"cfn-wait-signal-{_uuid_mod.uuid4().hex[:8]}"+ stack_id = cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_wait_condition_template(count=2)))["StackId"]+ try:+ _wait_for_wait_condition(cfn, stack_name)+ with pytest.raises(ClientError) as exc_info:+ cfn.signal_resource(StackName=stack_name, LogicalResourceId="After", UniqueId="s1", Status="SUCCESS")+ _assert_validation_error(exc_info, f"Resource [After] in stack [{stack_name}] is not waiting for signals")+ with pytest.raises(ClientError) as exc_info:+ cfn.signal_resource(StackName=stack_name, LogicalResourceId="Wait", UniqueId="s1", Status="DONE")+ _assert_validation_error(exc_info, "Member must satisfy enum value set: [FAILURE, SUCCESS]")+ with pytest.raises(ClientError) as exc_info:+ cfn.signal_resource(StackName=stack_name, LogicalResourceId="Wait", UniqueId="x" * 65, Status="SUCCESS")+ _assert_validation_error(exc_info, "Member must have length less than or equal to 64")+ cfn.signal_resource(StackName=stack_name, LogicalResourceId="Wait", UniqueId="s1", Status="SUCCESS")+ cfn.signal_resource(StackName=stack_id, LogicalResourceId="Wait", UniqueId="s2", Status="SUCCESS")+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ assert json.loads(_output(stack, "Data")) == {"s1": "", "s2": ""}+ assert sorted(_signal_events(cfn, stack_name)) == [+ "Received SUCCESS signal with UniqueId s1",+ "Received SUCCESS signal with UniqueId s2",+ ]+ with pytest.raises(ClientError) as exc_info:+ cfn.signal_resource(StackName=stack_name, LogicalResourceId="Wait", UniqueId="s3", Status="SUCCESS")+ _assert_validation_error(exc_info, f"Stack [{stack_name}] is in CREATE_COMPLETE state and cannot be signaled")+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ with pytest.raises(ClientError) as exc_info:+ cfn.signal_resource(StackName=stack_name, LogicalResourceId="Wait", UniqueId="s4", Status="SUCCESS")+ _assert_validation_error(exc_info, f"Stack [{stack_name}] does not exist")++[email protected]("missing", ["StackName", "LogicalResourceId", "UniqueId", "Status"])+def test_cfn_signal_resource_requires_every_field(missing):+ """boto3 refuses a missing field itself; a client without parameter+ validation shows the service's own answer."""+ client = boto3.client(+ "cloudformation",+ endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),+ region_name=os.environ.get("AWS_DEFAULT_REGION", "us-east-1"),+ aws_access_key_id="test",+ aws_secret_access_key="test",+ config=Config(parameter_validation=False, retries={"mode": "standard"}),+ )+ params = {"StackName": "no-such-stack", "LogicalResourceId": "Wait", "UniqueId": "s1", "Status": "SUCCESS"}+ params.pop(missing)+ with pytest.raises(ClientError) as exc_info:+ client.signal_resource(**params)+ _assert_validation_error(exc_info, f"{missing} is required")+++def test_cfn_signal_resource_failure_rolls_back(cfn):+ stack_name = f"cfn-wait-signalfail-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_wait_condition_template()))+ try:+ _wait_for_wait_condition(cfn, stack_name)+ cfn.signal_resource(StackName=stack_name, LogicalResourceId="Wait", UniqueId="node-9", Status="FAILURE")+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "ROLLBACK_COMPLETE"+ reasons = _stack_event_reasons(cfn, stack_name)+ assert "for uniqueId: node-9" in reasons+ assert "Received FAILURE signal with UniqueId node-9" in reasons+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++def test_cfn_wait_condition_in_a_nested_stack(cfn, s3):+ """A nested stack deploys on a worker thread, so a wait condition inside+ it holds the parent without blocking the server; SignalResource on the+ child stack (its id is the parent's resource physical id) releases it."""+ suffix = _uuid_mod.uuid4().hex[:8]+ templates_bucket = f"cfn-wait-nested-{suffix}"+ s3.create_bucket(Bucket=templates_bucket)+ s3.put_object(Bucket=templates_bucket, Key="child.json",+ Body=json.dumps(_wait_condition_template()).encode())+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")+ parent_name = f"cfn-wait-parent-{suffix}"+ parent_template = {+ "Resources": {+ "Nested": {+ "Type": "AWS::CloudFormation::Stack",+ "Properties": {"TemplateURL": f"{endpoint}/{templates_bucket}/child.json"},+ },+ "AfterNested": {+ "Type": "AWS::SSM::Parameter",+ "DependsOn": "Nested",+ "Properties": {"Type": "String", "Name": f"/{parent_name}/after", "Value": "x"},+ },+ },+ "Outputs": {"ChildData": {"Value": {"Fn::GetAtt": ["Nested", "Outputs.Data"]}}},+ }+ cfn.create_stack(StackName=parent_name, TemplateBody=json.dumps(parent_template))+ try:+ deadline = time.time() + 15+ child_id = None+ while time.time() < deadline and child_id is None:+ for summary in cfn.list_stacks(StackStatusFilter=["CREATE_IN_PROGRESS"])["StackSummaries"]:+ if summary["StackName"].startswith(f"{parent_name}-Nested-") \+ and _wait_condition_is_waiting(cfn, summary["StackId"]):+ child_id = summary["StackId"]+ time.sleep(0.2)+ assert child_id, "the child stack never reached its wait condition"+ # The server answers while the parent waits.+ assert cfn.describe_stacks(StackName=parent_name)["Stacks"][0]["StackStatus"] == "CREATE_IN_PROGRESS"+ cfn.signal_resource(StackName=child_id, LogicalResourceId="Wait", UniqueId="child-1", Status="SUCCESS")+ stack = _wait_stack(cfn, parent_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ assert json.loads(_output(stack, "ChildData")) == {"child-1": ""}+ nested = next(r for r in cfn.describe_stack_resources(StackName=parent_name)["StackResources"]+ if r["LogicalResourceId"] == "Nested")+ assert nested["PhysicalResourceId"] == child_id+ finally:+ _delete_cfn_test_stack(cfn, parent_name)+ try:+ s3.delete_object(Bucket=templates_bucket, Key="child.json")+ s3.delete_bucket(Bucket=templates_bucket)+ except ClientError:+ pass@pytest.mark.parametrize(