Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): make a stack's collections safe for concurrent requests (#4199)
Hector Venturafac87a6cf42b
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.javaindex c2ab571a4d..474193e8f5 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@@ -325,7 +325,7 @@ public class CloudFormationQueryHandler {try {List<Stack> stacks = cfnService.describeStacks(stackName, region);if (!stacks.isEmpty()) {- for (ChangeSet cs : stacks.get(0).getChangeSets().values()) {+ for (ChangeSet cs : stacks.get(0).changeSetsSnapshot().values()) {xml.start("member").elem("ChangeSetName", cs.getChangeSetName()).elem("ChangeSetId", cs.getChangeSetId())@@ -610,18 +610,19 @@ public class CloudFormationQueryHandler {}xml.end("Capabilities");xml.start("Parameters");- s.getParameters().forEach((k, v) ->+ s.parametersSnapshot().forEach((k, v) ->xml.start("member").elem("ParameterKey", k).elem("ParameterValue", v).end("member"));xml.end("Parameters");xml.start("Outputs");- s.getOutputs().forEach((k, v) -> {+ Map<String, String> outputExportNames = s.outputExportNamesSnapshot();+ s.outputsSnapshot().forEach((k, v) -> {xml.start("member").elem("OutputKey", k).elem("OutputValue", v);- String exportName = s.getOutputExportNames().get(k);+ String exportName = outputExportNames.get(k);if (exportName != null) {xml.elem("ExportName", exportName);}@@ -629,7 +630,7 @@ public class CloudFormationQueryHandler {});xml.end("Outputs");xml.start("Tags");- s.getTags().forEach((k, v) ->+ s.tagsSnapshot().forEach((k, v) ->xml.start("member").elem("Key", k).elem("Value", v)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 f9239c5a93..f9f6bdf1f7 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@@ -198,7 +198,7 @@ public class CloudFormationService implements ResourceProvider {*/public Map<String, String> currentParameters(String stackName, String region) {Stack stack = resolveStack(stackName, region);- return stack != null ? stack.getParameters() : Map.of();+ return stack != null ? stack.parametersSnapshot() : Map.of();}/**@@ -488,13 +488,11 @@ public class CloudFormationService implements ResourceProvider {? objectMapper.createObjectNode(): parseTemplate(stack.getTemplateBody()).path("Resources");- Map<String, String> oldParams = stack.getParameters() != null- ? stack.getParameters() : Map.of();+ Map<String, String> oldParams = stack.parametersSnapshot();// Prefer the SSM-resolved values captured by the last executeTemplate run; fall back to// the raw parameters for stacks persisted before resolvedParameters existed.- Map<String, String> oldResolvedParams = stack.getResolvedParameters() != null- && !stack.getResolvedParameters().isEmpty()- ? stack.getResolvedParameters() : oldParams;+ Map<String, String> resolvedSnapshot = stack.resolvedParametersSnapshot();+ Map<String, String> oldResolvedParams = resolvedSnapshot.isEmpty() ? oldParams : resolvedSnapshot;// A parameter omitted from the update falls back to the template's Default when// ExecuteChangeSet actually runs it, so the preview must resolve the same defaults or// it will under-report changes to resources that depend on that fallback value.@@ -538,7 +536,7 @@ public class CloudFormationService implements ResourceProvider {// ground truth execution uses - so no separate old-conditions evaluation is needed.Map<String, Boolean> newConditions = resolveConditions(newTemplate, newResolvedParams, null, region, regionResolver.getAccountId());- Set<String> deployedIds = stack.getResources().keySet();+ Set<String> deployedIds = stack.resourcesSnapshot().keySet();List<ResourceChange> changes = new ArrayList<>();newResources.fields().forEachRemaining(e -> {@@ -693,9 +691,11 @@ public class CloudFormationService implements ResourceProvider {cs.setExecutionStatus("EXECUTE_IN_PROGRESS");if (requireAvailable) {// CloudFormation deletes every other change set on the stack once one of them executes.- existing.getChangeSets().values().removeIf(other -> other != cs);+ synchronized (existing.getChangeSets()) {+ existing.getChangeSets().values().removeIf(other -> other != cs);+ }} else {- for (ChangeSet other : existing.getChangeSets().values()) {+ for (ChangeSet other : existing.changeSetsSnapshot().values()) {if (other != cs && "AVAILABLE".equals(other.getExecutionStatus())) {other.setExecutionStatus("OBSOLETE");}@@ -847,11 +847,11 @@ public class CloudFormationService implements ResourceProvider {private StackMutationSnapshot snapshot(Stack stack) {Map<ChangeSet, ChangeSetState> states = new IdentityHashMap<>();- for (ChangeSet changeSet : stack.getChangeSets().values()) {+ for (ChangeSet changeSet : stack.changeSetsSnapshot().values()) {states.put(changeSet, new ChangeSetState(changeSet.getStatus(), changeSet.getExecutionStatus()));}return new StackMutationSnapshot(stack.getStatus(), stack.getLastUpdatedTime(),- new ArrayList<>(stack.getEvents()), new LinkedHashMap<>(stack.getChangeSets()), states);+ stack.eventsSnapshot(), stack.changeSetsSnapshot(), states);}private void restore(Stack stack, StackMutationSnapshot snapshot) {@@ -1071,7 +1071,7 @@ public class CloudFormationService implements ResourceProvider {throw new AwsException("ValidationError","Stack with id " + stackName + " does not exist", 400);}- List<StackEvent> events = new ArrayList<>(stack.getEvents());+ List<StackEvent> events = stack.eventsSnapshot();Collections.reverse(events);return events;}@@ -1080,7 +1080,7 @@ public class CloudFormationService implements ResourceProvider {public List<StackResource> describeStackResources(String stackName, String region) {Stack stack = getStackOrThrow(stackName, region);- return new ArrayList<>(stack.getResources().values());+ return new ArrayList<>(stack.resourcesSnapshot().values());}// ── ListStacks ────────────────────────────────────────────────────────────@@ -1102,7 +1102,7 @@ public class CloudFormationService implements ResourceProvider {if (!accountId.equals(ownerAccount(stack)) || !region.equals(stack.getRegion())) {continue;}- for (var entry : stack.getExports().entrySet()) {+ for (var entry : stack.exportsSnapshot().entrySet()) {result.put(entry.getKey(), new ExportEntry(entry.getKey(), entry.getValue(), stack.getStackId()));}}@@ -1115,7 +1115,7 @@ public class CloudFormationService implements ResourceProvider {private void removeStackExports(Stack stack, String region) {String accountId = ownerAccount(stack);- for (String exportName : stack.getExports().keySet()) {+ for (String exportName : stack.exportsSnapshot().keySet()) {String logicalKey = exportKey(region, exportName);exports.remove(accountExportKey(accountId, logicalKey));exportBackend.deleteForAccount(accountId, logicalKey);@@ -1230,8 +1230,7 @@ public class CloudFormationService implements ResourceProvider {// Merge default parameter values from the template with caller-supplied paramsMap<String, String> givenParams = resolveDefaultParameters(template, params);- stack.getParameters().clear();- stack.getParameters().putAll(givenParams);+ stack.replaceParameters(givenParams);Map<String, String> resolvedParams = resolveSsmParameters(template, givenParams, region);stack.setResolvedParameters(new LinkedHashMap<>(resolvedParams));@@ -1248,7 +1247,7 @@ public class CloudFormationService implements ResourceProvider {Map<String, Map<String, String>> resourceAttrs = new LinkedHashMap<>();// First pass: collect existing physicalIds- for (var r : stack.getResources().values()) {+ for (var r : stack.resourcesSnapshot().values()) {if (r.getPhysicalId() != null) {physicalIds.put(r.getLogicalId(), r.getPhysicalId());resourceAttrs.put(r.getLogicalId(), r.getAttributes());@@ -1377,7 +1376,7 @@ public class CloudFormationService implements ResourceProvider {// Resolve outputs before mutating stack/global export state, so failed updates do not// leave stale or partially registered exports behind.- Map<String, String> oldExports = new LinkedHashMap<>(stack.getExports());+ Map<String, String> oldExports = stack.exportsSnapshot();Map<String, String> newOutputs = new LinkedHashMap<>();Map<String, String> newExports = new LinkedHashMap<>();Map<String, String> newOutputExportNames = new LinkedHashMap<>();@@ -1400,12 +1399,9 @@ public class CloudFormationService implements ResourceProvider {}removeStackExports(stack, region);- stack.getOutputs().clear();- stack.getOutputs().putAll(newOutputs);- stack.getExports().clear();- stack.getExports().putAll(newExports);- stack.getOutputExportNames().clear();- stack.getOutputExportNames().putAll(newOutputExportNames);+ stack.replaceOutputs(newOutputs);+ stack.replaceExports(newExports);+ stack.replaceOutputExportNames(newOutputExportNames);newExports.forEach((exportName, value) -> {String logicalKey = region + ":" + exportName;String exportKey = accountExportKey(accountId, logicalKey);@@ -1604,7 +1600,7 @@ public class CloudFormationService implements ResourceProvider {}private boolean hasReplacementUpdates(Stack stack) {- return stack.getResources().values().stream()+ return stack.resourcesSnapshot().values().stream().anyMatch(provisioner::hasReplacementUpdate);}@@ -1612,7 +1608,7 @@ public class CloudFormationService implements ResourceProvider {if (!resources.isObject()) {return false;}- for (StackResource resource : stack.getResources().values()) {+ for (StackResource resource : stack.resourcesSnapshot().values()) {JsonNode resDef = resources.get(resource.getLogicalId());if (resDef == null) {return true;@@ -1663,10 +1659,8 @@ public class CloudFormationService implements ResourceProvider {// successfully deployed values, even when resource rollback itself fails and the stack lands// in UPDATE_ROLLBACK_FAILED, so DescribeStacks and later change-set previews don't keep// serving the failed update's attempted values.- stack.getParameters().clear();- stack.getParameters().putAll(previousState.parameters());- stack.getResolvedParameters().clear();- stack.getResolvedParameters().putAll(previousState.resolvedParameters());+ stack.replaceParameters(previousState.parameters());+ stack.replaceResolvedParameters(previousState.resolvedParameters());if (rollbackFailures.isEmpty()) {stack.setTemplateBody(previousState.templateBody());// GetTemplate reads originalTemplateBody for TemplateStage=Original and templateBody@@ -1708,7 +1702,7 @@ public class CloudFormationService implements ResourceProvider {Map<String, StackResource> previousResources,Set<String> attemptedResourceIds,String region) {- List<StackResource> resources = new ArrayList<>(stack.getResources().values());+ List<StackResource> resources = new ArrayList<>(stack.resourcesSnapshot().values());Collections.reverse(resources);List<String> failures = new ArrayList<>();List<String> removedResources = new ArrayList<>();@@ -1777,7 +1771,7 @@ public class CloudFormationService implements ResourceProvider {private void restoreOutputAndExportState(Stack stack, String region, StackUpdateSnapshot previousState) {RuntimeException storageFailure = null;- for (String exportName : new ArrayList<>(stack.getExports().keySet())) {+ for (String exportName : stack.exportsSnapshot().keySet()) {String logicalKey = exportKey(region, exportName);String key = accountExportKey(ownerAccount(stack), logicalKey);exports.remove(key);@@ -1788,12 +1782,9 @@ public class CloudFormationService implements ResourceProvider {}}- stack.getOutputs().clear();- stack.getOutputs().putAll(previousState.outputs());- stack.getExports().clear();- stack.getExports().putAll(previousState.exports());- stack.getOutputExportNames().clear();- stack.getOutputExportNames().putAll(previousState.outputExportNames());+ stack.replaceOutputs(previousState.outputs());+ stack.replaceExports(previousState.exports());+ stack.replaceOutputExportNames(previousState.outputExportNames());for (Map.Entry<String, String> entry : previousState.exports().entrySet()) {String logicalKey = exportKey(region, entry.getKey());@@ -1823,12 +1814,12 @@ public class CloudFormationService implements ResourceProvider {return new StackUpdateSnapshot(stack.getTemplateBody(),stack.getOriginalTemplateBody(),- new LinkedHashMap<>(stack.getParameters()),- new LinkedHashMap<>(stack.getResolvedParameters()),- new LinkedHashMap<>(stack.getOutputs()),- new LinkedHashMap<>(stack.getExports()),- new LinkedHashMap<>(stack.getOutputExportNames()),- copyResources(stack.getResources()));+ stack.parametersSnapshot(),+ stack.resolvedParametersSnapshot(),+ stack.outputsSnapshot(),+ stack.exportsSnapshot(),+ stack.outputExportNamesSnapshot(),+ copyResources(stack.resourcesSnapshot()));}private Map<String, StackResource> copyResources(@@ -1870,7 +1861,7 @@ public class CloudFormationService implements ResourceProvider {/** Deletes every resource created in this execution, in reverse order. */private List<String> rollbackCreatedResources(Stack stack, String region) {- List<StackResource> resources = new ArrayList<>(stack.getResources().values());+ List<StackResource> resources = new ArrayList<>(stack.resourcesSnapshot().values());Collections.reverse(resources);List<String> failedResources = new ArrayList<>();for (StackResource resource : resources) {@@ -1926,7 +1917,7 @@ public class CloudFormationService implements ResourceProvider {}List<UpdateCleanupFailure> failures = new ArrayList<>();- List<StackResource> ordered = new ArrayList<>(stack.getResources().values());+ List<StackResource> ordered = new ArrayList<>(stack.resourcesSnapshot().values());Collections.reverse(ordered);for (StackResource resource : ordered) {JsonNode resDef = resources.get(resource.getLogicalId());@@ -1981,7 +1972,7 @@ public class CloudFormationService implements ResourceProvider {* cannot be read.*/private List<StackResource> resourcesInCreationOrder(Stack stack, String region) {- List<StackResource> ordered = new ArrayList<>(stack.getResources().values());+ List<StackResource> ordered = new ArrayList<>(stack.resourcesSnapshot().values());try {JsonNode template = parseTemplate(stack.getTemplateBody());JsonNode resources = template.path("Resources");@@ -1989,7 +1980,7 @@ public class CloudFormationService implements ResourceProvider {return ordered;}Map<String, Boolean> conditions = resolveConditions(- template, stack.getParameters(), stack, region, regionResolver.getAccountId());+ template, stack.parametersSnapshot(), stack, region, regionResolver.getAccountId());List<String> creationOrder = topologicalSort(resources, conditions);Map<String, Integer> rank = new HashMap<>();for (int i = 0; i < creationOrder.size(); i++) {@@ -2815,7 +2806,7 @@ public class CloudFormationService implements ResourceProvider {arn, "cloudformation:stack", "cloudformation",parsed.region(), parsed.accountId(),stack.getCreationTime() != null ? stack.getCreationTime() : Instant.now(),- stack.getTags() != null ? stack.getTags() : Map.of()));+ stack.tagsSnapshot()));}return resources;}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/Stack.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/Stack.javaindex 2dc4b71427..faf1e90fa0 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/Stack.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/Stack.java@@ -1,11 +1,30 @@package io.github.hectorvent.floci.services.cloudformation.model;+import com.fasterxml.jackson.annotation.JsonIgnore;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import com.fasterxml.jackson.annotation.JsonProperty;import io.quarkus.runtime.annotations.RegisterForReflection;import java.time.Instant;-import java.util.*;+import java.util.ArrayList;+import java.util.Collections;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.CopyOnWriteArrayList;+/**+ * A stack is shared state: it lives in the service's {@code stacks} map and is handed to every+ * request that names it, while a background executor provisions it. Its collections are therefore+ * thread-safe by construction, and every one keeps insertion order because the wire responses+ * (DescribeStacks outputs and parameters, DescribeStackEvents, ListChangeSets) reproduce it:+ * {@link Collections#synchronizedMap} over a {@link LinkedHashMap} for the maps and a+ * {@link CopyOnWriteArrayList} for the append-mostly event log. A single get, put, remove or add+ * on the live collection is safe; iterating one is not (the synchronized-map contract), so+ * callers that walk or copy a collection use the {@code *Snapshot()} accessors, which hold the+ * map's own monitor while copying. Jackson serializes through those snapshots too, so persisting+ * a stack mid-deploy never races the deploy.+ */@RegisterForReflection@JsonIgnoreProperties(ignoreUnknown = true)public class Stack {@@ -29,19 +48,19 @@ public class Stack {private String templateBody;private String originalTemplateBody;private List<String> capabilities = new ArrayList<>();- private Map<String, String> parameters = new LinkedHashMap<>();+ private Map<String, String> parameters = orderedMap();// Parameters after AWS::SSM::Parameter::Value<String> resolution, as last applied by// executeTemplate — used to detect drift in the live SSM value between deploys even when the// referencing parameter (name) is unchanged, so change-set previews agree with execution.- private Map<String, String> resolvedParameters = new LinkedHashMap<>();- private Map<String, String> outputs = new LinkedHashMap<>();- private Map<String, String> exports = new LinkedHashMap<>();+ private Map<String, String> resolvedParameters = orderedMap();+ private Map<String, String> outputs = orderedMap();+ private Map<String, String> exports = orderedMap();// Maps output key to its export name (when Export.Name is defined on an output)- private Map<String, String> outputExportNames = new LinkedHashMap<>();- private Map<String, StackResource> resources = new LinkedHashMap<>();- private List<StackEvent> events = new ArrayList<>();- private Map<String, ChangeSet> changeSets = new LinkedHashMap<>();- private Map<String, String> tags = new LinkedHashMap<>();+ private Map<String, String> outputExportNames = orderedMap();+ private Map<String, StackResource> resources = orderedMap();+ private List<StackEvent> events = new CopyOnWriteArrayList<>();+ private Map<String, ChangeSet> changeSets = orderedMap();+ private Map<String, String> tags = orderedMap();private boolean enableTerminationProtection = false;public String getStackId() { return stackId; }@@ -66,24 +85,101 @@ public class Stack {public void setOriginalTemplateBody(String originalTemplateBody) { this.originalTemplateBody = originalTemplateBody; }public List<String> getCapabilities() { return capabilities; }public void setCapabilities(List<String> capabilities) { this.capabilities = capabilities; }+ @JsonIgnorepublic Map<String, String> getParameters() { return parameters; }- public void setParameters(Map<String, String> parameters) { this.parameters = parameters; }+ @JsonProperty("parameters")+ public void setParameters(Map<String, String> parameters) { this.parameters = orderedMap(parameters); }+ @JsonProperty("parameters")+ public Map<String, String> parametersSnapshot() { return snapshot(parameters); }+ @JsonIgnorepublic Map<String, String> getResolvedParameters() { return resolvedParameters; }- public void setResolvedParameters(Map<String, String> resolvedParameters) { this.resolvedParameters = resolvedParameters; }+ @JsonProperty("resolvedParameters")+ public void setResolvedParameters(Map<String, String> resolvedParameters) { this.resolvedParameters = orderedMap(resolvedParameters); }+ @JsonProperty("resolvedParameters")+ public Map<String, String> resolvedParametersSnapshot() { return snapshot(resolvedParameters); }+ @JsonIgnorepublic Map<String, String> getOutputs() { return outputs; }- public void setOutputs(Map<String, String> outputs) { this.outputs = outputs; }+ @JsonProperty("outputs")+ public void setOutputs(Map<String, String> outputs) { this.outputs = orderedMap(outputs); }+ @JsonProperty("outputs")+ public Map<String, String> outputsSnapshot() { return snapshot(outputs); }+ @JsonIgnorepublic Map<String, String> getExports() { return exports; }- public void setExports(Map<String, String> exports) { this.exports = exports; }+ @JsonProperty("exports")+ public void setExports(Map<String, String> exports) { this.exports = orderedMap(exports); }+ @JsonProperty("exports")+ public Map<String, String> exportsSnapshot() { return snapshot(exports); }+ @JsonIgnorepublic Map<String, String> getOutputExportNames() { return outputExportNames; }- public void setOutputExportNames(Map<String, String> outputExportNames) { this.outputExportNames = outputExportNames; }+ @JsonProperty("outputExportNames")+ public void setOutputExportNames(Map<String, String> outputExportNames) { this.outputExportNames = orderedMap(outputExportNames); }+ @JsonProperty("outputExportNames")+ public Map<String, String> outputExportNamesSnapshot() { return snapshot(outputExportNames); }+ @JsonIgnorepublic Map<String, StackResource> getResources() { return resources; }- public void setResources(Map<String, StackResource> resources) { this.resources = resources; }+ @JsonProperty("resources")+ public void setResources(Map<String, StackResource> resources) { this.resources = orderedMap(resources); }+ @JsonProperty("resources")+ public Map<String, StackResource> resourcesSnapshot() { return snapshot(resources); }+ @JsonIgnorepublic List<StackEvent> getEvents() { return events; }- public void setEvents(List<StackEvent> events) { this.events = events; }+ @JsonProperty("events")+ public void setEvents(List<StackEvent> events) {+ this.events = new CopyOnWriteArrayList<>(events != null ? events : List.of());+ }+ /** The events in order; a copy-on-write list iterates a snapshot, so this is always consistent. */+ @JsonProperty("events")+ public List<StackEvent> eventsSnapshot() { return new ArrayList<>(events); }+ @JsonIgnorepublic Map<String, ChangeSet> getChangeSets() { return changeSets; }- public void setChangeSets(Map<String, ChangeSet> changeSets) { this.changeSets = changeSets; }+ @JsonProperty("changeSets")+ public void setChangeSets(Map<String, ChangeSet> changeSets) { this.changeSets = orderedMap(changeSets); }+ @JsonProperty("changeSets")+ public Map<String, ChangeSet> changeSetsSnapshot() { return snapshot(changeSets); }+ @JsonIgnorepublic Map<String, String> getTags() { return tags; }- public void setTags(Map<String, String> tags) { this.tags = tags; }+ @JsonProperty("tags")+ public void setTags(Map<String, String> tags) { this.tags = orderedMap(tags); }+ @JsonProperty("tags")+ public Map<String, String> tagsSnapshot() { return snapshot(tags); }++ /**+ * Replace a whole map as one step. {@code clear()} and {@code putAll()} are two separately+ * locked operations on a synchronized map, so a snapshot taken between them copies an empty+ * map: a DescribeStacks mid-update reporting no Outputs. Holding the map's monitor across the+ * pair makes the replace atomic to {@link #snapshot}, which takes the same monitor.+ */+ public void replaceParameters(Map<String, String> source) { replace(parameters, source); }+ public void replaceResolvedParameters(Map<String, String> source) { replace(resolvedParameters, source); }+ public void replaceOutputs(Map<String, String> source) { replace(outputs, source); }+ public void replaceExports(Map<String, String> source) { replace(exports, source); }+ public void replaceOutputExportNames(Map<String, String> source) { replace(outputExportNames, source); }++ private static <V> void replace(Map<String, V> target, Map<String, V> source) {+ synchronized (target) {+ target.clear();+ target.putAll(source);+ }+ }++ private static <V> Map<String, V> orderedMap() {+ return Collections.synchronizedMap(new LinkedHashMap<>());+ }++ private static <V> Map<String, V> orderedMap(Map<String, V> source) {+ Map<String, V> map = orderedMap();+ if (source != null) {+ map.putAll(source);+ }+ return map;+ }++ /** A consistent, insertion-ordered copy; the map's monitor guards the walk (synchronizedMap contract). */+ private static <V> Map<String, V> snapshot(Map<String, V> map) {+ synchronized (map) {+ return new LinkedHashMap<>(map);+ }+ }public boolean isEnableTerminationProtection() { return enableTerminationProtection; }public void setEnableTerminationProtection(boolean enableTerminationProtection) { this.enableTerminationProtection = enableTerminationProtection; }}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/model/StackConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/model/StackConcurrencyTest.javanew file mode 100644index 0000000000..6088e8a9a1--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/model/StackConcurrencyTest.java@@ -0,0 +1,195 @@+package io.github.hectorvent.floci.services.cloudformation.model;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;+import org.junit.jupiter.api.Test;++import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.concurrent.ConcurrentLinkedQueue;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.atomic.AtomicBoolean;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * A stack is read by request threads while the operation executor mutates it (#2419): events are+ * appended throughout a deploy while DescribeStackEvents copies them, resources are put and removed+ * while DescribeStackResources walks them. Plain collections lose writes, throw+ * {@code ConcurrentModificationException} or {@code ArrayIndexOutOfBoundsException} under that+ * load; the model's collections and snapshots must not.+ */+class StackConcurrencyTest {++ private static final int WRITERS = 4;+ private static final int WRITES_PER_WRITER = 5_000;++ @Test+ void concurrentWritesAndSnapshotsNeitherLoseWritesNorThrow() throws Exception {+ Stack stack = new Stack();+ CountDownLatch start = new CountDownLatch(1);+ AtomicBoolean stop = new AtomicBoolean(false);+ ConcurrentLinkedQueue<Throwable> failures = new ConcurrentLinkedQueue<>();+ List<Thread> threads = new ArrayList<>();++ for (int w = 0; w < WRITERS; w++) {+ int writer = w;+ threads.add(new Thread(() -> run(start, failures, () -> {+ for (int i = 0; i < WRITES_PER_WRITER; i++) {+ StackEvent event = new StackEvent();+ event.setEventId("w" + writer + "-" + i);+ stack.getEvents().add(event);+ StackResource resource = new StackResource();+ resource.setLogicalId("R" + writer + "-" + (i % 50));+ stack.getResources().put(resource.getLogicalId(), resource);+ if (i % 7 == 0) {+ stack.getResources().remove("R" + writer + "-" + ((i + 3) % 50));+ }+ stack.getOutputs().put("O" + (i % 20), "v" + i);+ ChangeSet changeSet = new ChangeSet();+ changeSet.setChangeSetName("cs" + (i % 10));+ stack.getChangeSets().put(changeSet.getChangeSetName(), changeSet);+ }+ })));+ }+ for (int r = 0; r < 3; r++) {+ threads.add(new Thread(() -> run(start, failures, () -> {+ while (!stop.get()) {+ stack.eventsSnapshot().size();+ stack.resourcesSnapshot().values().forEach(StackResource::getLogicalId);+ stack.outputsSnapshot().forEach((k, v) -> k.length());+ stack.changeSetsSnapshot().size();+ }+ })));+ }++ threads.forEach(Thread::start);+ start.countDown();+ for (int w = 0; w < WRITERS; w++) {+ threads.get(w).join();+ }+ stop.set(true);+ for (Thread reader : threads.subList(WRITERS, threads.size())) {+ reader.join();+ }++ assertTrue(failures.isEmpty(), "concurrent access failed: " + failures);+ assertEquals(WRITERS * WRITES_PER_WRITER, stack.eventsSnapshot().size(), "an appended event was lost");+ assertEquals(20, stack.outputsSnapshot().size());+ assertEquals(10, stack.changeSetsSnapshot().size());+ }++ /**+ * A replace is one step to a reader: a snapshot taken while the outputs are being replaced+ * holds either the old set or the new one, never the emptied map in between (a DescribeStacks+ * reporting no Outputs mid-update).+ */+ @Test+ void replaceIsNeverObservedHalfApplied() throws Exception {+ Stack stack = new Stack();+ Map<String, String> full = new LinkedHashMap<>();+ for (int i = 0; i < 20; i++) {+ full.put("O" + i, "v" + i);+ }+ stack.replaceOutputs(full);+ CountDownLatch start = new CountDownLatch(1);+ AtomicBoolean stop = new AtomicBoolean(false);+ ConcurrentLinkedQueue<Throwable> failures = new ConcurrentLinkedQueue<>();+ Thread writer = new Thread(() -> run(start, failures, () -> {+ for (int i = 0; i < 20_000; i++) {+ stack.replaceOutputs(full);+ }+ }));+ List<Thread> readers = new ArrayList<>();+ for (int r = 0; r < 3; r++) {+ readers.add(new Thread(() -> run(start, failures, () -> {+ while (!stop.get()) {+ int size = stack.outputsSnapshot().size();+ if (size != 20) {+ throw new AssertionError("snapshot saw a half-applied replace: " + size + " outputs");+ }+ }+ })));+ }+ writer.start();+ readers.forEach(Thread::start);+ start.countDown();+ writer.join();+ stop.set(true);+ for (Thread reader : readers) {+ reader.join();+ }++ assertTrue(failures.isEmpty(), "concurrent replace was observed half-applied: " + failures);+ }++ /** Insertion order is what the wire responses reproduce, so the safe collections must keep it. */+ @Test+ void collectionsKeepInsertionOrder() {+ Stack stack = new Stack();+ for (int i = 9; i >= 0; i--) {+ stack.getOutputs().put("O" + i, "v" + i);+ }+ assertEquals(List.of("O9", "O8", "O7", "O6", "O5", "O4", "O3", "O2", "O1", "O0"),+ new ArrayList<>(stack.outputsSnapshot().keySet()));+ stack.setOutputs(Map.of("only", "one"));+ assertEquals(List.of("only"), new ArrayList<>(stack.outputsSnapshot().keySet()));+ }++ /** The persisted shape is unchanged: the same property names, serialized from a consistent snapshot. */+ @Test+ void jacksonRoundTripKeepsTheStoredShape() throws Exception {+ ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());+ Stack stack = new Stack();+ stack.setStackName("s");+ StackEvent event = new StackEvent();+ event.setEventId("e1");+ stack.getEvents().add(event);+ StackResource resource = new StackResource();+ resource.setLogicalId("Bucket");+ stack.getResources().put("Bucket", resource);+ stack.getOutputs().put("Name", "value");+ stack.getOutputExportNames().put("Name", "exp");+ stack.getExports().put("exp", "value");+ stack.getParameters().put("P", "1");+ stack.getResolvedParameters().put("P", "1");+ stack.getTags().put("k", "v");+ ChangeSet changeSet = new ChangeSet();+ changeSet.setChangeSetName("cs");+ stack.getChangeSets().put("cs", changeSet);++ JsonNode json = mapper.readTree(mapper.writeValueAsString(stack));+ Set<String> expected = Set.of("parameters", "resolvedParameters", "outputs", "exports",+ "outputExportNames", "resources", "events", "changeSets", "tags");+ for (String field : expected) {+ assertTrue(json.has(field), "persisted stack lacks " + field + ": " + json.fieldNames());+ }+ assertTrue(json.get("events").isArray() && json.get("events").size() == 1);+ assertTrue(json.get("resources").isObject() && json.get("resources").has("Bucket"));++ Stack restored = mapper.readValue(mapper.writeValueAsString(stack), Stack.class);+ assertEquals("e1", restored.getEvents().get(0).getEventId());+ assertEquals("Bucket", restored.getResources().get("Bucket").getLogicalId());+ assertEquals("value", restored.getOutputs().get("Name"));+ assertEquals("exp", restored.getOutputExportNames().get("Name"));+ assertEquals("cs", restored.getChangeSets().get("cs").getChangeSetName());+ assertEquals("v", restored.getTags().get("k"));+ // A restored stack is thread-safe too, not a plain LinkedHashMap handed back by Jackson.+ assertEquals("java.util.Collections$SynchronizedMap", restored.getResources().getClass().getName());+ assertEquals("java.util.concurrent.CopyOnWriteArrayList", restored.getEvents().getClass().getName());+ }++ private static void run(CountDownLatch start, ConcurrentLinkedQueue<Throwable> failures, Runnable body) {+ try {+ start.await();+ body.run();+ } catch (Throwable t) {+ failures.add(t);+ }+ }+}