From 5876a37888deee48bb15e49b8e726b6d416f4825 Mon Sep 17 00:00:00 2001 From: Oleksandr Nikolaichuk <57410473+Sekator778@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:20:30 +0300 Subject: [PATCH] refactor(cloudformation): tell each provisioner what the update changed in its properties (#8087) --- .../cloudformation/CloudFormationService.java | 40 +- .../provisioners/CfnResourceDispatcher.java | 21 +- .../CognitoPoolScopedLifecycle.java | 3 +- .../provisioners/PropertyChanges.java | 142 +++++++ .../provisioners/ProvisionContext.java | 54 ++- .../SchedulerScheduleCfnProvisioner.java | 6 +- .../provisioners/SesCfnProvisioner.java | 3 +- .../CfnPropertyChangesIntegrationTest.java | 191 +++++++++ .../CloudFormationStackPolicyServiceTest.java | 2 +- .../provisioners/CarriedChanges.java | 44 ++ ...gnitoResourceServerCfnProvisionerTest.java | 14 + .../provisioners/PropertyChangesTest.java | 402 ++++++++++++++++++ .../provisioners/ProvisionContextTest.java | 129 ++++++ .../SchedulerScheduleCfnProvisionerTest.java | 31 ++ .../provisioners/SesCfnProvisionerTest.java | 18 + 15 files changed, 1069 insertions(+), 31 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/cloudformation/provisioners/PropertyChanges.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/CfnPropertyChangesIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/provisioners/CarriedChanges.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/provisioners/PropertyChangesTest.java diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java index f0c739d520..64d50e14d1 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java @@ -31,6 +31,7 @@ import io.floci.aws.services.cloudformation.model.TemplateSummary; import io.floci.aws.services.cloudformation.provisioners.CfnDynamicReferences; import io.floci.aws.services.cloudformation.provisioners.CfnResourceDispatcher; import io.floci.aws.services.cloudformation.provisioners.CfnRollback; +import io.floci.aws.services.cloudformation.provisioners.PropertyChanges; import io.floci.aws.services.cloudformation.provisioners.ProvisionContext; import io.floci.aws.services.cloudformation.provisioners.UpdateCleanupResult; import io.floci.aws.services.s3.S3Service; @@ -1004,6 +1005,17 @@ public class CloudFormationService implements ResourceProvider { * executed a template) report every resource with a truthy {@code Condition} as an Add. */ public List computeChangeSetChanges(ChangeSet cs, String region) { + return computeChangeSetChanges(cs, region, null); + } + + /** + * As above. When {@code comparedProperties} is given, it receives for each modified resource the + * {@code Properties} of the forms the diff compared, previous then current, so an update can tell + * which of a resource's properties changed. A resource diffed on its definitions as written, or + * modified only because it reads a replaced resource or a changed attribute, gets no entry. + */ + private List computeChangeSetChanges(ChangeSet cs, String region, + Map comparedProperties) { if ("FAILED".equals(cs.getStatus())) { // A SAM transform failure already recorded by createChangeSet (see // samTransformFailureReason): the change set carries 0 changes, matching real @@ -1156,6 +1168,11 @@ public class CloudFormationService implements ResourceProvider { if (replacement) { replacedResourceIds.add(logicalId); } + if (comparedProperties != null && compared[0] != null) { + comparedProperties.put(logicalId, new JsonNode[] { + compared[0].path(logicalId).path("Properties"), + compared[1].path(logicalId).path("Properties")}); + } changes.add(new ResourceChange("Modify", logicalId, resourcePhysicalId(stack, logicalId), resourceType, replacement ? "True" : "False")); @@ -2334,9 +2351,10 @@ public class CloudFormationService implements ResourceProvider { boolean updateCommitted = false; Set attemptedResourceIds = new LinkedHashSet<>(); try { + Map comparedProperties = new HashMap<>(); Set changedResourceIds = isCreate ? Set.of() - : changedResourceIds(stack, templateBody, params, region); + : changedResourceIds(stack, templateBody, params, region, comparedProperties); JsonNode previousResources = isCreate ? objectMapper.missingNode() : previousResources(stack, previousState, region, accountId); @@ -2487,12 +2505,19 @@ public class CloudFormationService implements ResourceProvider { JsonNode priorProps = type.equals(previousDefinition.path("Type").asText()) && previousDefinition.path("Properties").isObject() ? previousDefinition.path("Properties") : null; - resource = dispatcher.provision(logicalId, type, props.isMissingNode() ? null : props, + JsonNode provisionProps = props.isMissingNode() ? null : props; + JsonNode[] comparedForms = comparedProperties.get(logicalId); + PropertyChanges changes = PropertyChanges.between(type, + ProvisionContext.isUpdate(resource.getPhysicalId()), priorProps, + provisionProps, + comparedForms != null ? comparedForms[0] : null, + comparedForms != null ? comparedForms[1] : null); + resource = dispatcher.provision(logicalId, type, provisionProps, engine, region, accountId, stack.getStackName(), resource.getPhysicalId(), resource.getAttributes(), event -> addEvent(stack, logicalId, event.getPhysicalResourceId(), type, event.getResourceStatus(), event.getResourceStatusReason()), - priorProps); + priorProps, changes); } resource.setUpdateReplacePolicy( resDef.path("UpdateReplacePolicy").asText(null)); @@ -2756,8 +2781,13 @@ public class CloudFormationService implements ResourceProvider { } } + /** + * The ids of the resources an update adds or modifies. {@code comparedProperties} receives, for + * the modified ones the diff compared, the {@code Properties} of the compared forms, previous + * then current; see the change-set diff it comes from. + */ private Set changedResourceIds(Stack stack, String templateBody, Map params, - String region) { + String region, Map comparedProperties) { ChangeSet changeSet = new ChangeSet(); changeSet.setStackName(stack.getStackName()); changeSet.setStackId(stack.getStackId()); @@ -2766,7 +2796,7 @@ public class CloudFormationService implements ResourceProvider { changeSet.setParameters(params); Set changedResourceIds = new LinkedHashSet<>(); - for (ResourceChange change : computeChangeSetChanges(changeSet, region)) { + for (ResourceChange change : computeChangeSetChanges(changeSet, region, comparedProperties)) { if ("Add".equals(change.action()) || "Modify".equals(change.action())) { changedResourceIds.add(change.logicalResourceId()); } diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnResourceDispatcher.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnResourceDispatcher.java index f6ef6edc57..96154ce6b0 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnResourceDispatcher.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnResourceDispatcher.java @@ -90,15 +90,26 @@ public class CfnResourceDispatcher { existingPhysicalId, existingAttributes, event -> {}, null); } - /** - * {@code priorProperties} are the resource's properties in the previous template, unresolved, - * or null when there is none; see {@link ProvisionContext#previouslyDeclared(String)}. - */ public StackResource provision(String logicalId, String resourceType, JsonNode properties, CloudFormationTemplateEngine engine, String region, String accountId, String stackName, String existingPhysicalId, Map existingAttributes, Consumer progress, JsonNode priorProperties) { + return provision(logicalId, resourceType, properties, engine, region, accountId, stackName, + existingPhysicalId, existingAttributes, progress, priorProperties, null); + } + + /** + * {@code priorProperties} are the resource's properties in the previous template, unresolved, + * or null when there is none; see {@link ProvisionContext#previouslyDeclared(String)}. + * {@code changes} is what the engine found changed in them, or null when it made no statement; + * see {@link ProvisionContext#changes(String, JsonNode)}. + */ + public StackResource provision(String logicalId, String resourceType, JsonNode properties, + CloudFormationTemplateEngine engine, String region, String accountId, + String stackName, String existingPhysicalId, + Map existingAttributes, Consumer progress, + JsonNode priorProperties, PropertyChanges changes) { StackResource resource = new StackResource(); resource.setLogicalId(logicalId); resource.setResourceType(resourceType); @@ -110,7 +121,7 @@ public class CfnResourceDispatcher { if (owner != null) { owner.provision(resource, properties, new ProvisionContext(engine, region, accountId, stackName, existingPhysicalId, progress, - priorProperties)); + priorProperties, changes)); // A provisioner that migrated a stub without writing its own Arn would leave the // stub's, and the real resource would read as a stub on its next update. String arn = resource.getAttributes().get("Arn"); diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CognitoPoolScopedLifecycle.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CognitoPoolScopedLifecycle.java index 5ef843aa8c..4e06d21b82 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CognitoPoolScopedLifecycle.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CognitoPoolScopedLifecycle.java @@ -118,8 +118,7 @@ final class CognitoPoolScopedLifecycle { } String cleanupPrior = prior.stub() ? prior.physicalId() : prior.identity() == null ? null : encode(prior.identity()); - ProvisionContext cleanupContext = new ProvisionContext(ctx.engine(), ctx.region(), ctx.accountId(), - ctx.stackName(), cleanupPrior, ctx.progress(), ctx.priorProperties()); + ProvisionContext cleanupContext = ctx.withPriorPhysicalId(cleanupPrior); withProjection(resource, projected -> { ReplacementCleanup.record(projected, cleanupContext, attributesBefore); return null; diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/PropertyChanges.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/PropertyChanges.java new file mode 100644 index 0000000000..4c1db2401b --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/PropertyChanges.java @@ -0,0 +1,142 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.services.cloudformation.CfnCreateOnlyProperties; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +/** + * What an update did to each top-level property of one resource: added, changed, dropped or + * unchanged, and whether the registry marks it create-only. The engine states it once per + * resource so a provisioner reads it instead of deriving it from the two templates. + * + *

Declared-ness follows what the provisioner sees: a property whose {@code Fn::If} chose + * {@code AWS::NoValue} is not declared on that side. Only the choice between changed and + * unchanged can use the forms CloudFormation compares. + * + *

Names keep the previous template's field order for the ones it declared, then the rest in + * the order of the current properties, so {@link #dropped()} keeps the order callers saw before + * this type existed. + * + *

UNCHANGED means unchanged in the template. A property whose {@code Ref} or + * {@code Fn::GetAtt} reads a resource this update replaces still reads UNCHANGED, so UNCHANGED + * alone is no reason to skip a write. + */ +public record PropertyChanges(Map byName) { + + public enum Kind { ADDED, CHANGED, DROPPED, UNCHANGED } + + /** + * One property's fate. {@code prior} and {@code current} are the nodes as the previous and the + * current properties hold them, null on the side that does not declare the name. + */ + public record PropertyChange(String name, Kind kind, JsonNode prior, JsonNode current, + boolean createOnly) {} + + public PropertyChanges { + byName = byName == null + ? Map.of() + : Collections.unmodifiableMap(new LinkedHashMap<>(byName)); + } + + /** What the provisioner's own inputs say, values compared as written. */ + public static PropertyChanges between(String resourceType, boolean update, + JsonNode priorProperties, JsonNode properties) { + return between(resourceType, update, priorProperties, properties, null, null); + } + + /** + * The same, with changed against unchanged decided by the forms CloudFormation compares when + * both are given and hold the name, and by the values as written otherwise. + */ + public static PropertyChanges between(String resourceType, boolean update, + JsonNode priorProperties, JsonNode properties, + JsonNode comparedPrior, JsonNode comparedCurrent) { + Map changes = new LinkedHashMap<>(); + boolean currentIsObject = properties != null && properties.isObject(); + if (!update || priorProperties == null || !priorProperties.isObject()) { + if (currentIsObject) { + properties.fieldNames().forEachRemaining(name -> changes.put(name, + change(resourceType, name, Kind.ADDED, null, properties.get(name)))); + } + return new PropertyChanges(changes); + } + priorProperties.fieldNames().forEachRemaining(name -> { + JsonNode before = priorProperties.get(name); + if (before.isNull()) { + return; + } + if (currentIsObject && properties.has(name)) { + JsonNode now = properties.get(name); + Kind kind = unchanged(name, before, now, comparedPrior, comparedCurrent) + ? Kind.UNCHANGED : Kind.CHANGED; + changes.put(name, change(resourceType, name, kind, before, now)); + } else { + changes.put(name, change(resourceType, name, Kind.DROPPED, before, null)); + } + }); + if (currentIsObject) { + properties.fieldNames().forEachRemaining(name -> { + if (!changes.containsKey(name)) { + changes.put(name, change(resourceType, name, Kind.ADDED, null, properties.get(name))); + } + }); + } + return new PropertyChanges(changes); + } + + private static PropertyChange change(String resourceType, String name, Kind kind, + JsonNode prior, JsonNode current) { + boolean createOnly = resourceType != null + && CfnCreateOnlyProperties.isCreateOnly(resourceType, name); + return new PropertyChange(name, kind, prior, current, createOnly); + } + + private static boolean unchanged(String name, JsonNode before, JsonNode now, + JsonNode comparedPrior, JsonNode comparedCurrent) { + if (comparedPrior != null && comparedCurrent != null) { + JsonNode comparedBefore = comparedPrior.path(name); + JsonNode comparedNow = comparedCurrent.path(name); + if (!comparedBefore.isMissingNode() && !comparedNow.isMissingNode()) { + return comparedBefore.equals(comparedNow); + } + } + return before.equals(now); + } + + /** The kind of {@code name}, or null when it is in neither template. */ + public Kind kindOf(String name) { + PropertyChange found = byName.get(name); + return found == null ? null : found.kind(); + } + + public Set added() { + return names(Kind.ADDED); + } + + public Set changed() { + return names(Kind.CHANGED); + } + + public Set dropped() { + return names(Kind.DROPPED); + } + + public Set unchanged() { + return names(Kind.UNCHANGED); + } + + private Set names(Kind kind) { + Set names = new LinkedHashSet<>(); + for (PropertyChange found : byName.values()) { + if (found.kind() == kind) { + names.add(found.name()); + } + } + return Collections.unmodifiableSet(names); + } +} diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java index 6383a8940f..bcdb06f6ec 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java @@ -7,7 +7,6 @@ import io.floci.aws.services.cloudformation.model.StackEvent; import java.util.ArrayList; import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -22,11 +21,29 @@ import java.util.function.Consumer; */ public record ProvisionContext(CloudFormationTemplateEngine engine, String region, String accountId, String stackName, String priorPhysicalId, - Consumer progress, JsonNode priorProperties) { + Consumer progress, JsonNode priorProperties, + PropertyChanges changes) { + + public ProvisionContext(CloudFormationTemplateEngine engine, String region, + String accountId, String stackName, String priorPhysicalId, + Consumer progress, JsonNode priorProperties) { + this(engine, region, accountId, stackName, priorPhysicalId, progress, priorProperties, null); + } public ProvisionContext(CloudFormationTemplateEngine engine, String region, String accountId, String stackName, String priorPhysicalId) { - this(engine, region, accountId, stackName, priorPhysicalId, event -> {}, null); + this(engine, region, accountId, stackName, priorPhysicalId, event -> {}, null, null); + } + + /** + * A copy of this context that differs only in the prior physical id. The engine's change list, + * the previous properties and the progress callback travel with it, so a provisioner that + * re-bases its context (after restoring a rollback snapshot, or for a cleanup record) does not + * drop the engine's statement of the update, and a component added later is kept too. + */ + public ProvisionContext withPriorPhysicalId(String priorPhysicalId) { + return new ProvisionContext(engine, region, accountId, stackName, priorPhysicalId, progress, + priorProperties, changes); } /** Intermediate resource events retain the stack pipeline's event IDs and metadata. */ @@ -58,6 +75,15 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio * this as "reuse the existing entity" must still reject or replace on createOnly properties. */ public boolean isUpdate() { + return isUpdate(priorPhysicalId); + } + + /** + * The one definition of "this call is an update": a non-blank prior physical id. The engine + * uses it to build the property changes it hands a provisioner, so the statement and + * {@link #isUpdate()} cannot disagree. + */ + public static boolean isUpdate(String priorPhysicalId) { return priorPhysicalId != null && !priorPhysicalId.isBlank(); } @@ -88,16 +114,20 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio * (a create-only property is a replacement question, not a clear). */ public Set droppedProperties(JsonNode props) { - Set dropped = new LinkedHashSet<>(); - if (!isUpdate() || priorProperties == null) { - return dropped; + return PropertyChanges.between(null, isUpdate(), priorProperties, props).dropped(); + } + + /** + * What this update did to each top-level property of the resource: the engine's own statement + * when it made one, which decides changed against unchanged by the forms CloudFormation + * compares, otherwise one derived from this context's previous properties and {@code props}. + * {@code resourceType} only tells which properties are create-only on the derived form. + */ + public PropertyChanges changes(String resourceType, JsonNode props) { + if (changes != null) { + return changes; } - priorProperties.fieldNames().forEachRemaining(name -> { - if (previouslyDeclared(name) && (props == null || !props.has(name))) { - dropped.add(name); - } - }); - return dropped; + return PropertyChanges.between(resourceType, isUpdate(), priorProperties, props); } /** diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/SchedulerScheduleCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/SchedulerScheduleCfnProvisioner.java index 001c1a48d6..9c567e8bfb 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/SchedulerScheduleCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/SchedulerScheduleCfnProvisioner.java @@ -63,8 +63,7 @@ public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner { if (ctx.isUpdate() && resource.getAttributes().containsKey(SNAPSHOT_ATTR)) { try { rollbackUpdate(resource); - ctx = new ProvisionContext(ctx.engine(), ctx.region(), ctx.accountId(), ctx.stackName(), - resource.getPhysicalId(), ctx.progress(), ctx.priorProperties()); + ctx = ctx.withPriorPhysicalId(resource.getPhysicalId()); resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR); resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR); } catch (RuntimeException failure) { @@ -137,8 +136,7 @@ public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner { priorIdentity = CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore) ? ctx.priorPhysicalId() : address(priorGroup, ctx.priorPhysicalId()); } - ProvisionContext cleanupContext = new ProvisionContext(ctx.engine(), ctx.region(), ctx.accountId(), - ctx.stackName(), priorIdentity, ctx.progress(), ctx.priorProperties()); + ProvisionContext cleanupContext = ctx.withPriorPhysicalId(priorIdentity); ReplacementCleanup.record(cleanupResource(resource), cleanupContext, attributesBefore); if (moveSnapshot != null) { moveSnapshot.put("destinationCreated", true); diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/SesCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/SesCfnProvisioner.java index 5bc686c4a2..b6614b6e67 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/SesCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/SesCfnProvisioner.java @@ -52,8 +52,7 @@ public class SesCfnProvisioner implements CfnResourceProvisioner { // it before either an in-place update or replacement can overwrite its snapshot. rollbackUpdate(resource); recoveredSnapshot = true; - ctx = new ProvisionContext(ctx.engine(), ctx.region(), ctx.accountId(), ctx.stackName(), - resource.getPhysicalId(), ctx.progress(), ctx.priorProperties()); + ctx = ctx.withPriorPhysicalId(resource.getPhysicalId()); } String identityName = desired.identity(); boolean updating = ctx.reusesPriorEntity(identityName); diff --git a/src/test/java/io/floci/aws/services/cloudformation/CfnPropertyChangesIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CfnPropertyChangesIntegrationTest.java new file mode 100644 index 0000000000..5146520f6d --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnPropertyChangesIntegrationTest.java @@ -0,0 +1,191 @@ +package io.floci.aws.services.cloudformation; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.cloudformation.provisioners.PropertyChanges; +import io.floci.aws.services.cloudformation.provisioners.PropertyChanges.Kind; +import io.floci.aws.services.cloudformation.provisioners.ProvisionContext; +import io.floci.aws.services.cloudformation.provisioners.SqsCfnProvisioner; +import io.floci.aws.testing.CfnStackWaits; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.mockito.InjectSpy; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import static io.floci.aws.testing.CfnRequests.cfn; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.verify; + +/** + * UpdateStack hands the provisioner the engine's statement of what happened to each top-level + * property: the {@link ProvisionContext} it receives carries a {@link PropertyChanges} whose kinds + * decide CHANGED against UNCHANGED by the forms CloudFormation compares, so a value rewritten + * without changing what it resolves to is UNCHANGED. + * + *

Observed by spying on the real SQS provisioner and capturing the context of each call. + */ +@QuarkusTest +class CfnPropertyChangesIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261110/us-east-1/cloudformation/aws4_request"; + + @InjectSpy + SqsCfnProvisioner sqsProvisioner; + + private static String template(String queueName, String properties) { + return """ + { + "Resources": { + "Queue": { + "Type": "AWS::SQS::Queue", + "Properties": {"QueueName": "%s", %s} + } + } + } + """.formatted(queueName, properties); + } + + @Test + void updateGivesTheProvisionerTheKindOfEveryProperty() { + String suffix = Long.toString(System.nanoTime(), 36); + String stack = "changes-" + suffix; + String queue = "changes-q-" + suffix; + + cfn("CreateStack", stack).header("Authorization", CFN_AUTH) + .formParam("TemplateBody", template(queue, """ + "VisibilityTimeout": "30", "DelaySeconds": "5", "MessageRetentionPeriod": "600" + """)) + .when().post("/").then().statusCode(200); + CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", CFN_AUTH); + + cfn("UpdateStack", stack).header("Authorization", CFN_AUTH) + .formParam("TemplateBody", template(queue, """ + "VisibilityTimeout": {"Fn::Join": ["", ["3", "0"]]}, + "MaximumMessageSize": "2048", "MessageRetentionPeriod": "1200" + """)) + .when().post("/").then().statusCode(200); + CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE", CFN_AUTH); + + ArgumentCaptor contexts = ArgumentCaptor.forClass(ProvisionContext.class); + verify(sqsProvisioner, atLeast(2)).provision(any(), any(), contexts.capture()); + List seen = contexts.getAllValues().stream() + .filter(ctx -> ctx.stackName().equals(stack)) + .toList(); + ProvisionContext created = seen.get(0); + ProvisionContext updated = seen.get(seen.size() - 1); + + PropertyChanges onCreate = created.changes(); + assertNotNull(onCreate, "the engine supplies the object on a create too"); + assertEquals(Set.of("QueueName", "VisibilityTimeout", "DelaySeconds", "MessageRetentionPeriod"), + onCreate.added()); + assertTrue(onCreate.dropped().isEmpty()); + + PropertyChanges changes = updated.changes(); + assertNotNull(changes, "the engine supplies the object on an update"); + assertEquals(Kind.UNCHANGED, changes.kindOf("QueueName")); + assertEquals(Kind.UNCHANGED, changes.kindOf("VisibilityTimeout"), + "written as an Fn::Join but resolving to the same value"); + assertEquals(Kind.CHANGED, changes.kindOf("MessageRetentionPeriod")); + assertEquals(Kind.DROPPED, changes.kindOf("DelaySeconds")); + assertEquals(Kind.ADDED, changes.kindOf("MaximumMessageSize")); + assertEquals(Set.of("DelaySeconds"), changes.dropped()); + assertEquals(Set.of("MaximumMessageSize"), changes.added()); + assertTrue(changes.byName().get("QueueName").createOnly()); + } + + /** What one provision call saw, read before the real provisioner runs. */ + private record Seen(String stack, boolean isUpdate, List contextDropped, + PropertyChanges changes) { + } + + /** + * Creates then updates a queue stack, recording what each provision call saw. When + * {@code overwriteId} is true, the spy overwrites the + * resource's physical id after the real call, so the next update meets a resource kept with + * a null or blank physical id. + */ + private List createThenUpdateDroppingDelay(String stack, boolean overwriteId, + String physicalIdAfterProvision) { + List seen = new ArrayList<>(); + doAnswer(invocation -> { + StackResource resource = invocation.getArgument(0); + JsonNode props = invocation.getArgument(1); + ProvisionContext ctx = invocation.getArgument(2); + seen.add(new Seen(ctx.stackName(), ctx.isUpdate(), + new ArrayList<>(ctx.droppedProperties(props)), ctx.changes())); + Object result = invocation.callRealMethod(); + if (overwriteId) { + resource.setPhysicalId(physicalIdAfterProvision); + } + return result; + }).when(sqsProvisioner).provision(any(), any(), any()); + + String queue = stack + "-q"; + cfn("CreateStack", stack).header("Authorization", CFN_AUTH) + .formParam("TemplateBody", template(queue, """ + "VisibilityTimeout": "30", "DelaySeconds": "5" + """)) + .when().post("/").then().statusCode(200); + CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", CFN_AUTH); + + cfn("UpdateStack", stack).header("Authorization", CFN_AUTH) + .formParam("TemplateBody", template(queue, """ + "VisibilityTimeout": "30" + """)) + .when().post("/").then().statusCode(200); + CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE", CFN_AUTH); + + return seen.stream().filter(s -> s.stack().equals(stack)).toList(); + } + + private void assertEngineSaysNothingIsDropped(List forStack) { + assertEquals(2, forStack.size(), "one provision call for the create, one for the update"); + Seen update = forStack.get(1); + assertFalse(update.isUpdate(), "a resource without a physical id is not an update"); + assertEquals(List.of(), update.contextDropped()); + PropertyChanges changes = update.changes(); + assertNotNull(changes, "the engine supplies the object on every call"); + assertEquals(List.of(), List.copyOf(changes.dropped()), + "the engine agrees with the context that nothing is dropped"); + assertEquals(Set.of(), changes.changed()); + assertEquals(Set.of(), changes.unchanged()); + assertEquals(Set.of("QueueName", "VisibilityTimeout"), changes.added(), + "every property of the current template is ADDED when the context is not an update"); + } + + @Test + void engineAndContextAgreeOnDroppedForANormalUpdate() { + String stack = "agree-" + Long.toString(System.nanoTime(), 36); + List forStack = createThenUpdateDroppingDelay(stack, false, null); + + assertEquals(2, forStack.size()); + Seen update = forStack.get(1); + assertTrue(update.isUpdate()); + assertEquals(List.of("DelaySeconds"), update.contextDropped()); + assertNotNull(update.changes()); + assertEquals(update.contextDropped(), List.copyOf(update.changes().dropped())); + } + + @Test + void updateOfAResourceWithANullPhysicalIdIsNotAnUpdateForTheEngineEither() { + String stack = "nullid-" + Long.toString(System.nanoTime(), 36); + assertEngineSaysNothingIsDropped(createThenUpdateDroppingDelay(stack, true, null)); + } + + @Test + void updateOfAResourceWithABlankPhysicalIdIsNotAnUpdateForTheEngineEither() { + String stack = "blankid-" + Long.toString(System.nanoTime(), 36); + assertEngineSaysNothingIsDropped(createThenUpdateDroppingDelay(stack, true, " ")); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackPolicyServiceTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackPolicyServiceTest.java index fe0d5feb33..68b6c8c0d6 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackPolicyServiceTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackPolicyServiceTest.java @@ -51,7 +51,7 @@ class CloudFormationStackPolicyServiceTest { void setUp() { provisioner = mock(CfnResourceDispatcher.class); when(provisioner.provision(anyString(), anyString(), any(), any(), anyString(), anyString(), anyString(), - any(), any(), any(), any())).thenAnswer(invocation -> { + any(), any(), any(), any(), any())).thenAnswer(invocation -> { StackResource resource = new StackResource(); resource.setLogicalId(invocation.getArgument(0)); resource.setResourceType(invocation.getArgument(1)); diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CarriedChanges.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CarriedChanges.java new file mode 100644 index 0000000000..af78c662b0 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CarriedChanges.java @@ -0,0 +1,44 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import org.mockito.ArgumentCaptor; +import org.mockito.MockMakers; +import org.mockito.MockedStatic; + +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.withSettings; + +/** + * Test support for provisioners that rebuild their {@link ProvisionContext} mid-provision: the + * engine's {@link PropertyChanges} must still be on the context they hand to + * {@link ReplacementCleanup#record}. + */ +final class CarriedChanges { + + /** A distinct instance, so a test can tell the engine's statement from one derived afterwards. */ + static final PropertyChanges ENGINE_STATEMENT = new PropertyChanges(Map.of()); + + private CarriedChanges() { + } + + /** {@code base} with the engine's statement attached. */ + static ProvisionContext withEngineStatement(ProvisionContext base) { + return new ProvisionContext(base.engine(), base.region(), base.accountId(), base.stackName(), + base.priorPhysicalId(), base.progress(), base.priorProperties(), ENGINE_STATEMENT); + } + + /** Runs {@code provision} and returns the context its last {@code ReplacementCleanup.record} call received. */ + static ProvisionContext contextRecorded(Runnable provision) { + try (MockedStatic cleanup = mockStatic(ReplacementCleanup.class, + withSettings().mockMaker(MockMakers.INLINE).defaultAnswer(CALLS_REAL_METHODS))) { + provision.run(); + ArgumentCaptor recorded = ArgumentCaptor.forClass(ProvisionContext.class); + cleanup.verify(() -> ReplacementCleanup.record(any(), recorded.capture(), any()), atLeastOnce()); + return recorded.getAllValues().getLast(); + } + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CognitoResourceServerCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CognitoResourceServerCfnProvisionerTest.java index 05070ccc62..5118d374b2 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CognitoResourceServerCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CognitoResourceServerCfnProvisionerTest.java @@ -21,6 +21,7 @@ import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -583,6 +584,19 @@ class CognitoResourceServerCfnProvisionerTest { verify(cognito, never()).deleteResourceServer(NEW_POOL, IDENTIFIER); } + @Test + void aReplacementKeepsTheEnginesChangesOnTheCleanupContext() { + when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API")); + StackResource resource = resource(IDENTIFIER, POOL); + ProvisionContext engineContext = CarriedChanges.withEngineStatement(ctx(IDENTIFIER)); + ObjectNode desired = properties(NEW_POOL, IDENTIFIER, "New API"); + + ProvisionContext recorded = CarriedChanges.contextRecorded( + () -> provisioner.provision(resource, desired, engineContext)); + + assertSame(CarriedChanges.ENGINE_STATEMENT, recorded.changes("AWS::Cognito::UserPoolResourceServer", null)); + } + @Test void retainingAReplacementDoesNotDeleteThePriorResource() { when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API")); diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/PropertyChangesTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/PropertyChangesTest.java new file mode 100644 index 0000000000..6cac61844a --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/PropertyChangesTest.java @@ -0,0 +1,402 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.NullNode; +import io.floci.aws.services.cloudformation.provisioners.PropertyChanges.Kind; +import io.floci.aws.services.cloudformation.provisioners.PropertyChanges.PropertyChange; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * What the engine tells a provisioner about each top-level property of an update: added, changed, + * dropped or unchanged. Every expected value is written out by hand from the rules of the design + * (floci-spine 1.1), never read back from the implementation. + */ +class PropertyChangesTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static JsonNode json(String json) { + try { + return MAPPER.readTree(json); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + + private static List names(PropertyChanges changes) { + return List.copyOf(changes.byName().keySet()); + } + + // Rule 2: not an update, or no usable prior properties. + + @Test + void createMarksEveryPropertyAddedAndNothingElse() { + PropertyChanges changes = PropertyChanges.between("AWS::SQS::Queue", false, null, + json("{\"QueueName\": \"q\", \"DelaySeconds\": 5}")); + + assertEquals(List.of("QueueName", "DelaySeconds"), names(changes)); + assertEquals(Kind.ADDED, changes.kindOf("QueueName")); + assertEquals(Kind.ADDED, changes.kindOf("DelaySeconds")); + assertEquals(Set.of("QueueName", "DelaySeconds"), changes.added()); + assertTrue(changes.changed().isEmpty()); + assertTrue(changes.dropped().isEmpty()); + assertTrue(changes.unchanged().isEmpty()); + } + + @Test + void createIgnoresPriorPropertiesEvenWhenTheyAreSupplied() { + PropertyChanges changes = PropertyChanges.between(null, false, + json("{\"Gone\": 1, \"Same\": 2}"), json("{\"Same\": 2, \"New\": 3}")); + + assertEquals(List.of("Same", "New"), names(changes)); + assertEquals(Set.of("Same", "New"), changes.added()); + assertTrue(changes.dropped().isEmpty()); + assertTrue(changes.unchanged().isEmpty()); + assertNull(changes.kindOf("Gone")); + } + + @Test + void createWithComparedFormsStillMarksEveryPropertyAdded() { + PropertyChanges changes = PropertyChanges.between(null, false, null, json("{\"A\": 1}"), + json("{\"A\": 1}"), json("{\"A\": 1}")); + + assertEquals(Kind.ADDED, changes.kindOf("A")); + } + + @Test + void createWithNullPropertiesHasNoChanges() { + PropertyChanges changes = PropertyChanges.between(null, false, null, null); + + assertTrue(changes.byName().isEmpty()); + assertTrue(changes.added().isEmpty()); + assertTrue(changes.dropped().isEmpty()); + } + + @Test + void createMarksAJsonNullPropertyAdded() { + PropertyChanges changes = PropertyChanges.between(null, false, null, json("{\"A\": null}")); + + assertEquals(Kind.ADDED, changes.kindOf("A")); + } + + @Test + void updateWithNullPriorPropertiesMarksEveryPropertyAdded() { + PropertyChanges changes = PropertyChanges.between(null, true, null, json("{\"A\": 1, \"B\": 2}")); + + assertEquals(Set.of("A", "B"), changes.added()); + assertTrue(changes.changed().isEmpty()); + assertTrue(changes.dropped().isEmpty()); + assertTrue(changes.unchanged().isEmpty()); + } + + @Test + void updateWithANonObjectPriorMarksEveryPropertyAdded() { + for (String prior : List.of("[1, 2]", "\"text\"", "7", "null", "true")) { + PropertyChanges changes = PropertyChanges.between(null, true, json(prior), json("{\"A\": 1, \"B\": 2}")); + + assertEquals(List.of("A", "B"), names(changes), prior); + assertEquals(Set.of("A", "B"), changes.added(), prior); + assertTrue(changes.dropped().isEmpty(), prior); + assertTrue(changes.unchanged().isEmpty(), prior); + } + } + + // Rule 3: update with prior properties. + + @Test + void updateClassifiesAddedChangedDroppedAndUnchangedAsWritten() { + PropertyChanges changes = PropertyChanges.between("AWS::SQS::Queue", true, + json("{\"Kept\": \"a\", \"Edited\": \"b\", \"Removed\": \"c\"}"), + json("{\"Kept\": \"a\", \"Edited\": \"B\", \"Fresh\": \"d\"}")); + + assertEquals(Kind.UNCHANGED, changes.kindOf("Kept")); + assertEquals(Kind.CHANGED, changes.kindOf("Edited")); + assertEquals(Kind.DROPPED, changes.kindOf("Removed")); + assertEquals(Kind.ADDED, changes.kindOf("Fresh")); + assertEquals(Set.of("Fresh"), changes.added()); + assertEquals(Set.of("Edited"), changes.changed()); + assertEquals(Set.of("Removed"), changes.dropped()); + assertEquals(Set.of("Kept"), changes.unchanged()); + } + + @Test + void aNameInNeitherTemplateHasNoKind() { + PropertyChanges changes = PropertyChanges.between(null, true, json("{\"A\": 1}"), json("{\"A\": 1}")); + + assertNull(changes.kindOf("Absent")); + assertFalse(changes.byName().containsKey("Absent")); + } + + @Test + void asWrittenComparisonIsStructuralJsonEquality() { + PropertyChanges changes = PropertyChanges.between(null, true, + json("{\"Obj\": {\"x\": [1, 2]}, \"Num\": 1, \"Str\": \"1\"}"), + json("{\"Obj\": {\"x\": [1, 2]}, \"Num\": 1, \"Str\": 1}")); + + assertEquals(Kind.UNCHANGED, changes.kindOf("Obj")); + assertEquals(Kind.UNCHANGED, changes.kindOf("Num")); + assertEquals(Kind.CHANGED, changes.kindOf("Str"), "the text \"1\" is not the number 1 as written"); + } + + // Rule 1: JSON null. + + @Test + void aJsonNullBeforeIsNotDeclaredSoANonNullNowIsAdded() { + PropertyChanges changes = PropertyChanges.between(null, true, + json("{\"A\": null}"), json("{\"A\": \"v\"}")); + + PropertyChange change = changes.byName().get("A"); + assertEquals(Kind.ADDED, change.kind()); + assertNull(change.prior(), "not declared before, so no prior node"); + assertEquals("v", change.current().asText()); + } + + @Test + void aJsonNullNowIsDeclaredSoANonNullBeforeIsChanged() { + JsonNode current = json("{\"A\": null}"); + PropertyChanges changes = PropertyChanges.between(null, true, json("{\"A\": \"v\"}"), current); + + PropertyChange change = changes.byName().get("A"); + assertEquals(Kind.CHANGED, change.kind()); + assertEquals("v", change.prior().asText()); + assertSame(current.get("A"), change.current()); + assertTrue(change.current().isNull()); + } + + @Test + void aJsonNullOnBothSidesIsAddedBecauseOnlyNowIsDeclared() { + PropertyChanges changes = PropertyChanges.between(null, true, json("{\"A\": null}"), json("{\"A\": null}")); + + PropertyChange change = changes.byName().get("A"); + assertEquals(Kind.ADDED, change.kind()); + assertNull(change.prior()); + assertEquals(NullNode.getInstance(), change.current()); + } + + @Test + void aJsonNullBeforeAndAbsentNowIsInNeitherTemplate() { + PropertyChanges changes = PropertyChanges.between(null, true, json("{\"A\": null, \"B\": 1}"), json("{}")); + + assertNull(changes.kindOf("A")); + assertEquals(Set.of("B"), changes.dropped()); + } + + // Rule 8: properties null (or not an object) on an update. + + @Test + void nullPropertiesOnAnUpdateDropEveryPreviouslyDeclaredName() { + PropertyChanges changes = PropertyChanges.between("AWS::SQS::Queue", true, + json("{\"A\": 1, \"Nothing\": null, \"B\": 2}"), null); + + assertEquals(List.of("A", "B"), names(changes)); + assertEquals(Set.of("A", "B"), changes.dropped()); + assertTrue(changes.added().isEmpty()); + assertTrue(changes.changed().isEmpty()); + assertTrue(changes.unchanged().isEmpty()); + } + + @Test + void nonObjectPropertiesOnAnUpdateDropEveryPreviouslyDeclaredName() { + PropertyChanges changes = PropertyChanges.between(null, true, json("{\"A\": 1}"), json("[\"A\"]")); + + assertEquals(Set.of("A"), changes.dropped()); + } + + // Rule 4: compared forms. + + @Test + void aDifferenceOnlyAsWrittenIsUnchangedWhenTheComparedFormsAgree() { + PropertyChanges changes = PropertyChanges.between(null, true, + json("{\"Timeout\": \"30\"}"), + json("{\"Timeout\": {\"Fn::Join\": [\"\", [\"3\", \"0\"]]}}"), + json("{\"Timeout\": \"30\"}"), json("{\"Timeout\": \"30\"}")); + + assertEquals(Kind.UNCHANGED, changes.kindOf("Timeout")); + assertEquals(Set.of("Timeout"), changes.unchanged()); + assertTrue(changes.changed().isEmpty()); + } + + @Test + void anAsWrittenEqualityIsChangedWhenTheComparedFormsDiffer() { + PropertyChanges changes = PropertyChanges.between(null, true, + json("{\"Size\": {\"Ref\": \"P\"}}"), json("{\"Size\": {\"Ref\": \"P\"}}"), + json("{\"Size\": \"1\"}"), json("{\"Size\": \"2\"}")); + + assertEquals(Kind.CHANGED, changes.kindOf("Size")); + } + + @Test + void withoutComparedFormsTheAsWrittenValuesDecide() { + PropertyChanges nullForms = PropertyChanges.between(null, true, + json("{\"A\": 1, \"B\": 1}"), json("{\"A\": 1, \"B\": 2}"), null, null); + PropertyChanges shortForm = PropertyChanges.between(null, true, + json("{\"A\": 1, \"B\": 1}"), json("{\"A\": 1, \"B\": 2}")); + + assertEquals(Kind.UNCHANGED, nullForms.kindOf("A")); + assertEquals(Kind.CHANGED, nullForms.kindOf("B")); + assertEquals(shortForm.kindOf("A"), nullForms.kindOf("A")); + assertEquals(shortForm.kindOf("B"), nullForms.kindOf("B")); + } + + @Test + void aNullComparedPriorOrCurrentFallsBackToAsWritten() { + JsonNode prior = json("{\"Same\": 1, \"Diff\": 1}"); + JsonNode current = json("{\"Same\": 1, \"Diff\": 2}"); + JsonNode compared = json("{\"Same\": \"x\", \"Diff\": \"x\"}"); + + PropertyChanges noPrior = PropertyChanges.between(null, true, prior, current, null, compared); + PropertyChanges noCurrent = PropertyChanges.between(null, true, prior, current, compared, null); + + assertEquals(Kind.UNCHANGED, noPrior.kindOf("Same")); + assertEquals(Kind.CHANGED, noPrior.kindOf("Diff"), "the compared forms agree but one side is absent"); + assertEquals(Kind.UNCHANGED, noCurrent.kindOf("Same")); + assertEquals(Kind.CHANGED, noCurrent.kindOf("Diff")); + } + + @Test + void aNameMissingFromTheComparedCurrentUsesTheAsWrittenValues() { + PropertyChanges differs = PropertyChanges.between(null, true, + json("{\"A\": 1}"), json("{\"A\": 2}"), + json("{\"A\": \"x\"}"), json("{}")); + PropertyChanges equal = PropertyChanges.between(null, true, + json("{\"A\": 1}"), json("{\"A\": 1}"), + json("{\"A\": \"x\"}"), json("{}")); + + assertEquals(Kind.CHANGED, differs.kindOf("A")); + assertEquals(Kind.UNCHANGED, equal.kindOf("A")); + } + + @Test + void aNameMissingFromBothComparedFormsUsesTheAsWrittenValues() { + PropertyChanges changes = PropertyChanges.between(null, true, + json("{\"A\": 1}"), json("{\"A\": 2}"), json("{}"), json("{}")); + + assertEquals(Kind.CHANGED, changes.kindOf("A"), "two missing nodes are not an agreement"); + } + + @Test + void comparedFormsNeverTurnAnAddedOrDroppedNameIntoAnythingElse() { + PropertyChanges changes = PropertyChanges.between(null, true, + json("{\"Old\": 1}"), json("{\"New\": 1}"), + json("{\"Old\": 1, \"New\": 1}"), json("{\"Old\": 1, \"New\": 1}")); + + assertEquals(Kind.DROPPED, changes.kindOf("Old")); + assertEquals(Kind.ADDED, changes.kindOf("New")); + } + + // Rule 5: prior and current are the raw nodes. + + @Test + void priorAndCurrentAreTheNodesOfTheTemplatePropertiesNotTheComparedForms() { + JsonNode prior = json("{\"A\": {\"Fn::Join\": [\"\", [\"a\"]]}, \"Gone\": \"g\"}"); + JsonNode current = json("{\"A\": \"a\", \"New\": \"n\"}"); + + PropertyChanges changes = PropertyChanges.between(null, true, prior, current, + json("{\"A\": \"COMPARED-PRIOR\"}"), json("{\"A\": \"COMPARED-PRIOR\"}")); + + PropertyChange a = changes.byName().get("A"); + assertSame(prior.get("A"), a.prior()); + assertSame(current.get("A"), a.current()); + assertEquals("A", a.name()); + PropertyChange gone = changes.byName().get("Gone"); + assertSame(prior.get("Gone"), gone.prior()); + assertNull(gone.current(), "a dropped property has no current node"); + PropertyChange added = changes.byName().get("New"); + assertNull(added.prior(), "an added property has no prior node"); + assertSame(current.get("New"), added.current()); + } + + // Rule 6: createOnly. + + /** {@code create-only-properties.json}: {@code AWS::SQS::Queue} lists FifoQueue and QueueName. */ + @Test + void createOnlyFollowsTheRegistryForTheResourceType() { + PropertyChanges changes = PropertyChanges.between("AWS::SQS::Queue", true, + json("{\"QueueName\": \"a\", \"VisibilityTimeout\": 1, \"FifoQueue\": true}"), + json("{\"QueueName\": \"b\", \"VisibilityTimeout\": 2, \"New\": 1}")); + + assertTrue(changes.byName().get("QueueName").createOnly()); + assertTrue(changes.byName().get("FifoQueue").createOnly(), "also true for a dropped create-only property"); + assertFalse(changes.byName().get("VisibilityTimeout").createOnly()); + assertFalse(changes.byName().get("New").createOnly()); + } + + @Test + void createOnlyIsFalseForEveryNameWithoutAResourceType() { + PropertyChanges changes = PropertyChanges.between(null, true, + json("{\"QueueName\": \"a\"}"), json("{\"QueueName\": \"b\"}")); + + assertFalse(changes.byName().get("QueueName").createOnly()); + } + + @Test + void createOnlyIsFalseForATypeTheRegistryDoesNotKnow() { + PropertyChanges changes = PropertyChanges.between("Custom::Thing", false, null, json("{\"QueueName\": \"a\"}")); + + assertFalse(changes.byName().get("QueueName").createOnly()); + } + + // Rule 7: order and unmodifiable views. + + @Test + void byNameFollowsThePriorTemplatesOrderThenTheRemainingNamesInPropertiesOrder() { + PropertyChanges changes = PropertyChanges.between(null, true, + json("{\"B\": 1, \"A\": 2, \"C\": 3}"), json("{\"D\": 4, \"A\": 2, \"B\": 9, \"E\": 5}")); + + assertEquals(List.of("B", "A", "C", "D", "E"), names(changes)); + assertEquals(Kind.CHANGED, changes.kindOf("B")); + assertEquals(Kind.UNCHANGED, changes.kindOf("A")); + assertEquals(Kind.DROPPED, changes.kindOf("C")); + assertEquals(Kind.ADDED, changes.kindOf("D")); + } + + @Test + void eachSetKeepsThatOrder() { + PropertyChanges changes = PropertyChanges.between(null, true, + json("{\"Z\": 1, \"A\": 2, \"M\": 3, \"Keep\": 0}"), + json("{\"Y\": 1, \"Keep\": 0, \"X\": 2}")); + + assertEquals(List.of("Z", "A", "M"), List.copyOf(changes.dropped())); + assertEquals(List.of("Y", "X"), List.copyOf(changes.added())); + assertEquals(List.of("Keep"), List.copyOf(changes.unchanged())); + assertTrue(changes.changed().isEmpty()); + } + + @Test + void theFourSetsAreUnmodifiable() { + PropertyChanges changes = PropertyChanges.between(null, true, + json("{\"A\": 1, \"B\": 1, \"C\": 1}"), json("{\"A\": 2, \"B\": 1, \"D\": 1}")); + + assertThrows(UnsupportedOperationException.class, () -> changes.added().add("X")); + assertThrows(UnsupportedOperationException.class, () -> changes.changed().add("X")); + assertThrows(UnsupportedOperationException.class, () -> changes.dropped().add("X")); + assertThrows(UnsupportedOperationException.class, () -> changes.unchanged().add("X")); + assertThrows(UnsupportedOperationException.class, () -> changes.dropped().clear()); + } + + @Test + void theFourSetsPartitionByName() { + PropertyChanges changes = PropertyChanges.between(null, true, + json("{\"A\": 1, \"B\": 1, \"C\": 1}"), json("{\"A\": 2, \"B\": 1, \"D\": 1}")); + + Map byName = changes.byName(); + assertEquals(byName.size(), changes.added().size() + changes.changed().size() + + changes.dropped().size() + changes.unchanged().size()); + assertEquals(Set.of("D"), changes.added()); + assertEquals(Set.of("A"), changes.changed()); + assertEquals(Set.of("C"), changes.dropped()); + assertEquals(Set.of("B"), changes.unchanged()); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java index d290741cff..09ba3f940a 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java @@ -6,15 +6,21 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import java.lang.reflect.RecordComponent; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -59,6 +65,25 @@ class ProvisionContextTest { event -> { }, priorProperties == null ? null : props(priorProperties)); } + @Test + void withPriorPhysicalIdChangesOnlyThePriorPhysicalId() throws Exception { + PropertyChanges changes = PropertyChanges.between("AWS::SQS::Queue", true, + props("{\"A\":1}"), props("{\"A\":2}")); + ProvisionContext original = new ProvisionContext(engine, "eu-west-1", "123456789012", "stack", + "old-id", event -> {}, props("{\"A\":1}"), changes); + + for (String replacement : new String[] {"new-id", null}) { + ProvisionContext copy = original.withPriorPhysicalId(replacement); + + for (RecordComponent component : ProvisionContext.class.getRecordComponents()) { + Object expected = component.getName().equals("priorPhysicalId") + ? replacement : component.getAccessor().invoke(original); + assertSame(expected, component.getAccessor().invoke(copy), component.getName()); + } + } + assertEquals("old-id", original.priorPhysicalId()); + } + @Test void previouslyDeclaredReadsThePreviousTemplatesProperties() { ProvisionContext ctx = contextWithPriorProperties(""" @@ -83,6 +108,110 @@ class ProvisionContextTest { assertEquals(Set.of("Kept", "Dropped", "DroppedIf"), ctx.droppedProperties(null)); } + /** One prior/current pair for the rule that {@code changes(...).dropped()} is {@code droppedProperties}. */ + private record DroppedCase(String label, String priorPhysicalId, String prior, String props, + List expected) { + @Override + public String toString() { + return label; + } + } + + private static DroppedCase dropped(String label, String prior, String props, String... expected) { + return new DroppedCase(label, "prior-id", prior, props, List.of(expected)); + } + + /** Expected lists are the result of today's droppedProperties, worked out by hand from its definition. */ + static Stream droppedCases() { + return Stream.of( + dropped("one name removed", "{\"A\":1,\"B\":2}", "{\"A\":1}", "B"), + dropped("everything removed, empty props", "{\"A\":1,\"B\":2}", "{}", "A", "B"), + dropped("everything removed, null props", "{\"A\":1,\"B\":2}", null, "A", "B"), + dropped("a prior JSON null was never declared", "{\"A\":null,\"B\":2}", "{}", "B"), + dropped("a JSON null now still counts as declared now", "{\"A\":1}", "{\"A\":null}"), + dropped("same names in another order", "{\"A\":1,\"B\":2}", "{\"B\":2,\"A\":1}"), + dropped("prior field order is kept", "{\"Z\":1,\"A\":2,\"M\":3}", "{\"A\":2}", "Z", "M"), + dropped("no prior properties", null, "{}"), + dropped("prior is an array", "[1,2]", "{}"), + dropped("prior is a string", "\"x\"", "{}"), + dropped("props is an array", "{\"A\":1}", "[\"A\"]", "A"), + new DroppedCase("not an update", null, "{\"A\":1}", "{}", List.of()), + dropped("empty prior, new property", "{}", "{\"A\":1}"), + dropped("a prior Fn::If is declared", "{\"A\":{\"Fn::If\":[\"C\",\"x\",\"y\"]}}", "{\"B\":1}", "A"), + dropped("a null in the middle is skipped", "{\"A\":1,\"B\":null,\"C\":3}", "{\"B\":1}", "A", "C"), + new DroppedCase("a blank prior physical id is not an update", " ", "{\"A\":1}", "{}", List.of())); + } + + @ParameterizedTest + @MethodSource("droppedCases") + void changesDroppedEqualsDroppedPropertiesAndTheHandWrittenSet(DroppedCase c) { + ProvisionContext ctx = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", + c.priorPhysicalId(), event -> { }, c.prior() == null ? null : props(c.prior())); + JsonNode current = c.props() == null ? null : props(c.props()); + + Set viaChanges = ctx.changes("AWS::SQS::Queue", current).dropped(); + + assertEquals(c.expected(), List.copyOf(viaChanges), c.label()); + assertEquals(Set.copyOf(c.expected()), viaChanges, c.label()); + assertEquals(ctx.droppedProperties(current), viaChanges, c.label()); + assertEquals(List.copyOf(ctx.droppedProperties(current)), List.copyOf(viaChanges), c.label()); + } + + @Test + void changesReturnsTheEngineSuppliedObjectWhenTheContextWasBuiltWithOne() { + PropertyChanges supplied = PropertyChanges.between("AWS::SQS::Queue", true, + props("{\"A\":1}"), props("{\"A\":2}")); + ProvisionContext ctx = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", + "prior-id", event -> { }, props("{\"Other\":1}"), supplied); + + assertSame(supplied, ctx.changes()); + assertSame(supplied, ctx.changes("AWS::SQS::Queue", props("{\"Different\":1}")), + "the engine's statement wins over what the arguments would derive"); + assertSame(supplied, ctx.changes("AWS::S3::Bucket", null)); + } + + @Test + void changesIsDerivedFromTheContextsOwnInputsWhenTheEngineSuppliedNone() { + JsonNode prior = props("{\"QueueName\":\"q\",\"Old\":1,\"Same\":2}"); + JsonNode current = props("{\"QueueName\":\"q\",\"Same\":3,\"New\":4}"); + ProvisionContext ctx = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", + "prior-id", event -> { }, prior); + + PropertyChanges derived = ctx.changes("AWS::SQS::Queue", current); + + assertNotNull(derived); + assertEquals(PropertyChanges.between("AWS::SQS::Queue", true, prior, current), derived); + assertEquals(PropertyChanges.Kind.UNCHANGED, derived.kindOf("QueueName")); + assertTrue(derived.byName().get("QueueName").createOnly(), "the resource type given to changes() is used"); + assertEquals(Set.of("Old"), derived.dropped()); + assertEquals(Set.of("New"), derived.added()); + assertEquals(Set.of("Same"), derived.changed()); + } + + @Test + void changesDerivedOnACreateMarksEveryPropertyAdded() { + ProvisionContext ctx = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack"); + + PropertyChanges derived = ctx.changes("AWS::SQS::Queue", props("{\"A\":1,\"B\":2}")); + + assertEquals(Set.of("A", "B"), derived.added()); + assertTrue(derived.dropped().isEmpty()); + } + + @Test + void everyExistingConstructorYieldsNoSuppliedChanges() { + ProvisionContext four = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack"); + ProvisionContext five = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", "prior-id"); + ProvisionContext seven = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", "prior-id", + event -> { }, props("{\"A\":1}")); + + assertNull(four.changes()); + assertNull(five.changes()); + assertNull(seven.changes()); + assertEquals("prior-id", seven.priorPhysicalId()); + assertEquals(props("{\"A\":1}"), seven.priorProperties()); + } + @Test void nothingIsDroppedOnACreateOrWithoutAPreviousTemplate() { ProvisionContext create = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", null, diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/SchedulerScheduleCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/SchedulerScheduleCfnProvisionerTest.java index f6ab72f5d6..2f42da8b56 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/SchedulerScheduleCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/SchedulerScheduleCfnProvisionerTest.java @@ -26,6 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -99,6 +100,36 @@ class SchedulerScheduleCfnProvisionerTest { resource.getAttributes().get("Arn")); } + @Test + void theCleanupContextKeepsTheEnginesChanges() throws Exception { + StackResource resource = resource(); + provisioner.provision(resource, properties("same", "a"), context(null)); + trackScheduleUpdates("same", "a"); + ProvisionContext engineContext = CarriedChanges.withEngineStatement(context("same")); + ObjectNode desired = properties("same", "a").put("ScheduleExpression", "rate(10 minutes)"); + + ProvisionContext recorded = CarriedChanges.contextRecorded( + () -> provisioner.provision(resource, desired, engineContext)); + + assertSame(CarriedChanges.ENGINE_STATEMENT, recorded.changes("AWS::Scheduler::Schedule", null)); + } + + @Test + void aRecoveredRollbackKeepsTheEnginesChangesOnTheCleanupContext() throws Exception { + StackResource resource = resource(); + provisioner.provision(resource, properties("same", "a"), context(null)); + trackScheduleUpdates("same", "a"); + provisioner.provision(resource, properties("same", "a").put("ScheduleExpression", "rate(10 minutes)"), + context("same")); + ProvisionContext engineContext = CarriedChanges.withEngineStatement(context("same")); + ObjectNode desired = properties("same", "a").put("ScheduleExpression", "rate(15 minutes)"); + + ProvisionContext recorded = CarriedChanges.contextRecorded( + () -> provisioner.provision(resource, desired, engineContext)); + + assertSame(CarriedChanges.ENGINE_STATEMENT, recorded.changes("AWS::Scheduler::Schedule", null)); + } + @Test void unnamedScheduleKeepsItsGeneratedNameOnUpdate() throws Exception { ObjectNode props = properties(null, null); diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/SesCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/SesCfnProvisionerTest.java index 6c28d97a78..cc4e734663 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/SesCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/SesCfnProvisionerTest.java @@ -19,6 +19,7 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -404,6 +405,23 @@ class SesCfnProvisionerTest { verify(ses, never()).createEmailIdentity(anyString(), any(), any(), anyString()); } + @Test + void aRecoveredUpdateSnapshotKeepsTheEnginesChangesOnTheRecordedContext() throws Exception { + Identity identity = domain("example.com"); + when(identities.getIdentityVerificationAttributes("example.com", "us-east-1")).thenReturn(identity); + when(ses.listResourceTags(anyString(), eq("us-east-1"))).thenReturn(List.of()); + StackResource resource = resource(); + resource.setPhysicalId("example.com"); + resource.getAttributes().put("__FlociSesUpdateSnapshot", "{\"managedTags\":\"[]\"}"); + ProvisionContext engineContext = CarriedChanges.withEngineStatement(context("example.com")); + JsonNode desired = props("{\"EmailIdentity\":\"example.com\"}"); + + ProvisionContext recorded = CarriedChanges.contextRecorded( + () -> provisioner.provision(resource, desired, engineContext)); + + assertSame(CarriedChanges.ENGINE_STATEMENT, recorded.changes("AWS::SES::EmailIdentity", null)); + } + @Test void deleteDelegatesToSes() { provisioner.delete("AWS::SES::EmailIdentity", "example.com", "us-east-1");