Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): reject resources that depend on each other in a cycle (#5208)
Niels Kootstra13738f89de10
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCircularDependencyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCircularDependencyTest.javanew file mode 100644index 0000000000..d64e8b7442--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCircularDependencyTest.java@@ -0,0 +1,80 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.cloudformation.CloudFormationClient;+import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;+import software.amazon.awssdk.services.sqs.SqsClient;+import software.amazon.awssdk.services.sqs.model.QueueDoesNotExistException;++import java.util.List;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++@DisplayName("CloudFormation CreateStack with a dependency cycle")+class CloudFormationCircularDependencyTest {++ private static CloudFormationClient cfn;+ private static SqsClient sqs;+ private String stackName;++ @BeforeAll+ static void clients() {+ cfn = TestFixtures.cloudFormationClient();+ sqs = TestFixtures.sqsClient();+ }++ @BeforeEach+ void setup() {+ stackName = TestFixtures.uniqueName("compat-cfn-cycle");+ }++ @AfterEach+ void cleanup() {+ try {+ cfn.deleteStack(r -> r.stackName(stackName));+ } catch (CloudFormationException ignored) {+ // The stack is never created; this only covers the rejection regressing.+ }+ }++ @AfterAll+ static void closeClients() {+ cfn.close();+ sqs.close();+ }++ @Test+ @DisplayName("rejects the template, names the cycle and creates nothing")+ void rejectsCycleBeforeCreatingResources() {+ String template = """+ {"Resources":{+ "Downstream":{"Type":"AWS::SQS::Queue","DependsOn":"FirstQueue",+ "Properties":{"QueueName":"%1$s-downstream"}},+ "FirstQueue":{"Type":"AWS::SQS::Queue","DependsOn":"SecondQueue",+ "Properties":{"QueueName":"%1$s-first"}},+ "SecondQueue":{"Type":"AWS::SQS::Queue","DependsOn":"FirstQueue",+ "Properties":{"QueueName":"%1$s-second"}}}}+ """.formatted(stackName);++ assertThatThrownBy(() -> cfn.createStack(r -> r.stackName(stackName).templateBody(template)))+ .isInstanceOfSatisfying(CloudFormationException.class, e -> {+ assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationError");+ assertThat(e.awsErrorDetails().errorMessage())+ .contains("Circular dependency between resources", "FirstQueue", "SecondQueue");+ });++ assertThatThrownBy(() -> cfn.describeStacks(r -> r.stackName(stackName)))+ .isInstanceOf(CloudFormationException.class)+ .hasMessageContaining("does not exist");+ for (String suffix : List.of("downstream", "first", "second")) {+ assertThatThrownBy(() -> sqs.getQueueUrl(r -> r.queueName(stackName + "-" + suffix)))+ .isInstanceOf(QueueDoesNotExistException.class);+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/AwsIncludeProcessor.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/AwsIncludeProcessor.javaindex e3ad432c5a..6315c66460 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/AwsIncludeProcessor.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/AwsIncludeProcessor.java@@ -131,7 +131,7 @@ class AwsIncludeProcessor {* count: AWS documents that a snippet may not itself use {@code AWS::Include}, not that it may* carry no other transform. Package-private: also used by {@code CloudFormationService} to* report {@code AWS::Include} in {@code GetTemplateSummary}'s {@code DeclaredTransforms} and to- * skip {@code validateConditionDependencies} for a template the merge has not run against yet.+ * skip {@code validateResourceDependencies} for a template the merge has not run against yet.*/boolean containsAwsInclude(JsonNode node) {if (node.isObject()) {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.javaindex bd0b6a1381..3e40e4e0db 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@@ -355,13 +355,13 @@ public class CloudFormationService implements ResourceProvider {// of throwing, so this failure is reported by the change set, not by a 400 on creation.String samTransformFailureReason = samTransformFailureReason(stackName, resolvedTemplate);- // Reject an unresolvable condition dependency graph up front, before any stack state is+ // Reject an unresolvable or circular dependency graph up front, before any stack state is// created, so CreateStack/UpdateStack fail synchronously the way real CloudFormation does.- // Unconditional: validateConditionDependencies already returns immediately for any+ // Unconditional: validateResourceDependencies already returns immediately for any// template declaring the SAM transform, whether or not that transform succeeded, so// gating this call on samTransformFailureReason == null duplicates that check for no// effect.- validateConditionDependencies(resolvedTemplate, parameters, region, accountId);+ validateResourceDependencies(resolvedTemplate, parameters, region, accountId);// 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@@ -498,7 +498,7 @@ public class CloudFormationService implements ResourceProvider {try {template = parseTemplate(templateBody);} catch (Exception e) {- // Template parse failures are reported by validateConditionDependencies and by+ // Template parse failures are reported by validateResourceDependencies and by// execution itself, with their own messages; not this transform-specific one.return null;}@@ -2326,7 +2326,9 @@ public class CloudFormationService implements ResourceProvider {}Map<String, Boolean> conditions = resolveConditions(template, stack.parametersSnapshot(), stack, region, regionResolver.getAccountId());- List<String> creationOrder = topologicalSort(resources, conditions);+ // A stack saved before circular templates were rejected may still have one; order it+ // by its dependencies anyway rather than giving up.+ List<String> creationOrder = creationOrder(resources, conditions).sorted();Map<String, Integer> rank = new HashMap<>();for (int i = 0; i < creationOrder.size(); i++) {rank.put(creationOrder.get(i), i);@@ -2506,16 +2508,17 @@ public class CloudFormationService implements ResourceProvider {/*** Fails a create/update before any stack state is mutated when a resource that will be created- * depends on a resource excluded by a false condition. Real CloudFormation rejects such a- * template synchronously ("Template format error: Unresolved resource dependencies [...]")- * rather than silently skipping the dependent, so mirror that instead of dropping the resource.+ * depends on a resource excluded by a false condition, or when resources depend on each other+ * in a cycle. Real CloudFormation rejects such a template synchronously ("Template format+ * error: Unresolved resource dependencies [...]" or "Circular dependency between resources:+ * [...]") rather than skipping the dependent or picking an arbitrary order, so mirror that.* Malformed or SAM templates are left for the execution path, which surfaces their own errors.* A template carrying an unexpanded {@code Fn::Transform}/{@code AWS::Include} is left for the* same reason: a {@code Conditions} section spliced in from a snippet is invisible here, since* the merge has not run yet, and treating it as absent would fail a template whose dependency* graph the execution path resolves correctly.*/- private void validateConditionDependencies(String templateBody, Map<String, String> params,+ private void validateResourceDependencies(String templateBody, Map<String, String> params,String region, String accountId) {JsonNode template;try {@@ -2537,23 +2540,8 @@ public class CloudFormationService implements ResourceProvider {Map<String, Boolean> conditions =resolveConditions(template, resolvedParams, null, region, accountId);- Set<String> allIds = new LinkedHashSet<>();- resources.fieldNames().forEachRemaining(allIds::add);- Set<String> activeIds = new LinkedHashSet<>();- Map<String, Set<String>> dependencies = new HashMap<>();- for (String logicalId : allIds) {- JsonNode resDef = resources.get(logicalId);- String condition = resDef.path("Condition").asText(null);- if (condition == null || conditions.getOrDefault(condition, false)) {- activeIds.add(logicalId);- }- dependencies.put(logicalId, collectResourceDependencies(resDef, allIds, conditions));- }-- Set<String> unresolved = unresolvedConditionDependencies(activeIds, allIds, dependencies);- if (!unresolved.isEmpty()) {- throw unresolvedDependenciesError(unresolved);- }+ // Throws the ValidationError for either case; the order itself is computed again on execution.+ topologicalSort(resources, conditions);}private boolean evaluateCondition(JsonNode expr, Map<String, String> params,@@ -3069,6 +3057,25 @@ public class CloudFormationService implements ResourceProvider {}private List<String> topologicalSort(JsonNode resources, Map<String, Boolean> conditions) {+ // A resource left unsorted is in a dependency cycle or depends on one, so no creation+ // order exists; AWS rejects such a template instead of creating it in an arbitrary order.+ CreationOrder order = creationOrder(resources, conditions);+ if (!order.circular().isEmpty()) {+ throw new AwsException("ValidationError",+ "Circular dependency between resources: [" + String.join(", ", order.circular()) + "]", 400);+ }+ return order.sorted();+ }++ /**+ * The template's resources, dependencies first, and those in a dependency cycle. Resources in or+ * depending on a cycle are still placed in {@code sorted}, each cycle after the cycles it depends+ * on, so every dependency outside a cycle keeps its order.+ */+ private record CreationOrder(List<String> sorted, Set<String> circular) {+ }++ private CreationOrder creationOrder(JsonNode resources, Map<String, Boolean> conditions) {Set<String> allIds = new LinkedHashSet<>();resources.fieldNames().forEachRemaining(allIds::add);@@ -3128,13 +3135,81 @@ public class CloudFormationService implements ResourceProvider {}}- for (String id : activeIds) {- if (!sorted.contains(id)) {- sorted.add(id);+ // Every resource left waits on another one left. Ordering their strongly connected+ // components dependencies first still respects every dependency outside a cycle; only the+ // components that are cycles themselves are circular.+ Set<String> circular = new LinkedHashSet<>();+ if (sorted.size() < activeIds.size()) {+ Set<String> placed = new HashSet<>(sorted);+ for (List<String> component : componentsDependenciesFirst(activeIds, placed, dependencies)) {+ sorted.addAll(component);+ String first = component.get(0);+ if (component.size() > 1 || dependencies.get(first).contains(first)) {+ circular.addAll(component);+ }}}+ return new CreationOrder(sorted, circular);+ }- return sorted;+ /**+ * The strongly connected components of the resources not yet placed, each after every component+ * it depends on: Tarjan's algorithm completes a component only once those are complete. The+ * search keeps its own stack so a long dependency chain cannot exhaust the thread's.+ */+ private static List<List<String>> componentsDependenciesFirst(Set<String> activeIds, Set<String> placed,+ Map<String, Set<String>> dependencies) {+ Map<String, Integer> index = new HashMap<>();+ Map<String, Integer> lowLink = new HashMap<>();+ Deque<String> open = new ArrayDeque<>();+ Set<String> onOpen = new HashSet<>();+ List<List<String>> components = new ArrayList<>();+ Deque<Map.Entry<String, Iterator<String>>> path = new ArrayDeque<>();+ for (String root : activeIds) {+ if (placed.contains(root) || index.containsKey(root)) {+ continue;+ }+ String next = root;+ while (next != null || !path.isEmpty()) {+ if (next != null) {+ index.put(next, index.size());+ lowLink.put(next, index.get(next));+ open.push(next);+ onOpen.add(next);+ path.push(Map.entry(next, dependencies.get(next).iterator()));+ next = null;+ }+ String id = path.peek().getKey();+ Iterator<String> deps = path.peek().getValue();+ if (deps.hasNext()) {+ String dep = deps.next();+ if (!dependencies.containsKey(dep) || placed.contains(dep)) {+ continue;+ }+ if (!index.containsKey(dep)) {+ next = dep;+ } else if (onOpen.contains(dep)) {+ lowLink.merge(id, index.get(dep), Math::min);+ }+ continue;+ }+ path.pop();+ if (!path.isEmpty()) {+ lowLink.merge(path.peek().getKey(), lowLink.get(id), Math::min);+ }+ if (lowLink.get(id).equals(index.get(id))) {+ List<String> component = new ArrayList<>();+ String member;+ do {+ member = open.pop();+ onOpen.remove(member);+ component.add(member);+ } while (!member.equals(id));+ components.add(component);+ }+ }+ }+ return components;}private static final Pattern SUB_VAR_PATTERN = Pattern.compile("\\$\\{([^}]+)}");diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/AwsIncludeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/AwsIncludeIntegrationTest.javaindex 201dcc0749..db62a64e59 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/AwsIncludeIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/AwsIncludeIntegrationTest.java@@ -598,7 +598,7 @@ class AwsIncludeIntegrationTest {@Testvoid conditionsFromTheIncludedSnippetReachProvisioningInsteadOfBeingRejected() {- // validateConditionDependencies used to preflight the RAW, unmerged body: a Conditions+ // validateResourceDependencies used to preflight the RAW, unmerged body: a Conditions// section spliced in from a snippet was invisible there, so a resource conditioned on it// defaulted to excluded and a dependent resource failed CreateStack synchronously with a// spurious "Unresolved resource dependencies" error, even though the merge that runs laterdiff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCircularDependencyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCircularDependencyIntegrationTest.javanew file mode 100644index 0000000000..4fbb1be45c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCircularDependencyIntegrationTest.java@@ -0,0 +1,121 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.not;++@QuarkusTest+class CloudFormationCircularDependencyIntegrationTest {++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void createStack_rejectsResourcesThatDependOnEachOther() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "cfn-cycle-" + suffix;+ String firstQueueName = "cycle-first-" + suffix;+ String secondQueueName = "cycle-second-" + suffix;++ String template = """+ {+ "Resources": {+ "FirstQueue": {+ "Type": "AWS::SQS::Queue",+ "DependsOn": "SecondQueue",+ "Properties": { "QueueName": "%s" }+ },+ "SecondQueue": {+ "Type": "AWS::SQS::Queue",+ "DependsOn": "FirstQueue",+ "Properties": { "QueueName": "%s" }+ }+ }+ }+ """.formatted(firstQueueName, secondQueueName);++ try {+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))+ .body("ErrorResponse.Error.Message", containsString("Circular dependency between resources"))+ .body("ErrorResponse.Error.Message", containsString("FirstQueue"))+ .body("ErrorResponse.Error.Message", containsString("SecondQueue"));++ assertQueueAbsent(firstQueueName);+ assertQueueAbsent(secondQueueName);+ } finally {+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteStack")+ .formParam("StackName", stackName)+ .post("/");+ }+ }++ @Test+ void createStack_namesOnlyTheResourcesInTheCycle() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "cfn-cycle-names-" + suffix;++ // Downstream depends on the cycle but is not part of it.+ String template = """+ {+ "Resources": {+ "Downstream": { "Type": "AWS::SQS::Queue", "DependsOn": "FirstQueue" },+ "FirstQueue": { "Type": "AWS::SQS::Queue", "DependsOn": "SecondQueue" },+ "SecondQueue": { "Type": "AWS::SQS::Queue", "DependsOn": "FirstQueue" }+ }+ }+ """;++ try {+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))+ .body("ErrorResponse.Error.Message", containsString("FirstQueue"))+ .body("ErrorResponse.Error.Message", containsString("SecondQueue"))+ .body("ErrorResponse.Error.Message", not(containsString("Downstream")));+ } finally {+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteStack")+ .formParam("StackName", stackName)+ .post("/");+ }+ }++ private static void assertQueueAbsent(String queueName) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "GetQueueUrl")+ .formParam("QueueName", queueName)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("AWS.SimpleQueueService.NonExistentQueue"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.javaindex 985a9c2d67..e1f71ac691 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.java@@ -17,11 +17,13 @@ import io.github.hectorvent.floci.services.s3.S3Service;import io.github.hectorvent.floci.services.ssm.SsmService;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;+import org.mockito.InOrder;import java.time.Clock;import java.util.List;import java.util.Map;import java.util.Set;+import java.util.concurrent.atomic.AtomicReference;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertNull;@@ -31,6 +33,7 @@ import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.RETURNS_DEEP_STUBS;import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.inOrder;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;@@ -194,6 +197,161 @@ class CloudFormationServiceRollbackTest {assertEquals(Set.of("create"), stack.getChangeSets().keySet());}+ @Test+ void deleteStack_savedWithCircularTemplate_stillDeletesDependentsFirst() {+ // A stack saved before circular templates were rejected: the queues depend on each other,+ // and the target group was added by a later update, so it sits after the listener using it.+ Stack stack = new Stack();+ stack.setStackName("delete-saved-circular-stack");+ stack.setStackId("stack-id");+ stack.setRegion(REGION);+ stack.setStatus("UPDATE_COMPLETE");+ stack.setTemplateBody("""+ {"Resources": {+ "FirstQueue": {"Type": "AWS::SQS::Queue", "DependsOn": "SecondQueue"},+ "SecondQueue": {"Type": "AWS::SQS::Queue", "DependsOn": "FirstQueue"},+ "TargetGroup": {"Type": "AWS::ElasticLoadBalancingV2::TargetGroup"},+ "Listener": {"Type": "AWS::ElasticLoadBalancingV2::Listener",+ "Properties": {"DefaultActions": [{"Type": "forward",+ "TargetGroupArn": {"Ref": "TargetGroup"}}]}}+ }}""");+ StackResource listener = resource("Listener", "listener-arn", "AWS::ElasticLoadBalancingV2::Listener",+ "CREATE_COMPLETE");+ StackResource firstQueue = resource("FirstQueue", "first-url", "AWS::SQS::Queue", "CREATE_COMPLETE");+ StackResource secondQueue = resource("SecondQueue", "second-url", "AWS::SQS::Queue", "CREATE_COMPLETE");+ StackResource targetGroup = resource("TargetGroup", "target-group-arn",+ "AWS::ElasticLoadBalancingV2::TargetGroup", "CREATE_COMPLETE");+ for (StackResource resource : new StackResource[] {listener, firstQueue, secondQueue, targetGroup}) {+ stack.getResources().put(resource.getLogicalId(), resource);+ }+ when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());++ service.deleteStackResources(stack, REGION, ACCOUNT);++ InOrder deletes = inOrder(provisioner);+ deletes.verify(provisioner).delete(listener, REGION);+ deletes.verify(provisioner).delete(targetGroup, REGION);+ assertEquals("DELETE_COMPLETE", stack.getStatus());+ }++ @Test+ void deleteStack_savedWithCircularTemplate_deletesResourcesDependingOnTheCycleInDependencyOrder() {+ // The target group depends on a queue in the cycle, so it cannot be ordered either; the+ // listener using it comes first in the template, yet must still be deleted first.+ Stack stack = new Stack();+ stack.setStackName("delete-saved-circular-chain");+ stack.setStackId("stack-id");+ stack.setRegion(REGION);+ stack.setStatus("UPDATE_COMPLETE");+ stack.setTemplateBody("""+ {"Resources": {+ "Listener": {"Type": "AWS::ElasticLoadBalancingV2::Listener",+ "Properties": {"DefaultActions": [{"Type": "forward",+ "TargetGroupArn": {"Ref": "TargetGroup"}}]}},+ "FirstQueue": {"Type": "AWS::SQS::Queue", "DependsOn": "SecondQueue"},+ "SecondQueue": {"Type": "AWS::SQS::Queue", "DependsOn": "FirstQueue"},+ "TargetGroup": {"Type": "AWS::ElasticLoadBalancingV2::TargetGroup", "DependsOn": "FirstQueue"}+ }}""");+ StackResource listener = resource("Listener", "listener-arn", "AWS::ElasticLoadBalancingV2::Listener",+ "CREATE_COMPLETE");+ StackResource firstQueue = resource("FirstQueue", "first-url", "AWS::SQS::Queue", "CREATE_COMPLETE");+ StackResource secondQueue = resource("SecondQueue", "second-url", "AWS::SQS::Queue", "CREATE_COMPLETE");+ StackResource targetGroup = resource("TargetGroup", "target-group-arn",+ "AWS::ElasticLoadBalancingV2::TargetGroup", "CREATE_COMPLETE");+ for (StackResource resource : new StackResource[] {listener, firstQueue, secondQueue, targetGroup}) {+ stack.getResources().put(resource.getLogicalId(), resource);+ }+ when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());++ service.deleteStackResources(stack, REGION, ACCOUNT);++ InOrder deletes = inOrder(provisioner);+ deletes.verify(provisioner).delete(listener, REGION);+ deletes.verify(provisioner).delete(targetGroup, REGION);+ deletes.verify(provisioner).delete(firstQueue, REGION);+ assertEquals("DELETE_COMPLETE", stack.getStatus());+ }++ @Test+ void deleteStack_savedWithLinkedCircularTemplates_deletesTheDependentCycleFirst() {+ // Two cycles, the consumer's cycle also depending on the queues' cycle: the consumer must+ // be deleted while the queues it uses still exist.+ Stack stack = new Stack();+ stack.setStackName("delete-saved-linked-cycles");+ stack.setStackId("stack-id");+ stack.setRegion(REGION);+ stack.setStatus("UPDATE_COMPLETE");+ stack.setTemplateBody("""+ {"Resources": {+ "Consumer": {"Type": "AWS::SQS::Queue", "DependsOn": ["Partner", "FirstQueue"]},+ "Partner": {"Type": "AWS::SQS::Queue", "DependsOn": "Consumer"},+ "FirstQueue": {"Type": "AWS::SQS::Queue", "DependsOn": "SecondQueue"},+ "SecondQueue": {"Type": "AWS::SQS::Queue", "DependsOn": "FirstQueue"}+ }}""");+ StackResource consumer = resource("Consumer", "consumer-url", "AWS::SQS::Queue", "CREATE_COMPLETE");+ StackResource partner = resource("Partner", "partner-url", "AWS::SQS::Queue", "CREATE_COMPLETE");+ StackResource firstQueue = resource("FirstQueue", "first-url", "AWS::SQS::Queue", "CREATE_COMPLETE");+ StackResource secondQueue = resource("SecondQueue", "second-url", "AWS::SQS::Queue", "CREATE_COMPLETE");+ for (StackResource resource : new StackResource[] {consumer, partner, firstQueue, secondQueue}) {+ stack.getResources().put(resource.getLogicalId(), resource);+ }+ when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());++ service.deleteStackResources(stack, REGION, ACCOUNT);++ InOrder deletes = inOrder(provisioner);+ deletes.verify(provisioner).delete(consumer, REGION);+ deletes.verify(provisioner).delete(firstQueue, REGION);+ assertEquals("DELETE_COMPLETE", stack.getStatus());+ }++ @Test+ void deleteStack_savedWithLongChainIntoCycle_deletesWithoutExhaustingTheThreadStack() throws InterruptedException {+ // Each resource depends on the next and the last one on a cycle, so finding the cycle has+ // to follow the whole chain; a small thread stack makes a recursive search overflow.+ int chainLength = 5_000;+ StringBuilder resources = new StringBuilder();+ Stack stack = new Stack();+ stack.setStackName("delete-saved-long-chain");+ stack.setStackId("stack-id");+ stack.setRegion(REGION);+ stack.setStatus("UPDATE_COMPLETE");+ StackResource[] chain = new StackResource[chainLength];+ for (int i = 0; i < chainLength; i++) {+ String next = i + 1 < chainLength ? "Link" + (i + 1) : "FirstQueue";+ resources.append("\"Link").append(i).append("\": {\"Type\": \"AWS::SQS::Queue\", \"DependsOn\": \"")+ .append(next).append("\"},");+ chain[i] = resource("Link" + i, "link-" + i, "AWS::SQS::Queue", "CREATE_COMPLETE");+ stack.getResources().put(chain[i].getLogicalId(), chain[i]);+ }+ stack.setTemplateBody("{\"Resources\": {" + resources+ + "\"FirstQueue\": {\"Type\": \"AWS::SQS::Queue\", \"DependsOn\": \"SecondQueue\"},"+ + "\"SecondQueue\": {\"Type\": \"AWS::SQS::Queue\", \"DependsOn\": \"FirstQueue\"}}}");+ StackResource firstQueue = resource("FirstQueue", "first-url", "AWS::SQS::Queue", "CREATE_COMPLETE");+ StackResource secondQueue = resource("SecondQueue", "second-url", "AWS::SQS::Queue", "CREATE_COMPLETE");+ stack.getResources().put(firstQueue.getLogicalId(), firstQueue);+ stack.getResources().put(secondQueue.getLogicalId(), secondQueue);+ when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());++ AtomicReference<Throwable> failure = new AtomicReference<>();+ Thread deleter = new Thread(null, () -> {+ try {+ service.deleteStackResources(stack, REGION, ACCOUNT);+ } catch (Throwable t) {+ failure.set(t);+ }+ }, "small-stack-delete", 256 * 1024);+ deleter.start();+ deleter.join();++ assertNull(failure.get());+ assertEquals("DELETE_COMPLETE", stack.getStatus());+ InOrder deletes = inOrder(provisioner);+ deletes.verify(provisioner).delete(chain[0], REGION);+ deletes.verify(provisioner).delete(chain[chainLength - 1], REGION);+ deletes.verify(provisioner).delete(firstQueue, REGION);+ }+private static StackResource resource(String logicalId, String physicalId, String resourceType, String status) {StackResource resource = new StackResource();resource.setLogicalId(logicalId);