mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): replace an SNS topic when the engine says its create-only properties changed (#8374)
This commit is contained in:
1 parent
2ca478b7ba
commit
d2bca16023
6 files changed
+295
-25
No files matched your search
@@ -99,6 +99,22 @@ public final class CfnRollback {
|
||||
public static final String LISTENER_CERTIFICATES_UPDATE_SNAPSHOT_ATTR =
|
||||
"__FlociListenerCertificatesUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* The ARNs of the inline subscriptions a displaced SNS topic carried, kept while a replacing update
|
||||
* is in flight so a failed stack update can put them back. Written and spent by
|
||||
* {@code SnsCfnProvisioner}; the revert skips {@code __Floci} keys, so the key stays on the
|
||||
* resource until the update settles.
|
||||
*/
|
||||
public static final String SNS_PRIOR_INLINE_SUBSCRIPTIONS_ATTR = "__FlociSnsPriorInlineSubscriptions";
|
||||
|
||||
/**
|
||||
* What an update that adopted an existing SNS topic changed on it: the topic ARN and region, the
|
||||
* attributes it wrote with their prior values (null when absent) and the ARNs of the inline
|
||||
* subscriptions it created, so a failed stack update can put the topic back. Written and spent
|
||||
* by {@code SnsCfnProvisioner}.
|
||||
*/
|
||||
public static final String SNS_ADOPTED_TOPIC_UPDATE_SNAPSHOT_ATTR = "__FlociSnsAdoptedTopicUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* Holds the targets an EventBridge rule carried before the update in flight reconciled them,
|
||||
* with the rule name, bus and region needed to address them again, so a failed stack update can
|
||||
|
||||
+147
-16
@@ -1,6 +1,8 @@
|
||||
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.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.cloudformation.model.StackResource;
|
||||
import io.floci.aws.services.sns.SnsService;
|
||||
@@ -9,6 +11,7 @@ import io.floci.aws.services.sns.model.Topic;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
@@ -16,6 +19,7 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** Provisions {@code AWS::SNS::Topic}, {@code AWS::SNS::Subscription} and {@code AWS::SNS::TopicPolicy}. */
|
||||
@ApplicationScoped
|
||||
@@ -27,6 +31,10 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
|
||||
private static final int TOPIC_NAME_MAX_LENGTH = 256;
|
||||
private static final String FIFO_SUFFIX = ".fifo";
|
||||
private static final String INLINE_SUBSCRIPTION_PREFIX = "__FlociInlineSubscription:";
|
||||
private static final String PRIOR_INLINE_ATTR = CfnRollback.SNS_PRIOR_INLINE_SUBSCRIPTIONS_ATTR;
|
||||
|
||||
private static final String ADOPTED_ATTR = CfnRollback.SNS_ADOPTED_TOPIC_UPDATE_SNAPSHOT_ATTR;
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private final SnsService snsService;
|
||||
|
||||
@@ -50,7 +58,65 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.hasReplacement(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return ReplacementCleanup.cleanupPhysicalId(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.complete(resource, this::delete);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(PRIOR_INLINE_ATTR);
|
||||
resource.getAttributes().remove(ADOPTED_ATTR);
|
||||
ReplacementCleanup.clear(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
JsonNode snapshot = CfnRollback.updateSnapshot(resource, ADOPTED_ATTR);
|
||||
if (snapshot != null) {
|
||||
// A topic the update adopted is not the stack's to keep changed: put its attributes back and
|
||||
// drop the subscriptions this update made, then let the replacement cleanup point back.
|
||||
Map<String, String> prior = new HashMap<>();
|
||||
snapshot.path("attributes").fields().forEachRemaining(e ->
|
||||
prior.put(e.getKey(), CfnRollback.snapshotText(snapshot.path("attributes"), e.getKey())));
|
||||
List<String> added = new ArrayList<>();
|
||||
snapshot.path("subscriptions").forEach(arn -> added.add(arn.asText()));
|
||||
restoreAdoptedTopic(CfnRollback.snapshotText(snapshot, "topicArn"),
|
||||
CfnRollback.snapshotText(snapshot, "region"), prior, added);
|
||||
resource.getAttributes().remove(ADOPTED_ATTR);
|
||||
}
|
||||
if (!ReplacementCleanup.rollback(resource, this::delete)) {
|
||||
return false;
|
||||
}
|
||||
String prior = resource.getAttributes().remove(PRIOR_INLINE_ATTR);
|
||||
if (prior != null) {
|
||||
resource.getAttributes().keySet().removeIf(key -> key.startsWith(INLINE_SUBSCRIPTION_PREFIX));
|
||||
for (String arn : prior.split(",")) {
|
||||
if (!arn.isEmpty()) {
|
||||
resource.getAttributes().put(INLINE_SUBSCRIPTION_PREFIX + arn, "true");
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void provisionTopic(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
if (ctx.isUpdate()) {
|
||||
// Rolling this update back undoes it alone; only ContinueUpdateRollback retries the
|
||||
// delete the last rollback could not make.
|
||||
ReplacementCleanup.endRollbackRetry(r);
|
||||
}
|
||||
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
|
||||
String topicName = ctx.resolveOptional(props, "TopicName");
|
||||
String contentBasedDedupFlag = ctx.resolveOptional(props, "ContentBasedDeduplication");
|
||||
String throughputScope = ctx.resolveOptional(props, "FifoThroughputScope");
|
||||
@@ -60,19 +126,22 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
|
||||
boolean fifo = "true".equalsIgnoreCase(ctx.resolveOptional(props, "FifoTopic"))
|
||||
|| (topicName != null && topicName.endsWith(FIFO_SUFFIX));
|
||||
String priorName = r.getAttributes().get("TopicName");
|
||||
// FifoTopic is createOnly and carried by the name, so a flip needs a replacement. Nothing
|
||||
// cleans up the displaced topic or its subscriptions, so refuse it, as SqsCfnProvisioner
|
||||
// does for FifoQueue.
|
||||
if (ctx.isUpdate() && priorName != null && !priorName.isBlank()
|
||||
&& priorName.endsWith(FIFO_SUFFIX) != fifo) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Updating FifoTopic requires resource replacement, which is not supported.", 400);
|
||||
// The engine's change decides whether the update replaces the topic: TopicName and
|
||||
// FifoTopic are create-only in the registry. A topic's mode is carried by its name, so the
|
||||
// prior name's .fifo suffix tells the live mode; the engine reads an added FifoTopic as no
|
||||
// change and would apply the update in place. A named topic cannot be replaced under the
|
||||
// same name.
|
||||
boolean replaces = ctx.isUpdate() && priorName != null && !priorName.isBlank()
|
||||
&& (ctx.changes(TOPIC, props).requiresReplacement() || priorName.endsWith(FIFO_SUFFIX) != fifo);
|
||||
if (replaces && topicName != null && topicName.equals(priorName)) {
|
||||
throw CfnExceptions.customNamedReplacement(topicName);
|
||||
}
|
||||
if (topicName == null || topicName.isBlank()) {
|
||||
// ctx.stablePhysicalName does not fit here: the physical id is the topic ARN, so the
|
||||
// prior name comes from the attribute recorded at create time. Reusing it keeps an
|
||||
// unnamed topic (and its subscriptions) across updates instead of orphaning it.
|
||||
if (priorName != null && !priorName.isBlank()) {
|
||||
// unnamed topic (and its subscriptions) across updates instead of orphaning it. A
|
||||
// replacing update gets a fresh generated name instead.
|
||||
if (priorName != null && !priorName.isBlank() && !replaces) {
|
||||
topicName = priorName;
|
||||
} else if (fifo) {
|
||||
// Like real CloudFormation, a generated FIFO name ends in .fifo.
|
||||
@@ -114,8 +183,9 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
|
||||
boolean created = creation.created();
|
||||
// createTopic leaves an existing topic untouched, so an update writes the mutable
|
||||
// attributes itself. A property the template dropped is reset, not left standing.
|
||||
Map<String, String> desired = new HashMap<>();
|
||||
if (ctx.isUpdate()) {
|
||||
Map<String, String> desired = new HashMap<>(attributes);
|
||||
desired.putAll(attributes);
|
||||
if (fifo) {
|
||||
desired.putIfAbsent("ContentBasedDeduplication", "false");
|
||||
desired.putIfAbsent("FifoThroughputScope", "Topic");
|
||||
@@ -128,8 +198,13 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
|
||||
desired.put("MaximumMessageSize",
|
||||
String.valueOf(SnsService.DEFAULT_MAX_MESSAGE_SIZE));
|
||||
}
|
||||
desired.forEach((name, value) ->
|
||||
snsService.setTopicAttributes(topic.getTopicArn(), name, value, ctx.region()));
|
||||
}
|
||||
// A replacing update that adopted an existing topic changes something the stack did not
|
||||
// create, so what it writes (the prior values, null for absent) is kept for the undo.
|
||||
boolean adopted = ctx.isUpdate() && !created && !ctx.priorPhysicalId().equals(topic.getTopicArn());
|
||||
Map<String, String> priorAttributes = new HashMap<>();
|
||||
if (adopted) {
|
||||
desired.keySet().forEach(name -> priorAttributes.put(name, topic.getAttributes().get(name)));
|
||||
}
|
||||
// Ref returns the topic ARN, which is why the physical id is the ARN and not the name.
|
||||
r.setPhysicalId(topic.getTopicArn());
|
||||
@@ -143,9 +218,64 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
|
||||
Set<String> added = new HashSet<>();
|
||||
CfnRollback.guarded(r, ctx, created,
|
||||
() -> snsService.deleteTopic(topic.getTopicArn(), ctx.region()),
|
||||
() -> added.forEach(arn -> snsService.unsubscribe(arn, ctx.region())),
|
||||
() -> reconcileInlineSubscriptions(r, topic.getTopicArn(), ctx.region(),
|
||||
desiredSubscriptions, existing, added));
|
||||
() -> {
|
||||
if (adopted) {
|
||||
restoreAdoptedTopic(topic.getTopicArn(), ctx.region(), priorAttributes, added);
|
||||
} else {
|
||||
added.forEach(arn -> snsService.unsubscribe(arn, ctx.region()));
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
desired.forEach((name, value) ->
|
||||
snsService.setTopicAttributes(topic.getTopicArn(), name, value, ctx.region()));
|
||||
reconcileInlineSubscriptions(r, topic.getTopicArn(), ctx.region(),
|
||||
desiredSubscriptions, existing, added);
|
||||
});
|
||||
boolean replaced = ctx.isUpdate() && !ctx.priorPhysicalId().equals(r.getPhysicalId());
|
||||
if (replaced) {
|
||||
r.getAttributes().put(PRIOR_INLINE_ATTR, attributesBefore.keySet().stream()
|
||||
.filter(key -> key.startsWith(INLINE_SUBSCRIPTION_PREFIX))
|
||||
.map(key -> key.substring(INLINE_SUBSCRIPTION_PREFIX.length()))
|
||||
.collect(Collectors.joining(",")));
|
||||
} else {
|
||||
r.getAttributes().remove(PRIOR_INLINE_ATTR);
|
||||
}
|
||||
if (adopted) {
|
||||
ObjectNode snapshot = MAPPER.createObjectNode();
|
||||
snapshot.put("topicArn", topic.getTopicArn());
|
||||
snapshot.put("region", ctx.region());
|
||||
ObjectNode attrs = snapshot.putObject("attributes");
|
||||
priorAttributes.forEach((name, value) -> {
|
||||
if (value == null) {
|
||||
attrs.putNull(name);
|
||||
} else {
|
||||
attrs.put(name, value);
|
||||
}
|
||||
});
|
||||
added.forEach(arn -> snapshot.withArray("subscriptions").add(arn));
|
||||
r.getAttributes().put(ADOPTED_ATTR, snapshot.toString());
|
||||
} else {
|
||||
r.getAttributes().remove(ADOPTED_ATTR);
|
||||
}
|
||||
// A topic the update only adopted, because its name already existed, is not deleted by a rollback.
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore, replaced, created);
|
||||
}
|
||||
|
||||
/** Puts an adopted topic back: the attributes this update wrote (null = absent) and its own subscriptions. */
|
||||
private void restoreAdoptedTopic(String topicArn, String region, Map<String, String> prior,
|
||||
Collection<String> addedSubscriptions) {
|
||||
addedSubscriptions.forEach(arn -> CfnDeletes.safeDelete("subscription", arn,
|
||||
() -> snsService.unsubscribe(arn, region), "NotFound"));
|
||||
if (!snsService.topicExists(topicArn, region)) {
|
||||
return;
|
||||
}
|
||||
prior.forEach((name, value) -> {
|
||||
if (value == null) {
|
||||
snsService.removeTopicAttribute(topicArn, name, region);
|
||||
} else {
|
||||
snsService.setTopicAttributes(topicArn, name, value, region);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void reconcileInlineSubscriptions(StackResource r, String topicArn, String region,
|
||||
@@ -275,7 +405,8 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
switch (resourceType) {
|
||||
case TOPIC -> snsService.deleteTopic(physicalId, region);
|
||||
case TOPIC -> CfnDeletes.safeDelete("topic", physicalId,
|
||||
() -> snsService.deleteTopic(physicalId, region), "NotFound");
|
||||
case SUBSCRIPTION -> snsService.unsubscribe(physicalId, region);
|
||||
// No entity to remove. The topics keep the last policy written, the same choice
|
||||
// SqsCfnProvisioner makes for AWS::SQS::QueuePolicy.
|
||||
|
||||
@@ -739,6 +739,15 @@ public class SnsService implements Resettable, ResourceProvider {
|
||||
topicStore.put(key, topic);
|
||||
}
|
||||
|
||||
/** Exists for CloudFormation rollback: SetTopicAttributes cannot unset an attribute. */
|
||||
public synchronized void removeTopicAttribute(String topicArn, String attributeName, String region) {
|
||||
String key = topicKey(region, topicArn);
|
||||
Topic topic = topicStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("NotFound", "Topic does not exist.", 404));
|
||||
topic.getAttributes().remove(attributeName);
|
||||
topicStore.put(key, topic);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a statement to the topic's policy granting {@code accountIds} the named SNS actions,
|
||||
* written as AWS writes it: the label is its {@code Sid}, each account becomes its
|
||||
|
||||
@@ -217,6 +217,11 @@ class CfnReplacementIntegrationTest {
|
||||
+ " \"LogGroupName\": {\"Fn::If\": [\"Named\", \"repl-if-output\","
|
||||
+ " {\"Ref\": \"AWS::NoValue\"}]}}}}}",
|
||||
"Subject", "False", false, stack -> createOutputSource()),
|
||||
createOnlyRow("SNS topic TopicName removed", "", "", "AWS::SNS::Topic",
|
||||
"\"TopicName\": \"repl-sns-named\"", "\"DisplayName\": \"unnamed\"",
|
||||
"True", false, null),
|
||||
createOnlyRow("SNS topic FifoTopic switched on", "", "", "AWS::SNS::Topic",
|
||||
"\"FifoTopic\": false", "\"FifoTopic\": true", "True", false, null),
|
||||
new Row("deployed parameter renamed, same value",
|
||||
locationStack(stringParameter("NameA", HOSTED), "", REF_A, "d"),
|
||||
locationStack(stringParameter("NameB", HOSTED), "", REF_B, "e"),
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import io.floci.aws.testing.CfnTestStack;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Stack;
|
||||
import software.amazon.awssdk.services.sns.SnsClient;
|
||||
import software.amazon.awssdk.services.sns.model.Subscription;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationSnsAdoptedTopicRollbackIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT_ARN = "arn:aws:sns:us-east-1:000000000000:";
|
||||
private static final String OUTSIDE_QUEUE = "arn:aws:sqs:us-east-1:000000000000:outside-queue";
|
||||
private static final String INLINE_QUEUE = "arn:aws:sqs:us-east-1:000000000000:inline-queue";
|
||||
|
||||
@RegisterExtension
|
||||
final CfnTestStack stack = new CfnTestStack("cfn-sns-adopt");
|
||||
|
||||
@Test
|
||||
void aRolledBackReplacementLeavesTheTopicItAdoptedAsItWas() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String own = "own-" + suffix;
|
||||
String outside = "outside-" + suffix;
|
||||
SnsClient sns = stack.client(SnsClient.builder());
|
||||
String outsideArn = sns.createTopic(r -> r.name(outside).attributes(Map.of("DisplayName", "outside"))).topicArn();
|
||||
try {
|
||||
sns.subscribe(r -> r.topicArn(outsideArn).protocol("sqs").endpoint(OUTSIDE_QUEUE));
|
||||
Map<String, String> before = sns.getTopicAttributes(r -> r.topicArn(outsideArn)).attributes();
|
||||
|
||||
stack.create(template(own, "", false));
|
||||
|
||||
String inline = ", \"MaximumMessageSize\": 4096, \"Subscription\": "
|
||||
+ "[{\"Protocol\": \"sqs\", \"Endpoint\": \"" + INLINE_QUEUE + "\"}]";
|
||||
Stack rolledBack = stack.update(template(outside, inline, true), "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
assertEquals(before, sns.getTopicAttributes(r -> r.topicArn(outsideArn)).attributes());
|
||||
assertEquals(List.of(OUTSIDE_QUEUE), sns.listSubscriptionsByTopic(r -> r.topicArn(outsideArn))
|
||||
.subscriptions().stream().map(Subscription::endpoint).toList());
|
||||
assertEquals(ACCOUNT_ARN + own, CfnStackWaits.output(rolledBack, "TopicRef"));
|
||||
sns.getTopicAttributes(r -> r.topicArn(ACCOUNT_ARN + own));
|
||||
} finally {
|
||||
sns.deleteTopic(r -> r.topicArn(outsideArn));
|
||||
}
|
||||
}
|
||||
|
||||
/** A named topic; with {@code failing}, a later resource that fails, so the update rolls back. */
|
||||
private static String template(String topicName, String extraTopicProperties, boolean failing) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Topic": {"Type": "AWS::SNS::Topic", "Properties": {"TopicName": "%s"%s}}%s
|
||||
},
|
||||
"Outputs": {"TopicRef": {"Value": {"Ref": "Topic"}}}
|
||||
}
|
||||
""".formatted(topicName, extraTopicProperties,
|
||||
failing ? CfnStackWaits.failingResourceAfter("Topic") : "");
|
||||
}
|
||||
}
|
||||
+52
-9
@@ -10,6 +10,8 @@ import io.floci.aws.services.sns.model.Subscription;
|
||||
import io.floci.aws.services.sns.model.Topic;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -26,9 +28,11 @@ import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.contains;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -412,27 +416,27 @@ class SnsCfnProvisionerTest {
|
||||
"a standard topic must not be renamed into a FIFO one");
|
||||
}
|
||||
|
||||
/**
|
||||
* Replacing would displace a topic nothing cleans up, subscriptions included, so it is refused.
|
||||
*/
|
||||
/** A custom-named topic cannot be replaced under the same name, so turning it FIFO is refused. */
|
||||
@Test
|
||||
void aTopicTurningFifoIsRejectedRatherThanReplaced() {
|
||||
void aNamedTopicTurningFifoIsRefusedAsACustomNamedReplacement() {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("Topic");
|
||||
r.setResourceType("AWS::SNS::Topic");
|
||||
r.setAttributes(new HashMap<>(Map.of("TopicName", "my-stack-Topic-abc123def456")));
|
||||
r.setAttributes(new HashMap<>(Map.of("TopicName", "events")));
|
||||
r.setPhysicalId(TOPIC_ARN);
|
||||
ProvisionContext update =
|
||||
new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", TOPIC_ARN);
|
||||
ProvisionContext update = new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack",
|
||||
TOPIC_ARN, e -> { }, props("""
|
||||
{"TopicName": "events"}
|
||||
"""));
|
||||
JsonNode turningFifo = props("""
|
||||
{"FifoTopic": true}
|
||||
{"TopicName": "events", "FifoTopic": true}
|
||||
""");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, turningFifo, update));
|
||||
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
assertTrue(e.getMessage().contains("requires resource replacement"), e.getMessage());
|
||||
assertTrue(e.getMessage().contains("custom-named"), e.getMessage());
|
||||
verify(sns, never()).createTopic(anyString(), anyMap(), anyMap(), anyString());
|
||||
}
|
||||
|
||||
@@ -847,4 +851,43 @@ class SnsCfnProvisionerTest {
|
||||
provisioner.delete("AWS::SNS::TopicPolicy", "topic-policy-abc12345", REGION);
|
||||
verifyNoMoreInteractions(sns);
|
||||
}
|
||||
|
||||
/**
|
||||
* A replacing update that a later resource fails points the topic back to the old ARN with the old
|
||||
* inline-subscription marker, and deletes the new topic only when this update created it.
|
||||
*/
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@CsvSource(delimiter = '|', textBlock = """
|
||||
unnamed topic turning FIFO | my-stack-Topic-abc123 | {"FifoTopic": false, "Subscription": [SUB]} | {"FifoTopic": true, "Subscription": [SUB]} | true | 1
|
||||
rename onto a topic outside the stack | old | {"TopicName": "old", "Subscription": [SUB]} | {"TopicName": "taken", "Subscription": [SUB]} | false | 0
|
||||
""")
|
||||
void aRolledBackTopicReplacementRestoresTheOldTopicAndDeletesOnlyWhatItCreated(
|
||||
String label, String priorName, String priorJson, String newJson, boolean created, int deletes) {
|
||||
String oldArn = "arn:aws:sns:us-east-1:000000000000:" + priorName;
|
||||
String newArn = "arn:aws:sns:us-east-1:000000000000:replacement";
|
||||
String marker = "__FlociInlineSubscription:arn:old-sub";
|
||||
String sub = "{\"Protocol\": \"lambda\", \"Endpoint\": \"arn:lambda\"}";
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("Topic");
|
||||
r.setResourceType("AWS::SNS::Topic");
|
||||
r.setPhysicalId(oldArn);
|
||||
r.setAttributes(new HashMap<>(Map.of("TopicName", priorName, "TopicArn", oldArn, "Arn", oldArn,
|
||||
marker, "true")));
|
||||
doReturn(new SnsService.TopicCreation(topic(newArn), created))
|
||||
.when(sns).createTopicWithStatus(anyString(), anyMap(), anyMap(), eq(REGION));
|
||||
doReturn(subscription("arn:new-sub")).when(sns).subscribe(eq(newArn), anyString(), anyString(),
|
||||
eq(REGION), anyMap());
|
||||
ProvisionContext update = new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack",
|
||||
oldArn, e -> { }, props(priorJson.replace("SUB", sub)));
|
||||
|
||||
provisioner.provision(r, props(newJson.replace("SUB", sub)), update);
|
||||
assertEquals(newArn, r.getPhysicalId(), label);
|
||||
assertTrue(provisioner.rollbackUpdate(r), label);
|
||||
|
||||
assertEquals(oldArn, r.getPhysicalId(), label);
|
||||
assertEquals(priorName, r.getAttributes().get("TopicName"), label);
|
||||
assertEquals("true", r.getAttributes().get(marker), label);
|
||||
verify(sns, times(deletes)).deleteTopic(newArn, REGION);
|
||||
verify(sns, times(deletes)).deleteTopic(anyString(), eq(REGION));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user