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 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 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 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.java index 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 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 oldParams = stack.getParameters() != null - ? stack.getParameters() : Map.of(); + Map 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 oldResolvedParams = stack.getResolvedParameters() != null - && !stack.getResolvedParameters().isEmpty() - ? stack.getResolvedParameters() : oldParams; + Map resolvedSnapshot = stack.resolvedParametersSnapshot(); + Map 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 newConditions = resolveConditions( newTemplate, newResolvedParams, null, region, regionResolver.getAccountId()); - Set deployedIds = stack.getResources().keySet(); + Set deployedIds = stack.resourcesSnapshot().keySet(); List 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 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 events = new ArrayList<>(stack.getEvents()); + List events = stack.eventsSnapshot(); Collections.reverse(events); return events; } @@ -1080,7 +1080,7 @@ public class CloudFormationService implements ResourceProvider { public List 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 params Map givenParams = resolveDefaultParameters(template, params); - stack.getParameters().clear(); - stack.getParameters().putAll(givenParams); + stack.replaceParameters(givenParams); Map resolvedParams = resolveSsmParameters(template, givenParams, region); stack.setResolvedParameters(new LinkedHashMap<>(resolvedParams)); @@ -1248,7 +1247,7 @@ public class CloudFormationService implements ResourceProvider { Map> 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 oldExports = new LinkedHashMap<>(stack.getExports()); + Map oldExports = stack.exportsSnapshot(); Map newOutputs = new LinkedHashMap<>(); Map newExports = new LinkedHashMap<>(); Map 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 previousResources, Set attemptedResourceIds, String region) { - List resources = new ArrayList<>(stack.getResources().values()); + List resources = new ArrayList<>(stack.resourcesSnapshot().values()); Collections.reverse(resources); List failures = new ArrayList<>(); List 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 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 copyResources( @@ -1870,7 +1861,7 @@ public class CloudFormationService implements ResourceProvider { /** Deletes every resource created in this execution, in reverse order. */ private List rollbackCreatedResources(Stack stack, String region) { - List resources = new ArrayList<>(stack.getResources().values()); + List resources = new ArrayList<>(stack.resourcesSnapshot().values()); Collections.reverse(resources); List failedResources = new ArrayList<>(); for (StackResource resource : resources) { @@ -1926,7 +1917,7 @@ public class CloudFormationService implements ResourceProvider { } List failures = new ArrayList<>(); - List ordered = new ArrayList<>(stack.getResources().values()); + List 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 resourcesInCreationOrder(Stack stack, String region) { - List ordered = new ArrayList<>(stack.getResources().values()); + List 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 conditions = resolveConditions( - template, stack.getParameters(), stack, region, regionResolver.getAccountId()); + template, stack.parametersSnapshot(), stack, region, regionResolver.getAccountId()); List creationOrder = topologicalSort(resources, conditions); Map 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.java index 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 capabilities = new ArrayList<>(); - private Map parameters = new LinkedHashMap<>(); + private Map parameters = orderedMap(); // Parameters after AWS::SSM::Parameter::Value 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 resolvedParameters = new LinkedHashMap<>(); - private Map outputs = new LinkedHashMap<>(); - private Map exports = new LinkedHashMap<>(); + private Map resolvedParameters = orderedMap(); + private Map outputs = orderedMap(); + private Map exports = orderedMap(); // Maps output key to its export name (when Export.Name is defined on an output) - private Map outputExportNames = new LinkedHashMap<>(); - private Map resources = new LinkedHashMap<>(); - private List events = new ArrayList<>(); - private Map changeSets = new LinkedHashMap<>(); - private Map tags = new LinkedHashMap<>(); + private Map outputExportNames = orderedMap(); + private Map resources = orderedMap(); + private List events = new CopyOnWriteArrayList<>(); + private Map changeSets = orderedMap(); + private Map 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 getCapabilities() { return capabilities; } public void setCapabilities(List capabilities) { this.capabilities = capabilities; } + @JsonIgnore public Map getParameters() { return parameters; } - public void setParameters(Map parameters) { this.parameters = parameters; } + @JsonProperty("parameters") + public void setParameters(Map parameters) { this.parameters = orderedMap(parameters); } + @JsonProperty("parameters") + public Map parametersSnapshot() { return snapshot(parameters); } + @JsonIgnore public Map getResolvedParameters() { return resolvedParameters; } - public void setResolvedParameters(Map resolvedParameters) { this.resolvedParameters = resolvedParameters; } + @JsonProperty("resolvedParameters") + public void setResolvedParameters(Map resolvedParameters) { this.resolvedParameters = orderedMap(resolvedParameters); } + @JsonProperty("resolvedParameters") + public Map resolvedParametersSnapshot() { return snapshot(resolvedParameters); } + @JsonIgnore public Map getOutputs() { return outputs; } - public void setOutputs(Map outputs) { this.outputs = outputs; } + @JsonProperty("outputs") + public void setOutputs(Map outputs) { this.outputs = orderedMap(outputs); } + @JsonProperty("outputs") + public Map outputsSnapshot() { return snapshot(outputs); } + @JsonIgnore public Map getExports() { return exports; } - public void setExports(Map exports) { this.exports = exports; } + @JsonProperty("exports") + public void setExports(Map exports) { this.exports = orderedMap(exports); } + @JsonProperty("exports") + public Map exportsSnapshot() { return snapshot(exports); } + @JsonIgnore public Map getOutputExportNames() { return outputExportNames; } - public void setOutputExportNames(Map outputExportNames) { this.outputExportNames = outputExportNames; } + @JsonProperty("outputExportNames") + public void setOutputExportNames(Map outputExportNames) { this.outputExportNames = orderedMap(outputExportNames); } + @JsonProperty("outputExportNames") + public Map outputExportNamesSnapshot() { return snapshot(outputExportNames); } + @JsonIgnore public Map getResources() { return resources; } - public void setResources(Map resources) { this.resources = resources; } + @JsonProperty("resources") + public void setResources(Map resources) { this.resources = orderedMap(resources); } + @JsonProperty("resources") + public Map resourcesSnapshot() { return snapshot(resources); } + @JsonIgnore public List getEvents() { return events; } - public void setEvents(List events) { this.events = events; } + @JsonProperty("events") + public void setEvents(List 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 eventsSnapshot() { return new ArrayList<>(events); } + @JsonIgnore public Map getChangeSets() { return changeSets; } - public void setChangeSets(Map changeSets) { this.changeSets = changeSets; } + @JsonProperty("changeSets") + public void setChangeSets(Map changeSets) { this.changeSets = orderedMap(changeSets); } + @JsonProperty("changeSets") + public Map changeSetsSnapshot() { return snapshot(changeSets); } + @JsonIgnore public Map getTags() { return tags; } - public void setTags(Map tags) { this.tags = tags; } + @JsonProperty("tags") + public void setTags(Map tags) { this.tags = orderedMap(tags); } + @JsonProperty("tags") + public Map 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 source) { replace(parameters, source); } + public void replaceResolvedParameters(Map source) { replace(resolvedParameters, source); } + public void replaceOutputs(Map source) { replace(outputs, source); } + public void replaceExports(Map source) { replace(exports, source); } + public void replaceOutputExportNames(Map source) { replace(outputExportNames, source); } + + private static void replace(Map target, Map source) { + synchronized (target) { + target.clear(); + target.putAll(source); + } + } + + private static Map orderedMap() { + return Collections.synchronizedMap(new LinkedHashMap<>()); + } + + private static Map orderedMap(Map source) { + Map 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 Map snapshot(Map 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.java new file mode 100644 index 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 failures = new ConcurrentLinkedQueue<>(); + List 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 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 failures = new ConcurrentLinkedQueue<>(); + Thread writer = new Thread(() -> run(start, failures, () -> { + for (int i = 0; i < 20_000; i++) { + stack.replaceOutputs(full); + } + })); + List 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 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 failures, Runnable body) { + try { + start.await(); + body.run(); + } catch (Throwable t) { + failures.add(t); + } + } +}