Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(cloudformation): keep a rolled-back stack's diagnostics until the next redeploy (#2365)

Priamo Germosenc54f8ddf0230
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java
index 3850878bb5..ee51bff2a0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java
@@ -210,7 +210,9 @@ public class CloudFormationQueryHandler {
List<String> capabilities = extractList(params, "Capabilities.member.");
Map<String, String> tags = extractTags(params);
- ChangeSet cs = cfnService.createChangeSet(stackName, changeSetName, changeSetType,
+ // The CreateChangeSet operation, unlike the change sets CreateStack/UpdateStack build
+ // internally, may attach a CREATE change set to a stack still in REVIEW_IN_PROGRESS.
+ ChangeSet cs = cfnService.createChangeSetForRequest(stackName, changeSetName, changeSetType,
templateBody, templateUrl, parameters, capabilities, tags, region);
String xml = new XmlBuilder()
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java
index 079a8134d2..49271756e6 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java
@@ -151,7 +151,31 @@ public class CloudFormationService {
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region) {
return createChangeSet(stackName, changeSetName, changeSetType, templateBody, templateUrl,
- parameters, capabilities, tags, region, regionResolver.getAccountId());
+ parameters, capabilities, tags, region, regionResolver.getAccountId(), false);
+ }
+
+ /**
+ * Entry point for the {@code CreateChangeSet} operation itself, as opposed to the change sets
+ * {@code CreateStack}/{@code UpdateStack}/StackSet deployment create internally and execute
+ * immediately.
+ *
+ * <p>The difference matters for exactly one case: a CREATE change set is allowed to attach to a
+ * stack already sitting in {@code REVIEW_IN_PROGRESS}, because that status means "a CREATE
+ * change set was created here and nobody has executed it yet" - the stack is a placeholder, not
+ * a deployment. {@code aws cloudformation deploy} and SAM rely on this: {@code has_stack} in the
+ * AWS CLI's deployer treats a {@code REVIEW_IN_PROGRESS} stack as nonexistent and sends a second
+ * CREATE change set against it, which real CloudFormation accepts. Routing that exemption
+ * through a separate entry point rather than the shared one keeps it off the implicit callers,
+ * where a stack is only ever momentarily {@code REVIEW_IN_PROGRESS} - between {@link #newStack}
+ * and the execute that immediately follows - and treating that window as reusable would let two
+ * racing {@code CreateStack} requests both provision the same template.
+ */
+ public ChangeSet createChangeSetForRequest(String stackName, String changeSetName, String changeSetType,
+ String templateBody, String templateUrl,
+ Map<String, String> parameters, List<String> capabilities,
+ Map<String, String> tags, String region) {
+ return createChangeSet(stackName, changeSetName, changeSetType, templateBody, templateUrl,
+ parameters, capabilities, tags, region, regionResolver.getAccountId(), true);
}
/**
@@ -168,48 +192,93 @@ public class CloudFormationService {
String templateBody, String templateUrl,
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region, String accountId) {
+ return createChangeSet(stackName, changeSetName, changeSetType, templateBody, templateUrl,
+ parameters, capabilities, tags, region, accountId, false);
+ }
+
+ private ChangeSet createChangeSet(String stackName, String changeSetName, String changeSetType,
+ String templateBody, String templateUrl,
+ Map<String, String> parameters, List<String> capabilities,
+ Map<String, String> tags, String region, String accountId,
+ boolean attachToReviewInProgressStack) {
String resolvedTemplate = resolveTemplate(templateBody, templateUrl);
// Reject an unresolvable condition dependency graph up front, before any stack state is
// created, so CreateStack/UpdateStack fail synchronously the way real CloudFormation does.
validateConditionDependencies(resolvedTemplate, parameters, region, accountId);
- // Detect first creation atomically: the mapping function runs at most once per key, so the
- // flag is only set for the thread that actually creates the stack (no double-recording under
- // concurrent CreateChangeSet calls).
- boolean[] stackCreated = {false};
- Stack stack = stacks.computeIfAbsent(key(stackName, region), k -> {
- stackCreated[0] = true;
- Stack s = newStack(stackName, region);
- if (tags != null) s.getTags().putAll(tags);
- return s;
+ // A CREATE change set against a name that already has a stack of any status - including
+ // ROLLBACK_COMPLETE - is a real conflict: AWS requires an explicit DeleteStack before a
+ // name can be reused, even when the existing stack already failed to create (see #2207).
+ //
+ // The one exception is a stack in REVIEW_IN_PROGRESS, and only for the CreateChangeSet
+ // operation itself (see createChangeSetForRequest): that status means a CREATE change set
+ // exists but has never been executed, so the stack is a placeholder the next CREATE change
+ // set attaches to rather than a deployment to conflict with. The AWS CLI's `deploy` and SAM
+ // both depend on it - their has_stack treats REVIEW_IN_PROGRESS as nonexistent and sends a
+ // second CREATE change set, which real CloudFormation accepts.
+ //
+ // The existence check and the insert must be one atomic operation: compute() holds the
+ // map's per-key lock for the whole call, so two CreateStack requests racing for the same
+ // unused name can no longer both see "absent" and then share whichever Stack
+ // computeIfAbsent settled on - the second one now finds the first's stack already there
+ // and throws, instead of both executing the template concurrently. That race is also why
+ // the exemption above is scoped to the explicit operation: on the CreateStack path every
+ // brand-new stack is REVIEW_IN_PROGRESS for the moment between newStack() and the execute
+ // that follows it, so exempting the status outright would hand the racing request the same
+ // stack and reopen exactly this hole.
+ //
+ // Recording the change set happens inside the same remapping function, for the same reason.
+ // Stack#changeSets is a plain LinkedHashMap, so two requests that legitimately share one
+ // stack - two UPDATE change sets on a live stack, or two CREATE change sets attaching to the
+ // same REVIEW_IN_PROGRESS placeholder - would otherwise both write it after the per-key lock
+ // was already released, losing an accepted change set or corrupting the map's links. Only
+ // persistStack() stays outside: it is storage I/O, and compute()'s contract is that the
+ // remapping function does short, non-blocking work.
+ boolean isCreateType = changeSetType == null || "CREATE".equalsIgnoreCase(changeSetType);
+ ChangeSet[] created = new ChangeSet[1];
+ Stack stack = stacks.compute(key(stackName, region), (k, existing) -> {
+ Stack target;
+ if (existing == null) {
+ target = newStack(stackName, region);
+ if (tags != null) target.getTags().putAll(tags);
+ // A CREATE change set puts a brand-new stack into REVIEW_IN_PROGRESS. Record the
+ // matching stack-level event (as AWS and LocalStack do) so DescribeStackEvents is
+ // non-empty straight after change-set creation — tooling such as the AWS SAM CLI
+ // reads StackEvents[0] there and otherwise fails with an IndexError.
+ // (CreateChangeSet defaults a null type to CREATE.)
+ if (isCreateType) {
+ addEvent(target, target.getStackName(), target.getStackId(),
+ "AWS::CloudFormation::Stack", "REVIEW_IN_PROGRESS", "User Initiated");
+ }
+ } else {
+ boolean reusableReviewPlaceholder =
+ attachToReviewInProgressStack && "REVIEW_IN_PROGRESS".equals(existing.getStatus());
+ if (isCreateType && !reusableReviewPlaceholder) {
+ throw new AwsException("AlreadyExistsException",
+ "Stack [" + stackName + "] already exists", 400);
+ }
+ target = existing;
+ }
+
+ ChangeSet cs = new ChangeSet();
+ cs.setChangeSetId(AwsArnUtils.Arn.of("cloudformation", region, regionResolver.getAccountId(), "changeSet/" + changeSetName + "/" + UUID.randomUUID()).toString());
+ cs.setChangeSetName(changeSetName);
+ cs.setStackName(stackName);
+ cs.setStackId(target.getStackId());
+ cs.setChangeSetType(changeSetType != null ? changeSetType : "CREATE");
+ cs.setTemplateBody(resolvedTemplate);
+ cs.setParameters(parameters);
+ cs.setCapabilities(capabilities);
+ cs.setStatus("CREATE_COMPLETE");
+ cs.setExecutionStatus("AVAILABLE");
+ target.getChangeSets().put(changeSetName, cs);
+ created[0] = cs;
+ return target;
});
- // A CREATE change set puts a brand-new stack into REVIEW_IN_PROGRESS. Record the matching
- // stack-level event (as AWS and LocalStack do) so DescribeStackEvents is non-empty straight
- // after change-set creation — tooling such as the AWS SAM CLI reads StackEvents[0] there and
- // otherwise fails with an IndexError. (CreateChangeSet defaults a null type to CREATE.)
- boolean isCreateType = changeSetType == null || "CREATE".equalsIgnoreCase(changeSetType);
- if (stackCreated[0] && isCreateType) {
- addEvent(stack, stack.getStackName(), stack.getStackId(),
- "AWS::CloudFormation::Stack", "REVIEW_IN_PROGRESS", "User Initiated");
- }
-
- ChangeSet cs = new ChangeSet();
- cs.setChangeSetId(AwsArnUtils.Arn.of("cloudformation", region, regionResolver.getAccountId(), "changeSet/" + changeSetName + "/" + UUID.randomUUID()).toString());
- cs.setChangeSetName(changeSetName);
- cs.setStackName(stackName);
- cs.setStackId(stack.getStackId());
- cs.setChangeSetType(changeSetType != null ? changeSetType : "CREATE");
- cs.setTemplateBody(resolvedTemplate);
- cs.setParameters(parameters);
- cs.setCapabilities(capabilities);
- cs.setStatus("CREATE_COMPLETE");
- cs.setExecutionStatus("AVAILABLE");
-
- stack.getChangeSets().put(changeSetName, cs);
persistStack(stack);
- return cs;
+ return created[0];
}
// ── DescribeChangeSet ─────────────────────────────────────────────────────
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
index ec4b9558d6..8c5e8c83f9 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
@@ -20,6 +20,11 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
@@ -9655,6 +9660,401 @@ class CloudFormationIntegrationTest {
.body(containsString("CREATE_FAILED"));
}
+ @Test
+ void createStack_onExistingActiveStack_throwsAlreadyExistsException() {
+ String template = """
+ {
+ "Resources": {
+ "MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2207-active-bus" } }
+ }
+ }
+ """;
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", "cfn-2207-active-stack")
+ .formParam("TemplateBody", template)
+ .when().post("/").then().statusCode(200);
+
+ // A second CreateStack for the same name, while the first is still ACTIVE, is a real
+ // conflict - it must not silently re-run the template against the live stack.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", "cfn-2207-active-stack")
+ .formParam("TemplateBody", template)
+ .when().post("/")
+ .then()
+ .body(containsString("AlreadyExistsException"))
+ .body(containsString("already exists"));
+ }
+
+ @Test
+ void createStack_concurrentRequestsForUnusedName_exactlyOneSucceeds() throws InterruptedException {
+ // The existence check and the stack-map insert used to be two separate operations, so two
+ // requests racing for the same never-before-used name could both observe "absent" and then
+ // share whichever Stack computeIfAbsent settled on, each independently executing the
+ // template - duplicate provisioning instead of one AlreadyExistsException. Verifies the
+ // check-and-insert is now atomic.
+ String template = """
+ {
+ "Resources": {
+ "MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2207-concurrent-bus" } }
+ }
+ }
+ """;
+ String stackName = "cfn-2207-concurrent-stack";
+ int attempts = 16;
+
+ CountDownLatch ready = new CountDownLatch(attempts);
+ CountDownLatch go = new CountDownLatch(1);
+ AtomicInteger succeeded = new AtomicInteger();
+ AtomicInteger conflicted = new AtomicInteger();
+ ExecutorService pool = Executors.newFixedThreadPool(attempts);
+ try {
+ for (int i = 0; i < attempts; i++) {
+ pool.submit(() -> {
+ ready.countDown();
+ try {
+ go.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return;
+ }
+ String body = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when().post("/").then().extract().asString();
+ if (body.contains("AlreadyExistsException")) {
+ conflicted.incrementAndGet();
+ } else if (body.contains("<StackId>")) {
+ succeeded.incrementAndGet();
+ }
+ });
+ }
+ assertTrue(ready.await(10, TimeUnit.SECONDS), "workers failed to line up in time");
+ go.countDown();
+ } finally {
+ pool.shutdown();
+ assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "requests did not finish in time");
+ }
+
+ assertEquals(1, succeeded.get(), "exactly one CreateStack should have won the race");
+ assertEquals(attempts - 1, conflicted.get(), "every other request should see AlreadyExistsException");
+ }
+
+ @Test
+ void createStack_onRollbackCompleteStack_alsoThrowsAlreadyExistsException() {
+ // #2207: a stack whose first CREATE fails ends in ROLLBACK_COMPLETE and stays fully
+ // describable - it is not deleted eagerly at rollback time. Matching real AWS,
+ // ROLLBACK_COMPLETE is still a real conflict for CreateStack: an explicit DeleteStack is
+ // required before the name can be reused (verified against AWS's own CreateStack API
+ // reference and troubleshooting docs, which list AlreadyExists unconditionally - there is
+ // no ROLLBACK_COMPLETE carve-out).
+ String failingTemplate = """
+ {
+ "Resources": {
+ "BadSecret": {
+ "Type": "AWS::SecretsManager::Secret",
+ "Properties": {
+ "Name": "cfn-2207-redeploy-secret",
+ "SecretString": "explicit",
+ "GenerateSecretString": { "PasswordLength": 32 }
+ }
+ }
+ }
+ }
+ """;
+ String stackName = "cfn-2207-redeploy-stack";
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", failingTemplate)
+ .when().post("/").then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when().post("/")
+ .then().statusCode(200).body(containsString("<StackStatus>ROLLBACK_COMPLETE</StackStatus>"));
+
+ // A second CreateStack still conflicts - the diagnostic is preserved, not silently
+ // superseded.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", failingTemplate)
+ .when().post("/")
+ .then().body(containsString("AlreadyExistsException"));
+
+ // The failed attempt's diagnostic is still readable after that rejected retry.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackEvents")
+ .formParam("StackName", stackName)
+ .when().post("/")
+ .then().statusCode(200).body(containsString("CREATE_FAILED"));
+
+ // An explicit DeleteStack, though, clears the way for a fresh CreateStack - matching the
+ // issue's suggested fix: "let DeleteStack remove it."
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStack")
+ .formParam("StackName", stackName)
+ .when().post("/").then().statusCode(200);
+
+ String workingTemplate = """
+ {
+ "Resources": {
+ "MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2207-redeploy-bus" } }
+ }
+ }
+ """;
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", workingTemplate)
+ .when().post("/").then().statusCode(200).body(containsString("<StackId>"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when().post("/")
+ .then().statusCode(200).body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
+ }
+
+ @Test
+ void createChangeSet_secondCreateTypeBeforeExecution_attachesToReviewInProgressStack() {
+ // `aws cloudformation deploy` (and SAM, which shares the code) treats a REVIEW_IN_PROGRESS
+ // stack as nonexistent - see has_stack in the AWS CLI's deployer.py - and sends another
+ // CREATE change set against it, which real CloudFormation accepts: a CREATE change set
+ // leaves the stack in REVIEW_IN_PROGRESS until somebody executes it, so it is a placeholder
+ // rather than a deployment to conflict with. Retrying a failed `deploy` before any execute
+ // must therefore not hit AlreadyExistsException.
+ String template = """
+ {
+ "Resources": {
+ "MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2365-review-bus" } }
+ }
+ }
+ """;
+ String stackName = "cfn-2365-review-stack";
+
+ String firstStackId = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateChangeSet")
+ .formParam("StackName", stackName)
+ .formParam("ChangeSetName", "deploy-attempt-1")
+ .formParam("ChangeSetType", "CREATE")
+ .formParam("TemplateBody", template)
+ .when().post("/")
+ .then().statusCode(200).extract().path("CreateChangeSetResponse.CreateChangeSetResult.StackId");
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when().post("/")
+ .then().statusCode(200).body(containsString("<StackStatus>REVIEW_IN_PROGRESS</StackStatus>"));
+
+ // The retry: same name, still nothing executed. It attaches to the placeholder rather than
+ // conflicting with it, and lands on the same stack rather than creating a second one.
+ String secondStackId = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateChangeSet")
+ .formParam("StackName", stackName)
+ .formParam("ChangeSetName", "deploy-attempt-2")
+ .formParam("ChangeSetType", "CREATE")
+ .formParam("TemplateBody", template)
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(not(containsString("AlreadyExistsException")))
+ .extract().path("CreateChangeSetResponse.CreateChangeSetResult.StackId");
+
+ assertEquals(firstStackId, secondStackId, "the retry should attach to the same placeholder stack");
+
+ // Executing the retry's change set still deploys normally.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ExecuteChangeSet")
+ .formParam("StackName", stackName)
+ .formParam("ChangeSetName", "deploy-attempt-2")
+ .when().post("/").then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when().post("/")
+ .then().statusCode(200).body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
+ }
+
+ @Test
+ void createChangeSet_createTypeAfterExecution_stillThrowsAlreadyExistsException() {
+ // The exemption is narrow: it covers a stack that never left REVIEW_IN_PROGRESS. Once the
+ // change set has been executed the stack is a real deployment, and a further CREATE change
+ // set is the ordinary name conflict again.
+ String template = """
+ {
+ "Resources": {
+ "MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2365-executed-bus" } }
+ }
+ }
+ """;
+ String stackName = "cfn-2365-executed-stack";
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateChangeSet")
+ .formParam("StackName", stackName)
+ .formParam("ChangeSetName", "deploy-attempt-1")
+ .formParam("ChangeSetType", "CREATE")
+ .formParam("TemplateBody", template)
+ .when().post("/").then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ExecuteChangeSet")
+ .formParam("StackName", stackName)
+ .formParam("ChangeSetName", "deploy-attempt-1")
+ .when().post("/").then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateChangeSet")
+ .formParam("StackName", stackName)
+ .formParam("ChangeSetName", "deploy-attempt-2")
+ .formParam("ChangeSetType", "CREATE")
+ .formParam("TemplateBody", template)
+ .when().post("/")
+ .then().body(containsString("AlreadyExistsException"));
+ }
+
+ @Test
+ void createChangeSet_concurrentRequestsOnSamePlaceholder_keepEveryChangeSet() throws InterruptedException {
+ // Two requests are allowed to share one stack - two CREATE change sets attaching to the
+ // same REVIEW_IN_PROGRESS placeholder, or two UPDATE change sets on a live stack. Stack's
+ // changeSets is a plain LinkedHashMap, so recording the change set has to happen inside the
+ // same per-key lock that resolves the stack; done afterwards, concurrent writers lose an
+ // accepted change set or corrupt the map.
+ String template = """
+ {
+ "Resources": {
+ "MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2365-parallel-bus" } }
+ }
+ }
+ """;
+ String stackName = "cfn-2365-parallel-stack";
+ int attempts = 16;
+
+ // Establish the placeholder first, so every racing request takes the "attach" path.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateChangeSet")
+ .formParam("StackName", stackName)
+ .formParam("ChangeSetName", "seed")
+ .formParam("ChangeSetType", "CREATE")
+ .formParam("TemplateBody", template)
+ .when().post("/").then().statusCode(200);
+
+ CountDownLatch ready = new CountDownLatch(attempts);
+ CountDownLatch go = new CountDownLatch(1);
+ AtomicInteger accepted = new AtomicInteger();
+ ExecutorService pool = Executors.newFixedThreadPool(attempts);
+ try {
+ for (int i = 0; i < attempts; i++) {
+ String changeSetName = "parallel-" + i;
+ pool.submit(() -> {
+ ready.countDown();
+ try {
+ go.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return;
+ }
+ String body = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateChangeSet")
+ .formParam("StackName", stackName)
+ .formParam("ChangeSetName", changeSetName)
+ .formParam("ChangeSetType", "CREATE")
+ .formParam("TemplateBody", template)
+ .when().post("/").then().extract().asString();
+ if (body.contains("<StackId>")) {
+ accepted.incrementAndGet();
+ }
+ });
+ }
+ assertTrue(ready.await(10, TimeUnit.SECONDS), "workers failed to line up in time");
+ go.countDown();
+ } finally {
+ pool.shutdown();
+ assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "requests did not finish in time");
+ }
+
+ assertEquals(attempts, accepted.get(), "every CREATE change set on the placeholder should be accepted");
+
+ // Every accepted change set must still be readable - an acknowledged write that vanished
+ // from the map is exactly the failure this guards.
+ String listed = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ListChangeSets")
+ .formParam("StackName", stackName)
+ .when().post("/").then().statusCode(200).extract().asString();
+
+ for (int i = 0; i < attempts; i++) {
+ assertTrue(listed.contains("parallel-" + i), "change set parallel-" + i + " was lost");
+ }
+ assertTrue(listed.contains("seed"), "the seed change set was lost");
+ }
+
+ @Test
+ void createStack_onReviewInProgressStack_throwsAlreadyExistsException() {
+ // CreateStack does not get the REVIEW_IN_PROGRESS exemption, and must not: every stack it
+ // creates is REVIEW_IN_PROGRESS for the window between newStack() and the execute that
+ // immediately follows, so exempting the status on this path would let two racing
+ // CreateStack requests share one stack and both provision the template - the very race
+ // createStack_concurrentRequestsForUnusedName_exactlyOneSucceeds covers. LocalStack draws
+ // the same line: its create_stack conflicts on any status but DELETE_COMPLETE, while only
+ // its create_change_set exempts REVIEW_IN_PROGRESS.
+ String template = """
+ {
+ "Resources": {
+ "MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2365-implicit-bus" } }
+ }
+ }
+ """;
+ String stackName = "cfn-2365-implicit-stack";
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateChangeSet")
+ .formParam("StackName", stackName)
+ .formParam("ChangeSetName", "pending")
+ .formParam("ChangeSetType", "CREATE")
+ .formParam("TemplateBody", template)
+ .when().post("/").then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when().post("/")
+ .then().body(containsString("AlreadyExistsException"));
+ }
+
@Test
void createStack_apiGatewayRestApi_withEndpointConfiguration() {
String template = """