feat(cloudformation): provision SES event destinations (#8620)

* feat(cloudformation): provision SES event destinations
* fix(cloudformation): validate SES event destination replacements
* fix(cloudformation): apply SES event destination review feedback
* test(cloudformation): use shared stack waits for SES event destinations
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-11-16 17:08:48 -04:00
1 parent aef8416c4b
commit 5f77b841a2
22 files changed
+1264 -104

No files matched your search

@@ -8,6 +8,7 @@ import org.jboss.logging.Logger;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -19,21 +20,24 @@ public final class CfnCreateOnlyProperties {
private static final Logger LOG = Logger.getLogger(CfnCreateOnlyProperties.class);
private static final String RESOURCE_NAME = "cloudformation/create-only-properties.json";
private static final Map<String, Set<String>> PROPERTIES = load();
private static final String CONDITIONAL_RESOURCE_NAME =
"cloudformation/conditional-create-only-properties.json";
private static final Map<String, Set<String>> PROPERTIES = load(RESOURCE_NAME);
private static final Map<String, Set<String>> CONDITIONAL_PROPERTIES = load(CONDITIONAL_RESOURCE_NAME);
private CfnCreateOnlyProperties() {
}
private static Map<String, Set<String>> load() {
try (InputStream in = CfnCreateOnlyProperties.class.getClassLoader().getResourceAsStream(RESOURCE_NAME)) {
private static Map<String, Set<String>> load(String resourceName) {
try (InputStream in = CfnCreateOnlyProperties.class.getClassLoader().getResourceAsStream(resourceName)) {
if (in == null) {
LOG.warnv("Resource {0} not found on classpath", RESOURCE_NAME);
LOG.warnv("Resource {0} not found on classpath", resourceName);
return Collections.emptyMap();
}
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(in, new TypeReference<Map<String, Set<String>>>() {});
} catch (Exception e) {
LOG.warnv(e, "Failed to load {0}", RESOURCE_NAME);
LOG.warnv(e, "Failed to load {0}", resourceName);
return Collections.emptyMap();
}
}
@@ -68,6 +72,18 @@ public final class CfnCreateOnlyProperties {
return PROPERTIES.getOrDefault(resourceType, Collections.emptySet());
}
/** Schema pointers that require replacement, including conditionally create-only paths. */
static Set<String> replacementPointers(String resourceType) {
Set<String> schemaPointers = getCreateOnlyProperties(resourceType);
Set<String> conditionalPointers = CONDITIONAL_PROPERTIES.get(resourceType);
if (conditionalPointers == null || conditionalPointers.isEmpty()) {
return schemaPointers;
}
Set<String> pointers = new HashSet<>(schemaPointers);
pointers.addAll(conditionalPointers);
return pointers;
}
/** True when the registry table has an entry for the type, so its pointers are authoritative. */
public static boolean hasSchema(String resourceType) {
return PROPERTIES.containsKey(resourceType);
@@ -80,7 +96,7 @@ public final class CfnCreateOnlyProperties {
* element's subtree.
*/
public static boolean createOnlyValueChanged(String resourceType, JsonNode oldProps, JsonNode newProps) {
for (String pointer : getCreateOnlyProperties(resourceType)) {
for (String pointer : replacementPointers(resourceType)) {
if (createOnlyPointerChanged(pointer, oldProps, newProps)) {
return true;
}
@@ -104,7 +120,7 @@ public final class CfnCreateOnlyProperties {
/** The subtrees of the new properties that sit under a create-only pointer of the type. */
public static List<JsonNode> createOnlySubtrees(String resourceType, JsonNode props) {
List<JsonNode> out = new ArrayList<>();
for (String pointer : getCreateOnlyProperties(resourceType)) {
for (String pointer : replacementPointers(resourceType)) {
collect(props, pointer.split("/"), 0, out);
}
return out;
@@ -1591,7 +1591,7 @@ public class CloudFormationService implements ResourceProvider {
}
JsonNode digestedBefore = digested(before);
JsonNode digestedAfter = digested(after);
for (String pointer : CfnCreateOnlyProperties.getCreateOnlyProperties(resourceType)) {
for (String pointer : CfnCreateOnlyProperties.replacementPointers(resourceType)) {
boolean changed = noEvidence(pointer, before)
? writtenPointerChanged(pointer, oldProps, newProps)
: CfnCreateOnlyProperties.createOnlyPointerChanged(pointer, digestedBefore, digestedAfter);
@@ -0,0 +1,76 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.services.cloudformation.model.StackResource;
import java.util.function.Consumer;
/** Cleanup records shared by resources whose physical name is only part of their deletion address. */
final class CfnLifecycleRecords {
private static final ObjectMapper MAPPER = new ObjectMapper();
private CfnLifecycleRecords() {
}
static ObjectNode read(StackResource resource, String attribute, String invalid, String wrongShape) {
String raw = resource.getAttributes().get(attribute);
if (raw == null) {
return null;
}
try {
if (MAPPER.readTree(raw) instanceof ObjectNode object) {
return object;
}
throw new IllegalStateException(wrongShape);
} catch (JsonProcessingException failure) {
throw new IllegalStateException(invalid, failure);
}
}
static void setCleanup(StackResource resource, String attribute, ObjectNode address, boolean retainable) {
resource.getAttributes().put(attribute,
address.put("retainable", retainable).put("attempts", 0).toString());
}
static boolean retained(StackResource resource, JsonNode pending) {
return pending.path("retainable").asBoolean() && "Retain".equals(resource.getUpdateReplacePolicy());
}
static void deletePending(StackResource resource, String attribute, ObjectNode pending,
boolean honorRetain, Consumer<ObjectNode> delete) {
if (pending == null) {
return;
}
if (!honorRetain || !retained(resource, pending)) {
delete.accept(pending);
}
resource.getAttributes().remove(attribute);
}
static String cleanupPhysicalId(StackResource resource, ObjectNode pending) {
return pending == null || retained(resource, pending) ? null : pending.path("name").asText();
}
static UpdateCleanupResult completePending(StackResource resource, String cleanupAttribute,
String updateAttribute, ObjectNode pending,
boolean honorRetain, Consumer<ObjectNode> delete) {
if (pending == null) {
return resource.getAttributes().containsKey(updateAttribute)
? new UpdateCleanupResult(true, true, null, 0, null)
: UpdateCleanupResult.notApplicable();
}
String name = pending.path("name").asText();
try {
deletePending(resource, cleanupAttribute, pending, honorRetain, delete);
return new UpdateCleanupResult(true, true, name, 0, null);
} catch (RuntimeException failure) {
int attempts = pending.path("attempts").asInt() + 1;
pending.put("attempts", attempts);
resource.getAttributes().put(cleanupAttribute, pending.toString());
return new UpdateCleanupResult(true, false, name, attempts, failure.getMessage());
}
}
}
@@ -82,6 +82,35 @@ final class CfnPropertyTypes {
return shape;
}
/** Reject unmodeled members for a provisioner that passes the whole schema-shaped object to a service. */
static void rejectUnknownMembers(String resourceType, JsonNode properties) {
String shape = Holder.MODEL.operations().get(resourceType);
if (shape == null) {
throw notVendored(resourceType);
}
rejectUnknownMembers(properties, shape);
}
private static void rejectUnknownMembers(JsonNode value, String shapeName) {
if (value == null || value.isNull()) {
return;
}
Shape shape = Holder.MODEL.shapes().get(shapeName);
if ("structure".equals(shape.type()) && value.isObject()) {
value.properties().forEach(member -> {
String nested = shape.members().get(member.getKey());
if (nested == null) {
throw new AwsException("ValidationError", "Unknown property: " + member.getKey(), 400);
}
rejectUnknownMembers(member.getValue(), nested);
});
} else if ("list".equals(shape.type()) && value.isArray()) {
value.forEach(element -> rejectUnknownMembers(element, shape.element()));
} else if ("map".equals(shape.type()) && value.isObject()) {
value.forEach(element -> rejectUnknownMembers(element, shape.element()));
}
}
private static IllegalStateException notVendored(String what) {
return new IllegalStateException(what + " is not in " + RESOURCE_NAME
+ "; add the type to tools/aws/regen_cfn_property_types.py");
@@ -1,6 +1,5 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@@ -139,8 +138,7 @@ public class LogsLogStreamCfnProvisioner implements CfnResourceProvisioner {
}
private static void setCleanup(StackResource resource, Identity identity, String region, boolean retainable) {
ObjectNode cleanup = address(identity, region).put("retainable", retainable).put("attempts", 0);
resource.getAttributes().put(CLEANUP_ATTR, cleanup.toString());
CfnLifecycleRecords.setCleanup(resource, CLEANUP_ATTR, address(identity, region), retainable);
}
@Override
@@ -161,10 +159,8 @@ public class LogsLogStreamCfnProvisioner implements CfnResourceProvisioner {
private void deletePending(StackResource resource) {
ObjectNode cleanup = read(resource, CLEANUP_ATTR);
if (cleanup != null) {
delete(identity(cleanup), cleanup.path("region").asText());
resource.getAttributes().remove(CLEANUP_ATTR);
}
CfnLifecycleRecords.deletePending(resource, CLEANUP_ATTR, cleanup, false,
record -> delete(identity(record), record.path("region").asText()));
}
@Override
@@ -195,35 +191,14 @@ public class LogsLogStreamCfnProvisioner implements CfnResourceProvisioner {
@Override
public String updateCleanupPhysicalId(StackResource resource) {
ObjectNode cleanup = read(resource, CLEANUP_ATTR);
return cleanup == null || retained(resource, cleanup) ? null : cleanup.path("name").asText();
return CfnLifecycleRecords.cleanupPhysicalId(resource, cleanup);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
ObjectNode cleanup = read(resource, CLEANUP_ATTR);
if (cleanup == null) {
return resource.getAttributes().containsKey(UPDATE_ATTR)
? new UpdateCleanupResult(true, true, null, 0, null)
: UpdateCleanupResult.notApplicable();
}
String name = cleanup.path("name").asText();
if (retained(resource, cleanup)) {
resource.getAttributes().remove(CLEANUP_ATTR);
return new UpdateCleanupResult(true, true, name, 0, null);
}
try {
deletePending(resource);
return new UpdateCleanupResult(true, true, name, 0, null);
} catch (RuntimeException failure) {
int attempts = cleanup.path("attempts").asInt() + 1;
cleanup.put("attempts", attempts);
resource.getAttributes().put(CLEANUP_ATTR, cleanup.toString());
return new UpdateCleanupResult(true, false, name, attempts, failure.getMessage());
}
}
private static boolean retained(StackResource resource, JsonNode cleanup) {
return cleanup.path("retainable").asBoolean() && "Retain".equals(resource.getUpdateReplacePolicy());
return CfnLifecycleRecords.completePending(resource, CLEANUP_ATTR, UPDATE_ATTR, cleanup, true,
record -> delete(identity(record), record.path("region").asText()));
}
@Override
@@ -233,18 +208,7 @@ public class LogsLogStreamCfnProvisioner implements CfnResourceProvisioner {
}
private static ObjectNode read(StackResource resource, String attribute) {
String raw = resource.getAttributes().get(attribute);
if (raw == null) {
return null;
}
try {
JsonNode record = MAPPER.readTree(raw);
if (record.isObject()) {
return (ObjectNode) record;
}
} catch (JsonProcessingException e) {
throw new IllegalStateException("Invalid log stream lifecycle record for " + resource.getLogicalId(), e);
}
throw new IllegalStateException("Invalid log stream lifecycle record for " + resource.getLogicalId());
String error = "Invalid log stream lifecycle record for " + resource.getLogicalId();
return CfnLifecycleRecords.read(resource, attribute, error, error);
}
}
@@ -0,0 +1,349 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
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.ses.SesConfigurationSetService;
import io.floci.aws.services.ses.model.EventDestination;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.Set;
@ApplicationScoped
public class SesEventDestinationCfnProvisioner implements CfnResourceProvisioner {
private static final String TYPE = "AWS::SES::ConfigurationSetEventDestination";
private static final String SET_ATTR = "__FlociSesEventDestinationConfigurationSet";
private static final String NAME_MODE_ATTR = "__FlociSesEventDestinationNameMode";
private static final String UPDATE_ATTR = "__FlociSesEventDestinationUpdate";
private static final String CLEANUP_ATTR = "__FlociSesEventDestinationCleanup";
private static final ObjectMapper MAPPER = new ObjectMapper();
private final SesConfigurationSetService configurationSets;
@Inject
public SesEventDestinationCfnProvisioner(SesConfigurationSetService configurationSets) {
this.configurationSets = configurationSets;
}
@Override
public Set<String> resourceTypes() {
return Set.of(TYPE);
}
@Override
public void provision(StackResource resource, JsonNode properties, ProvisionContext ctx) {
if (resource.getAttributes().containsKey(UPDATE_ATTR)) {
rollbackUpdate(resource);
ctx = ctx.withPriorPhysicalId(resource.getPhysicalId());
}
JsonNode resolved = ctx.engine().resolveNodeOmittingNoValue(properties);
if (resolved == null || !resolved.isObject()) {
throw invalid("Properties must be an object.");
}
CfnPropertyTypes.rejectUnknownMembers(TYPE, resolved);
if (resolved.has("Id")) {
throw invalid("Unknown property: Id");
}
rejectNullDestinationBlocks(resolved.path("EventDestination"));
JsonNode props = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(TYPE, resolved);
String set = requiredText(props, "ConfigurationSetName");
JsonNode definition = props.path("EventDestination");
if (!definition.isObject()) {
throw invalid("EventDestination must be an object.");
}
validateNonblankRequiredValues(definition);
String explicitName = optionalText(definition, "Name");
Address prior = priorAddress(resource, ctx);
String name = explicitName != null && !explicitName.isBlank() ? explicitName
: prior != null && "generated".equals(resource.getAttributes().get(NAME_MODE_ATTR))
? prior.name() : ctx.generatePhysicalName(resource.getLogicalId(), 64, false);
Address target = new Address(set, name, ctx.region());
EventDestination destination = destination(definition, name);
deletePending(resource);
boolean replacement = prior == null || !prior.equals(target);
ObjectNode snapshot = ctx.isUpdate() ? snapshot(resource, prior, target, ctx) : null;
if (snapshot != null && !replacement) {
EventDestination previous = find(prior);
snapshot.set("previous", MAPPER.valueToTree(previous));
resource.getAttributes().put(UPDATE_ATTR, snapshot.toString());
configurationSets.updateEventDestination(set, name, destination, ctx.accountId(), ctx.region(), true);
} else {
if (snapshot != null) {
resource.getAttributes().put(UPDATE_ATTR, snapshot.toString());
}
configurationSets.createEventDestination(set, name, destination, ctx.accountId(), ctx.region(), true);
if (snapshot != null) {
snapshot.put("created", true);
resource.getAttributes().put(UPDATE_ATTR, snapshot.toString());
if (prior != null) {
CfnLifecycleRecords.setCleanup(resource, CLEANUP_ATTR, address(prior), true);
}
}
}
resource.setPhysicalId(name);
resource.getAttributes().put("Id", name);
resource.getAttributes().put(SET_ATTR, set);
resource.getAttributes().put(NAME_MODE_ATTR, explicitName == null || explicitName.isBlank()
? "generated" : "explicit");
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
}
private Address priorAddress(StackResource resource, ProvisionContext ctx) {
if (!ctx.isUpdate()) {
return null;
}
String set = resource.getAttributes().get(SET_ATTR);
if (set == null) {
if (!CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), resource.getAttributes())) {
throw new IllegalStateException("Missing SES event destination address for "
+ resource.getLogicalId());
}
return null;
}
return new Address(set, ctx.priorPhysicalId(), ctx.region());
}
private EventDestination find(Address address) {
return configurationSets.getEventDestinations(address.set(), address.region()).stream()
.filter(destination -> address.name().equals(destination.getName()))
.findFirst().orElseThrow(() -> new AwsException("NotFoundException",
"SES event destination " + address.name() + " does not exist.", 404));
}
private static EventDestination destination(JsonNode definition, String name) {
ObjectNode normalized = ((ObjectNode) definition).deepCopy();
if (normalized.get("SnsDestination") instanceof ObjectNode sns) {
rename(sns, "TopicARN", "TopicArn");
}
if (normalized.get("KinesisFirehoseDestination") instanceof ObjectNode firehose) {
rename(firehose, "IAMRoleARN", "IamRoleArn");
rename(firehose, "DeliveryStreamARN", "DeliveryStreamArn");
}
try {
EventDestination destination = MAPPER.treeToValue(normalized, EventDestination.class);
destination.setName(name);
return destination;
} catch (JsonProcessingException failure) {
throw invalid("Invalid EventDestination: " + failure.getOriginalMessage());
}
}
private static void rejectNullDestinationBlocks(JsonNode definition) {
if (!definition.isObject()) {
return;
}
for (String key : new String[] {"SnsDestination", "KinesisFirehoseDestination",
"EventBridgeDestination", "CloudWatchDestination"}) {
if (definition.path(key).isNull()) {
throw invalid(key + " must be an object.");
}
}
if (definition.path("CloudWatchDestination").path("DimensionConfigurations").isNull()) {
throw invalid("DimensionConfigurations must be an array.");
}
JsonNode dimensions = definition.path("CloudWatchDestination").path("DimensionConfigurations");
if (dimensions.isArray()) {
for (JsonNode dimension : dimensions) {
if (dimension.isNull()) {
throw invalid("DimensionConfigurations entries must be objects.");
}
}
}
}
private static void validateNonblankRequiredValues(JsonNode definition) {
// HandlerReader checks schema types and missing members; these reject blank strings and nulls it omits.
if (!definition.has("MatchingEventTypes")) {
throw invalid("MatchingEventTypes is required.");
}
if (definition.path("SnsDestination").isObject()) {
requiredText(definition.get("SnsDestination"), "TopicARN");
}
if (definition.path("KinesisFirehoseDestination").isObject()) {
requiredText(definition.get("KinesisFirehoseDestination"), "IAMRoleARN");
requiredText(definition.get("KinesisFirehoseDestination"), "DeliveryStreamARN");
}
if (definition.path("EventBridgeDestination").isObject()) {
requiredText(definition.get("EventBridgeDestination"), "EventBusArn");
}
JsonNode dimensions = definition.path("CloudWatchDestination").path("DimensionConfigurations");
if (dimensions.isArray()) {
for (JsonNode dimension : dimensions) {
requiredText(dimension, "DimensionName");
requiredText(dimension, "DimensionValueSource");
requiredText(dimension, "DefaultDimensionValue");
}
}
}
private static void rename(ObjectNode node, String from, String to) {
JsonNode value = node.remove(from);
if (value != null) {
node.set(to, value);
}
}
private static ObjectNode snapshot(StackResource resource, Address prior, Address target, ProvisionContext ctx) {
ObjectNode snapshot = MAPPER.createObjectNode();
snapshot.put("physicalId", resource.getPhysicalId());
snapshot.put("accountId", ctx.accountId());
snapshot.put("replacement", prior == null || !prior.equals(target));
snapshot.set("attributes", MAPPER.valueToTree(resource.getAttributes()));
snapshot.set("target", address(target));
if (prior != null) {
snapshot.set("prior", address(prior));
}
return snapshot;
}
private record Address(String set, String name, String region) { }
private static ObjectNode address(Address address) {
return MAPPER.createObjectNode().put("set", address.set()).put("name", address.name())
.put("region", address.region());
}
private static Address address(JsonNode node) {
return new Address(node.path("set").asText(), node.path("name").asText(),
node.path("region").asText());
}
private void delete(Address address) {
CfnDeletes.safeDelete("SES event destination", address.name(),
() -> configurationSets.deleteEventDestination(address.set(), address.name(), address.region()),
"NotFoundException", "ConfigurationSetDoesNotExist");
}
@Override
public void delete(StackResource resource, String region) {
ObjectNode snapshot = read(resource, UPDATE_ATTR);
if (snapshot != null && snapshot.path("replacement").asBoolean()
&& snapshot.path("created").asBoolean()) {
delete(address(snapshot.path("target")));
}
if (snapshot != null && snapshot.has("prior")) {
delete(address(snapshot.path("prior")));
} else if (snapshot == null && resource.getAttributes().containsKey(SET_ATTR)) {
delete(new Address(resource.getAttributes().get(SET_ATTR), resource.getPhysicalId(), region));
}
deletePending(resource);
resource.getAttributes().remove(UPDATE_ATTR);
}
private void deletePending(StackResource resource) {
ObjectNode pending = read(resource, CLEANUP_ATTR);
CfnLifecycleRecords.deletePending(resource, CLEANUP_ATTR, pending, true,
record -> delete(address(record)));
}
@Override
public boolean rollbackUpdate(StackResource resource) {
ObjectNode snapshot = read(resource, UPDATE_ATTR);
if (snapshot == null) {
return true;
}
if (snapshot.path("replacement").asBoolean()) {
if (snapshot.path("created").asBoolean()) {
delete(address(snapshot.path("target")));
}
resource.getAttributes().remove(CLEANUP_ATTR);
} else {
Address prior = address(snapshot.path("prior"));
try {
EventDestination previous = MAPPER.treeToValue(snapshot.path("previous"), EventDestination.class);
configurationSets.updateEventDestination(prior.set(), prior.name(), previous,
snapshot.path("accountId").asText(), prior.region(), true);
} catch (JsonProcessingException failure) {
throw new IllegalStateException("Invalid SES event destination update snapshot", failure);
}
}
resource.setPhysicalId(snapshot.path("physicalId").asText(null));
resource.getAttributes().clear();
snapshot.path("attributes").fields().forEachRemaining(entry ->
resource.getAttributes().put(entry.getKey(), entry.getValue().asText()));
return true;
}
@Override
public boolean retainsFailedUpdateState(StackResource resource) {
return resource.getAttributes().containsKey(UPDATE_ATTR);
}
@Override
public boolean requiresUpdateRecovery(StackResource resource) {
return "UPDATE_FAILED".equals(resource.getStatus()) && retainsFailedUpdateState(resource);
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return resource.getAttributes().containsKey(CLEANUP_ATTR);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
ObjectNode pending = read(resource, CLEANUP_ATTR);
return CfnLifecycleRecords.cleanupPhysicalId(resource, pending);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
if (requiresUpdateRecovery(resource)) {
return new UpdateCleanupResult(true, false, resource.getPhysicalId(), 0,
"SES event destination rollback is pending.");
}
return completePending(resource);
}
private UpdateCleanupResult completePending(StackResource resource) {
ObjectNode pending = read(resource, CLEANUP_ATTR);
return CfnLifecycleRecords.completePending(resource, CLEANUP_ATTR, UPDATE_ATTR, pending, true,
record -> delete(address(record)));
}
@Override
public UpdateCleanupResult completeDeleteCleanup(StackResource resource) {
ObjectNode pending = read(resource, CLEANUP_ATTR);
if (pending == null) {
return UpdateCleanupResult.notApplicable();
}
return completePending(resource);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(UPDATE_ATTR);
}
private static ObjectNode read(StackResource resource, String attribute) {
return CfnLifecycleRecords.read(resource, attribute,
"Invalid SES event destination lifecycle record",
"SES event destination lifecycle record must be an object");
}
private static String requiredText(JsonNode node, String key) {
String value = optionalText(node, key);
if (value == null || value.isBlank()) {
throw invalid(key + " must be a nonempty string.");
}
return value;
}
private static String optionalText(JsonNode node, String key) {
JsonNode value = node.get(key);
if (value == null || value.isNull()) {
return null;
}
if (!value.isTextual()) {
throw invalid(key + " must be a string.");
}
return value.textValue();
}
private static AwsException invalid(String message) {
return new AwsException("ValidationError", message, 400);
}
}
@@ -159,22 +159,13 @@ public class SesReceiptRuleCfnProvisioner implements CfnResourceProvisioner {
}
private static void setCleanup(StackResource resource, Identity identity, String region, boolean retainable) {
resource.getAttributes().put(CLEANUP_ATTR,
address(identity, region).put("retainable", retainable).put("attempts", 0).toString());
CfnLifecycleRecords.setCleanup(resource, CLEANUP_ATTR, address(identity, region), retainable);
}
private void deletePending(StackResource resource) {
ObjectNode pending = read(resource, CLEANUP_ATTR);
if (pending != null) {
if (!retained(resource, pending)) {
delete(identity(pending), pending.path("region").asText());
}
resource.getAttributes().remove(CLEANUP_ATTR);
}
}
private static boolean retained(StackResource resource, JsonNode pending) {
return pending.path("retainable").asBoolean() && "Retain".equals(resource.getUpdateReplacePolicy());
CfnLifecycleRecords.deletePending(resource, CLEANUP_ATTR, pending, true,
record -> delete(identity(record), record.path("region").asText()));
}
@Override
@@ -234,7 +225,7 @@ public class SesReceiptRuleCfnProvisioner implements CfnResourceProvisioner {
@Override
public String updateCleanupPhysicalId(StackResource resource) {
ObjectNode pending = read(resource, CLEANUP_ATTR);
return pending == null || retained(resource, pending) ? null : pending.path("name").asText();
return CfnLifecycleRecords.cleanupPhysicalId(resource, pending);
}
@Override
@@ -248,20 +239,8 @@ public class SesReceiptRuleCfnProvisioner implements CfnResourceProvisioner {
@Override
public UpdateCleanupResult completeDeleteCleanup(StackResource resource) {
ObjectNode pending = read(resource, CLEANUP_ATTR);
if (pending == null) {
return retainsFailedUpdateState(resource) ? new UpdateCleanupResult(true, true, null, 0, null)
: UpdateCleanupResult.notApplicable();
}
String name = pending.path("name").asText();
try {
deletePending(resource);
return new UpdateCleanupResult(true, true, name, 0, null);
} catch (RuntimeException failure) {
int attempts = pending.path("attempts").asInt() + 1;
pending.put("attempts", attempts);
resource.getAttributes().put(CLEANUP_ATTR, pending.toString());
return new UpdateCleanupResult(true, false, name, attempts, failure.getMessage());
}
return CfnLifecycleRecords.completePending(resource, CLEANUP_ATTR, UPDATE_ATTR, pending, true,
record -> delete(identity(record), record.path("region").asText()));
}
@Override
@@ -270,19 +249,8 @@ public class SesReceiptRuleCfnProvisioner implements CfnResourceProvisioner {
}
private static ObjectNode read(StackResource resource, String key) {
String raw = resource.getAttributes().get(key);
if (raw == null) {
return null;
}
try {
JsonNode node = MAPPER.readTree(raw);
if (node.isObject()) {
return (ObjectNode) node;
}
} catch (JsonProcessingException e) {
throw new IllegalStateException("Invalid SES receipt rule lifecycle record", e);
}
throw new IllegalStateException("Invalid SES receipt rule lifecycle record");
String error = "Invalid SES receipt rule lifecycle record";
return CfnLifecycleRecords.read(resource, key, error, error);
}
private static ReceiptRule parseRule(JsonNode node) {