refactor(cloudformation): replace the retired monolith with CfnResourceDispatcher (#4269)

* refactor(cloudformation): replace the retired monolith with CfnResourceDispatcher

CloudFormationResourceProvisioner was the monolith that held every AWS::
provisioning arm. With the per-service migration complete it kept no arm:
LEGACY_SWITCH_TYPES and DELETE_NEEDS_STACK_RESOURCE were empty sets, five
private helpers duplicated ProvisionContext, six imports were unused, and its
UPDATE_ROLLBACK_* constants only re-exported CfnRollback. What it still did is
small: route provision and delete to the registry, stub a type nothing serves
(or refuse it in strict mode), answer the engine's update-lifecycle questions
through the owning provisioner, and give Cloud Control its stack-less entry
points.

That is now CfnResourceDispatcher in provisioners/, behaviour unchanged: the
same stub arm, warn lines, status reasons and strict-mode failure, with the
same logger category the unsupported-type test binds to. The dead overloads
go with the class (the 8-arg provision, the unused accountId on delete, the
short deleteStandalone forms). CloudFormationTemplateEngine gains a public
standalone(...) factory so the dispatcher can build Cloud Control's throwaway
engine from outside the package while the constructors stay package-private
for the tests that mock it. CloudFormationService reads the rollback markers
from CfnRollback directly.

The empty guards leave with the class: CfnDeletePrecedenceTest read only the
empty set, and CfnResourceInventoryTest no longer folds a legacy owner into
the inventory (the checked-in file had no such row). Javadocs that described
the switch as still present now describe the registry.

CfnResourceDispatcherTest pins the standalone engine's dynamic-reference
resolver, the prior identity reaching the ProvisionContext, and the
whole-resource delete form; every other test only changed the type it names.

* chore(cloudformation): retire the legacy-switch guards from tooling and instructions

The switch is gone, so nothing can carry a LEGACY_SWITCH owner: the schema
coverage test drops its skip, the docs generator's double-ownership check
generalises to any type with two provisioners, and its fixtures name real
owners. AGENTS.md and CONTRIBUTING.md tell contributors where types live
instead of warning them off a class that no longer exists.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-23 22:31:27 -04:00
1 parent 239f560d97
commit 69ceb976c7
68 files changed
+590 -673

No files matched your search

@@ -20,7 +20,7 @@ import java.net.URI;
* <li>{@link LaunchedContainerAwsEnv}, which sets the AWS endpoint for Lambda, ECS, Flink and MWAA
* containers</li>
* <li>{@code Ec2ContainerManager}, for the {@code AWS_ENDPOINT_URL} of EC2 instance containers</li>
* <li>{@code CloudFormationResourceProvisioner}, for the {@code ResponseURL} a custom resource
* <li>{@code CustomResourceCfnProvisioner}, for the {@code ResponseURL} a custom resource
* Lambda PUTs its result to</li>
* </ul>
*
@@ -10,8 +10,8 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationResourceProvisioner;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;
import io.github.hectorvent.floci.services.ec2.model.Instance;
@@ -51,7 +51,7 @@ public class CloudControlService {
private final S3Service s3Service;
private final Ec2Service ec2Service;
private final IamService iamService;
private final CloudFormationResourceProvisioner provisioner;
private final CfnResourceDispatcher provisioner;
private final ObjectMapper mapper;
private final AccountAwareStorageBackend<PersistedRequest> requestStore;
private final AccountAwareStorageBackend<PersistedCreatedResource> createdStore;
@@ -181,7 +181,7 @@ public class CloudControlService {
@Inject
public CloudControlService(S3Service s3Service, Ec2Service ec2Service,
IamService iamService, CloudFormationResourceProvisioner provisioner,
IamService iamService, CfnResourceDispatcher provisioner,
ObjectMapper mapper, StorageFactory storageFactory) {
this(s3Service, ec2Service, iamService, provisioner, mapper,
storageFactory.create("cloudcontrol", "cloudcontrol-requests.json",
@@ -191,7 +191,7 @@ public class CloudControlService {
}
public CloudControlService(S3Service s3Service, Ec2Service ec2Service,
IamService iamService, CloudFormationResourceProvisioner provisioner,
IamService iamService, CfnResourceDispatcher provisioner,
ObjectMapper mapper) {
this(s3Service, ec2Service, iamService, provisioner, mapper,
AccountAwareStorageBackend.inMemory(DEFAULT_ACCOUNT),
@@ -199,7 +199,7 @@ public class CloudControlService {
}
CloudControlService(S3Service s3Service, Ec2Service ec2Service,
IamService iamService, CloudFormationResourceProvisioner provisioner,
IamService iamService, CfnResourceDispatcher provisioner,
ObjectMapper mapper,
AccountAwareStorageBackend<PersistedRequest> requestStore,
AccountAwareStorageBackend<PersistedCreatedResource> createdStore) {
@@ -340,7 +340,7 @@ public class CloudControlService {
}
RequestScopes.runAs(accountId,
() -> provisioner.deleteStandalone(typeName, identifier, region, accountId, attributes));
() -> provisioner.deleteStandalone(typeName, identifier, region, attributes));
created.remove(key);
removePersistedCreated(accountId, region, typeName, identifier);
return record(new ProgressEvent(typeName, identifier,
@@ -1,414 +0,0 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
import io.github.hectorvent.floci.services.cloudformation.provisioners.OpenApiDocuments;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ReplacementCleanup;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.UpdateCleanupResult;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.github.hectorvent.floci.services.pipes.model.DesiredState;
import io.github.hectorvent.floci.services.ssm.model.Parameter;
import io.github.hectorvent.floci.services.apigatewayv2.model.*;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.*;
import java.util.function.Consumer;
import java.util.regex.Pattern;
/**
* Provisions individual CloudFormation resource types using Floci's existing service implementations.
*/
@ApplicationScoped
public class CloudFormationResourceProvisioner {
private static final Logger LOG = Logger.getLogger(CloudFormationResourceProvisioner.class);
static final String UPDATE_ROLLBACK_RESTORED_ATTR = CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR;
static final String UPDATE_ROLLBACK_FAILURE_ATTR = CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR;
private static final int GENERATED_NAME_SUFFIX_LENGTH = 12;
/**
* Types whose delete needs the whole {@link StackResource}, not just its physical id, because a
* create-time attribute or stashed state identifies what to remove. Now empty: every such type
* moved to a per-service provisioner that overrides {@code delete(StackResource, String)}. Kept
* as the gate {@code CfnDeletePrecedenceTest} checks, which fails if a type is ever both listed
* here and served by the registry.
*/
static final Set<String> DELETE_NEEDS_STACK_RESOURCE = Set.of();
/**
* Resource types still served by the switch in {@link #provision} rather than the registry. Now
* empty: every type moved to a per-service provisioner. Kept as the guard that fails loudly,
* rather than silently stubbing, if an arm is ever removed without clearing its entry, and kept
* in step with the registry by {@code CfnResourceInventoryTest}.
*/
static final Set<String> LEGACY_SWITCH_TYPES = Set.of();
private final ObjectMapper objectMapper;
// Item 15 decomposition: every resource type now has a per-service provisioner reached through
// the registry, so the switch below serves no type and only stubs or rejects the unknown. The
// last type-specific service deps left with the types they served; what remains is what the
// dispatch itself needs.
private final CloudFormationResourceRegistry resourceRegistry;
private final CfnDynamicReferences dynamicReferences;
private final EmulatorConfig config;
@Inject
public CloudFormationResourceProvisioner(ObjectMapper objectMapper,
CloudFormationResourceRegistry resourceRegistry,
CfnDynamicReferences dynamicReferences,
EmulatorConfig config) {
this.config = config;
this.objectMapper = objectMapper;
this.resourceRegistry = resourceRegistry;
this.dynamicReferences = dynamicReferences;
}
/**
* Provisions a single resource. Returns the populated StackResource (physicalId + attributes set).
*
* <p>A resource type with no provisioner is stubbed: a synthetic physical id, an
* {@code arn:aws:stub:::} ARN attribute and {@code CREATE_COMPLETE}, logged at warn and
* carrying a status reason saying nothing was created. With
* {@code floci.services.cloudformation.allow-stub-unsupported-resource-types} off it comes back
* {@code CREATE_FAILED} instead, with no physical id.
*/
public StackResource provision(String logicalId, String resourceType, JsonNode properties,
CloudFormationTemplateEngine engine, String region, String accountId,
String stackName) {
return provision(logicalId, resourceType, properties, engine, region, accountId, stackName, null);
}
public StackResource provision(String logicalId, String resourceType, JsonNode properties,
CloudFormationTemplateEngine engine, String region, String accountId,
String stackName, String existingPhysicalId) {
return provision(logicalId, resourceType, properties, engine, region, accountId, stackName,
existingPhysicalId, Map.of());
}
public StackResource provision(String logicalId, String resourceType, JsonNode properties,
CloudFormationTemplateEngine engine, String region, String accountId,
String stackName, String existingPhysicalId,
Map<String, String> existingAttributes) {
return provision(logicalId, resourceType, properties, engine, region, accountId, stackName,
existingPhysicalId, existingAttributes, event -> {});
}
public StackResource provision(String logicalId, String resourceType, JsonNode properties,
CloudFormationTemplateEngine engine, String region, String accountId,
String stackName, String existingPhysicalId,
Map<String, String> existingAttributes, Consumer<StackEvent> progress) {
StackResource resource = new StackResource();
resource.setLogicalId(logicalId);
resource.setResourceType(resourceType);
resource.setPhysicalId(existingPhysicalId);
resource.setAttributes(new HashMap<>(existingAttributes != null ? existingAttributes : Map.of()));
try {
CfnResourceProvisioner extracted = resourceRegistry.forType(resourceType).orElse(null);
if (extracted != null) {
extracted.provision(resource, properties,
new ProvisionContext(engine, region, accountId, stackName, existingPhysicalId, progress));
resource.setStatus("CREATE_COMPLETE");
return resource;
}
switch (resourceType) {
default -> {
if (LEGACY_SWITCH_TYPES.contains(resourceType)) {
// A declared legacy type reaching the default arm means its case was removed
// without removing its LEGACY_SWITCH_TYPES entry (or without registering a
// provisioner). Stubbing it would report CREATE_COMPLETE with a fake ARN and
// hide the mistake, so fail instead.
throw new IllegalStateException("No switch arm for declared legacy type "
+ resourceType + ", remove its LEGACY_SWITCH_TYPES entry when it "
+ "moves to a per-service provisioner.");
} else if (!stubUnsupportedResourceTypesAllowed()) {
// Before the physical id below is assigned, so the Cloud Control path sees
// a resource with none and reports this message rather than a success. On
// the stack path the catch below turns it into CREATE_FAILED with the same
// sentence, which rolls the stack back.
throw new AwsException("ValidationError",
unsupportedResourceTypeMessage(resourceType), 400);
} else {
// Warn, not debug, and a status reason on the resource: the stub reports
// CREATE_COMPLETE while creating nothing, so without both the stack is
// indistinguishable from one where every resource was really provisioned.
// The reason reaches DescribeStackEvents through the event
// CloudFormationService already builds from it.
LOG.warnv("Stubbing unsupported resource type {0} ({1}): nothing is created "
+ "for it. Set floci.services.cloudformation."
+ "allow-stub-unsupported-resource-types=false to fail the "
+ "stack instead.",
resourceType, logicalId);
resource.setStatusReason(unsupportedResourceTypeMessage(resourceType)
+ " It was stubbed and nothing was created for it.");
resource.setPhysicalId(logicalId + "-" + UUID.randomUUID().toString().substring(0, 8));
resource.getAttributes().put("Arn", "arn:aws:stub:::" + logicalId);
}
}
}
resource.setStatus("CREATE_COMPLETE");
} catch (Exception e) {
LOG.warnv("Failed to provision {0} ({1}): {2}", resourceType, logicalId, e.getMessage());
resource.setStatus("CREATE_FAILED");
resource.setStatusReason(e.getMessage());
}
return resource;
}
/**
* Whether a resource type with no provisioner may be stubbed. The provisioners hand-built in
* unit tests carry no config; absent configuration means the documented default, which here is
* the lenient behaviour, so the test reads {@code config == null ||}.
*/
private boolean stubUnsupportedResourceTypesAllowed() {
return config == null || config.services().cloudformation().allowStubUnsupportedResourceTypes();
}
/** The one sentence Floci says about a resource type it has no provisioner for. */
static String unsupportedResourceTypeMessage(String resourceType) {
return "Resource type " + resourceType + " is not supported by Floci.";
}
/**
* Provision a single resource with no enclosing CloudFormation stack, the Cloud Control
* {@code CreateResource} path. Cloud Control DesiredState carries resolved values (no
* intrinsics), so a minimal template engine suffices. Reuses the same 114-type provisioning
* that CloudFormation stacks use, so any type a stack can create, Cloud Control can too.
*/
public StackResource provisionStandalone(String resourceType, JsonNode properties, String region, String accountId) {
CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine(
accountId, region, "cloudcontrol", "cloudcontrol",
Map.of(), new HashMap<>(), new HashMap<>(), Map.of(), Map.of(), objectMapper, name -> null,
value -> dynamicReferences.resolveDynamicReferences(value, region, false));
return provision("resource", resourceType, properties, engine, region, accountId, "cloudcontrol");
}
/** Delete a resource by type + physical id, the Cloud Control {@code DeleteResource} path. */
public void deleteStandalone(String resourceType, String identifier, String region) {
deleteStandalone(resourceType, identifier, region, Map.of());
}
/**
* As above, with the attributes recorded when the resource was created. Custom resources, EKS
* nodegroups and IAM inline policies cannot be deleted from type and physical id alone, so
* without these their delete silently no-ops.
*/
public void deleteStandalone(String resourceType, String identifier, String region,
Map<String, String> attributes) {
deleteStandalone(resourceType, identifier, region, "000000000000", attributes);
}
/** Account-aware standalone delete used by Cloud Control. */
public void deleteStandalone(String resourceType, String identifier, String region,
String accountId, Map<String, String> attributes) {
StackResource resource = new StackResource();
resource.setResourceType(resourceType);
resource.setPhysicalId(identifier);
resource.setAttributes(new HashMap<>(attributes == null ? Map.of() : attributes));
delete(resource, region, accountId);
}
/**
* Deletes a provisioned resource. Custom resources are re-invoked with {@code RequestType=Delete}
* (using the ServiceToken + properties stashed at create time); everything else delegates to the
* type-keyed {@link #delete(String, String, String)}.
*/
public void delete(StackResource resource, String region) {
delete(resource, region, "000000000000");
}
public void delete(StackResource resource, String region, String accountId) {
String resourceType = resource.getResourceType();
// Registry first. An extracted provisioner owns its type outright, and gets the whole
// resource so an attribute-aware delete can read its create-time attributes. Consulting it
// ahead of the branches below means an exact match always beats the Custom:: prefix branch
// (which is how Custom::DynamoDBReplica moved to DynamoDbCfnProvisioner), and that migrating one of the
// DELETE_NEEDS_STACK_RESOURCE types cannot silently keep using the stale branch here.
CfnResourceProvisioner extractedForDelete = resourceRegistry.forType(resourceType).orElse(null);
if (extractedForDelete != null) {
extractedForDelete.delete(resource, region);
return;
}
delete(resourceType, resource.getPhysicalId(), region);
}
/**
* Deletes a single resource by type + physical id. Failures propagate to the caller
* (CloudFormationService#deleteStackResources) so the stack transitions to DELETE_FAILED,
* matching AWS, e.g. deleting a non-empty S3 bucket raises BucketNotEmpty and must not be
* silently reported as a successful stack deletion. Resource types that AWS itself treats
* leniently keep their dedicated handling: the {@code *Safe} helpers below swallow expected
* conflicts, and KMS keys are intentionally left for scheduled deletion.
*/
public void delete(String resourceType, String physicalId, String region) {
CfnResourceProvisioner extracted = resourceRegistry.forType(resourceType).orElse(null);
if (extracted != null) {
extracted.delete(resourceType, physicalId, region);
return;
}
switch (resourceType) {
// Warn for the same reason the create path does: the delete reports success over a
// type nothing here removes, and at debug that is invisible at the default log level.
// The line names the physical id without claiming a resource survives it: this arm
// takes both a type the create switch provisioned and one it only stubbed, and only
// the first leaves something behind.
default -> LOG.warnv("No delete implemented for resource type {0}: {1} is not removed "
+ "here.", resourceType, physicalId);
}
}
/**
* One attempt at deleting what this update's replacement displaced, delegated to the
* provisioner that owns the type. Step Functions was the last type answering here without an
* extracted provisioner, so this is now pure delegation.
*/
UpdateCleanupResult completeUpdate(StackResource resource) {
return resourceRegistry.forType(resource.getResourceType())
.map(owner -> owner.completeUpdate(resource))
.filter(UpdateCleanupResult::applicable)
.orElseGet(UpdateCleanupResult::notApplicable);
}
/**
* The physical id this update displaced, announced as DELETE_IN_PROGRESS before the stack
* update closes. A type whose {@code UpdateReplacePolicy} is {@code Retain} owes no cleanup.
*/
String updateCleanupPhysicalId(StackResource resource) {
if ("Retain".equals(resource.getUpdateReplacePolicy())) {
return null;
}
return resourceRegistry.forType(resource.getResourceType())
.map(owner -> owner.updateCleanupPhysicalId(resource))
.orElse(null);
}
/** Only an opted-in provisioner may identify cleanup owed by an UPDATE_FAILED resource. */
boolean hasPendingRollbackCleanup(StackResource resource) {
return resourceRegistry.forType(resource.getResourceType())
.map(owner -> owner.hasPendingRollbackCleanup(resource))
.orElse(false);
}
/** Only an opted-in provisioner may keep a failed update attempt in place of the previous resource. */
boolean retainsFailedUpdateState(StackResource resource) {
return resourceRegistry.forType(resource.getResourceType())
.map(owner -> owner.retainsFailedUpdateState(resource))
.orElse(false);
}
/**
* Whether this update replaced the resource's physical entity, so the stack has cleanup
* pending.
*/
boolean hasReplacementUpdate(StackResource resource) {
return resourceRegistry.forType(resource.getResourceType())
.map(owner -> owner.hasReplacementUpdate(resource))
.orElse(false);
}
/** Drops the cleanup bookkeeping this update left on the resource. */
void clearUpdate(StackResource resource) {
resourceRegistry.forType(resource.getResourceType())
.ifPresent(owner -> owner.clearUpdate(resource));
}
/**
* Puts the physical entity back to its pre-update configuration when a later resource fails
* the stack update, delegated to the provisioner that owns the type.
*/
boolean rollbackUpdate(StackResource resource) {
return rollbackUpdate(resource, event -> {});
}
boolean rollbackUpdate(StackResource resource, Consumer<StackEvent> progress) {
return resourceRegistry.forType(resource.getResourceType())
.map(owner -> owner.rollbackUpdate(resource, progress))
.orElse(false);
}
/**
* Carries ownership discovered by a failed update onto the last known-good resource metadata
* that CloudFormation restores. Only additive cleanup tracking belongs here; normal attempted
* attributes must not overwrite the committed resource state.
*/
void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) {
// Any provisioner using ReplacementCleanup: an entity the failed attempt created and could
// not remove is owed to the next cleanup, which runs on the restored resource.
ReplacementCleanup.mergeDisplaced(previous, attempted);
if (!Objects.equals(previous.getResourceType(), attempted.getResourceType())) {
return;
}
// Extracted provisioners that track their own generated sub-resources (ApiGatewayV2's Api
// body routes/integrations/authorizers) carry that tracking forward themselves.
resourceRegistry.forType(previous.getResourceType())
.ifPresent(owner -> owner.mergeFailedUpdateResourceTracking(previous, attempted));
}
// ── Helpers ───────────────────────────────────────────────────────────────
private static String textOrNull(JsonNode node, String field) {
return node != null && node.hasNonNull(field) ? node.path(field).asText() : null;
}
private String resolveOptional(JsonNode props, String name, CloudFormationTemplateEngine engine) {
if (props == null || !props.has(name) || props.get(name).isNull()) {
return null;
}
return engine.resolve(props.get(name));
}
/**
* Resolves CloudFormation dynamic references in a provisioned property value. Delegates to
* {@link CfnDynamicReferences}. {@code allowSsmSecure} is {@code true} only for the RDS
* master-credential properties resolved here directly; every other property value reaches
* {@link CfnDynamicReferences} through {@link CloudFormationTemplateEngine#resolveNode}, which
* disallows {@code ssm-secure} the same way the general path does.
*/
private String resolveDynamicReferences(String value, String region, boolean allowSsmSecure) {
return dynamicReferences.resolveDynamicReferences(value, region, allowSsmSecure);
}
private String resolveOrDefault(JsonNode props, String name,
CloudFormationTemplateEngine engine, String defaultValue) {
String value = resolveOptional(props, name, engine);
return (value != null && !value.isBlank()) ? value : defaultValue;
}
/**
* Generate an AWS-like physical name: {stackName}-{logicalId}-{randomSuffix}.
* Mirrors the naming pattern AWS CloudFormation uses when no explicit name is provided.
*/
private String generatePhysicalName(String stackName, String logicalId, int maxLength, boolean lowercase) {
String suffix = UUID.randomUUID().toString().replace("-", "")
.substring(0, GENERATED_NAME_SUFFIX_LENGTH);
String base = stackName + "-" + logicalId;
if (lowercase) {
base = base.toLowerCase();
}
String name = base + "-" + suffix;
if (maxLength > 0 && name.length() > maxLength) {
// Truncate the descriptive prefix but always keep the trailing uniqueness token. When a
// stack's name approaches the length limit, distinct logical resources still get distinct
// physical names, CloudFormation preserves the random suffix when it shortens a generated
// name. Truncating the whole string (suffix included) would collapse every such resource
// onto one name and break Ref/GetAtt-based lookup (e.g. a custom resource's ServiceToken
// resolving to the wrong Lambda).
int keep = Math.max(0, maxLength - suffix.length() - 1);
String prefix = base.length() > keep ? base.substring(0, keep) : base;
while (prefix.endsWith("-")) {
prefix = prefix.substring(0, prefix.length() - 1);
}
name = prefix.isEmpty() ? suffix : prefix + "-" + suffix;
}
return name;
}
}
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.model.TemplateSummary;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.cloudformation.provisioners.UpdateCleanupResult;
import io.github.hectorvent.floci.services.s3.S3Service;
@@ -77,7 +78,7 @@ public class CloudFormationService implements ResourceProvider {
new ThreadPoolExecutor.AbortPolicy());
}
private final CloudFormationResourceProvisioner provisioner;
private final CfnResourceDispatcher dispatcher;
private final S3Service s3Service;
private final SsmService ssmService;
private final CfnDynamicReferences dynamicReferences;
@@ -96,12 +97,12 @@ public class CloudFormationService implements ResourceProvider {
@Inject
public CloudFormationService(CloudFormationResourceProvisioner provisioner, S3Service s3Service,
public CloudFormationService(CfnResourceDispatcher dispatcher, S3Service s3Service,
SsmService ssmService, CfnDynamicReferences dynamicReferences,
ObjectMapper objectMapper, EmulatorConfig config,
RegionResolver regionResolver, Clock clock,
StorageFactory storageFactory) {
this.provisioner = provisioner;
this.dispatcher = dispatcher;
this.s3Service = s3Service;
this.ssmService = ssmService;
this.dynamicReferences = dynamicReferences;
@@ -1325,7 +1326,7 @@ public class CloudFormationService implements ResourceProvider {
props.isMissingNode() ? null : props,
engine, region, accountId, isCreate, previousResource);
} else {
resource = provisioner.provision(logicalId, type, props.isMissingNode() ? null : props,
resource = dispatcher.provision(logicalId, type, props.isMissingNode() ? null : props,
engine, region, accountId, stack.getStackName(),
resource.getPhysicalId(), resource.getAttributes(),
event -> addEvent(stack, logicalId, event.getPhysicalResourceId(), type,
@@ -1357,21 +1358,21 @@ public class CloudFormationService implements ResourceProvider {
// A provisioner that keeps the failed attempt's identity and tracking for
// its own rollback is not restored here; the rollback walker owns it.
if (!isCreate && previousResource != null
&& !provisioner.retainsFailedUpdateState(resource)) {
&& !dispatcher.retainsFailedUpdateState(resource)) {
// Provisioners work on a copy of the stored resource metadata. Keep the
// last known-good identity and status when an update attempt fails so a
// later retry or stack deletion still manages the original resource.
// Preserve any additional resources that the failed attempt could not
// clean up, otherwise restoring this object would orphan them.
provisioner.mergeFailedUpdateResourceTracking(previousResource, resource);
dispatcher.mergeFailedUpdateResourceTracking(previousResource, resource);
String rollbackFailure = resource.getAttributes().get(
CloudFormationResourceProvisioner.UPDATE_ROLLBACK_FAILURE_ATTR);
CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR);
if (rollbackFailure == null) {
// The rollback walker must know this resource is already restored;
// otherwise an earlier UPDATE_COMPLETE status looks like an
// unhandled mutation and incorrectly becomes ROLLBACK_FAILED.
previousResource.getAttributes().put(
CloudFormationResourceProvisioner.UPDATE_ROLLBACK_RESTORED_ATTR,
CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR,
"true");
} else {
// Restoration was attempted eagerly by the provisioner but did not
@@ -1379,7 +1380,7 @@ public class CloudFormationService implements ResourceProvider {
// rollback walker reports UPDATE_ROLLBACK_FAILED rather than claiming
// the stale snapshot is live.
previousResource.getAttributes().put(
CloudFormationResourceProvisioner.UPDATE_ROLLBACK_FAILURE_ATTR,
CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR,
rollbackFailure);
}
stack.getResources().put(logicalId, previousResource);
@@ -1558,7 +1559,7 @@ public class CloudFormationService implements ResourceProvider {
List<StackResource> resources = resourcesInCreationOrder(stack, region);
Collections.reverse(resources);
for (StackResource resource : resources) {
String cleanupPhysicalId = provisioner.updateCleanupPhysicalId(resource);
String cleanupPhysicalId = dispatcher.updateCleanupPhysicalId(resource);
if (cleanupPhysicalId != null) {
addEvent(
stack,
@@ -1569,7 +1570,7 @@ public class CloudFormationService implements ResourceProvider {
null);
}
while (true) {
UpdateCleanupResult result = provisioner.completeUpdate(resource);
UpdateCleanupResult result = dispatcher.completeUpdate(resource);
if (!result.applicable()) {
break;
}
@@ -1583,7 +1584,7 @@ public class CloudFormationService implements ResourceProvider {
"DELETE_COMPLETE",
null);
}
provisioner.clearUpdate(resource);
dispatcher.clearUpdate(resource);
break;
}
if (result.attempts() < 3) {
@@ -1602,7 +1603,7 @@ public class CloudFormationService implements ResourceProvider {
resource.getResourceType(),
"DELETE_FAILED",
reason);
provisioner.clearUpdate(resource);
dispatcher.clearUpdate(resource);
break;
}
}
@@ -1631,7 +1632,7 @@ public class CloudFormationService implements ResourceProvider {
private boolean hasReplacementUpdates(Stack stack) {
return stack.resourcesSnapshot().values().stream()
.anyMatch(provisioner::hasReplacementUpdate);
.anyMatch(dispatcher::hasReplacementUpdate);
}
private boolean hasRemovedOrConditionFalseResources(Stack stack, JsonNode resources, Map<String, Boolean> conditions) {
@@ -1668,7 +1669,7 @@ public class CloudFormationService implements ResourceProvider {
"AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null);
deleteStackResources(child, region, accountId);
} else {
provisioner.delete(resource, region);
dispatcher.delete(resource, region);
}
}
@@ -1756,17 +1757,17 @@ public class CloudFormationService implements ResourceProvider {
"Resource creation cancelled during update rollback");
removedResources.add(resource.getLogicalId());
} else if (resource.getAttributes().containsKey(
CloudFormationResourceProvisioner.UPDATE_ROLLBACK_FAILURE_ATTR)) {
CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)) {
String reason = resource.getAttributes().remove(
CloudFormationResourceProvisioner.UPDATE_ROLLBACK_FAILURE_ATTR);
CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR);
failures.add(resource.getLogicalId());
resource.setStatus("UPDATE_FAILED");
resource.setStatusReason(reason);
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "UPDATE_FAILED", reason);
} else if ("true".equals(resource.getAttributes().remove(
CloudFormationResourceProvisioner.UPDATE_ROLLBACK_RESTORED_ATTR))
|| provisioner.rollbackUpdate(resource,
CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR))
|| dispatcher.rollbackUpdate(resource,
event -> addEvent(stack, resource.getLogicalId(), event.getPhysicalResourceId(),
resource.getResourceType(), event.getResourceStatus(), event.getResourceStatusReason()))) {
resource.setStatus(previous.getStatus());
@@ -2046,7 +2047,7 @@ public class CloudFormationService implements ResourceProvider {
|| "UPDATE_COMPLETE".equals(resource.getStatus())
|| "DELETE_FAILED".equals(resource.getStatus())
|| ("UPDATE_FAILED".equals(resource.getStatus())
&& provisioner.hasPendingRollbackCleanup(resource));
&& dispatcher.hasPendingRollbackCleanup(resource));
if (resource.getPhysicalId() == null || !deletable) {
continue;
}
@@ -40,6 +40,20 @@ public class CloudFormationTemplateEngine {
private final UnaryOperator<String> dynamicReferenceResolver;
private final List<String> unresolvedIntrinsics = new ArrayList<>();
/**
* A minimal engine for a resource provisioned outside any stack (Cloud Control CreateResource).
* Desired state carries resolved values, so it needs no parameters, mappings, conditions or
* sibling resources: only intrinsics and dynamic references. The constructors stay
* package-private so tests in {@code provisioners/} keep mocking the engine.
*/
public static CloudFormationTemplateEngine standalone(String accountId, String region, String stackName,
ObjectMapper objectMapper,
UnaryOperator<String> dynamicReferenceResolver) {
return new CloudFormationTemplateEngine(accountId, region, stackName, stackName,
Map.of(), new HashMap<>(), new HashMap<>(), Map.of(), Map.of(), objectMapper,
name -> null, dynamicReferenceResolver);
}
CloudFormationTemplateEngine(String accountId, String region, String stackName, String stackId,
Map<String, String> parameters,
Map<String, String> physicalIds,
@@ -14,8 +14,7 @@ import java.util.zip.ZipOutputStream;
* {@code cfn-response} (Node.js) / {@code cfnresponse} (Python) module into ZipFile
* packages so custom-resource handlers can send their CloudFormation callbacks, and
* Solutions-style templates (e.g. Landing Zone Accelerator's installer) rely on it.
* Lives outside {@code CloudFormationResourceProvisioner} so the eventual Lambda
* provisioner extraction can take it along unchanged.</p>
* Kept separate from {@code LambdaCfnProvisioner} so other callers can share it unchanged.</p>
*/
public final class InlineZipPackager {
@@ -471,7 +471,7 @@ class SamTransformProcessor {
/**
* Resolves the SAM authorizer's {@code IdentitySource}, accepting either the documented array
* form or a single scalar string — mirroring
* {@code CloudFormationResourceProvisioner.resolveIdentitySource}, since the raw
* the {@code AWS::ApiGatewayV2::Authorizer} provisioner's own IdentitySource parsing, since the raw
* {@code AWS::ApiGatewayV2::Authorizer} resource this expands to accepts both. SAM itself
* rejects a JWT authorizer with no {@code IdentitySource} ({@code _validate_jwt_authorizer} in
* samtranslator/model/apigatewayv2.py), so an absent or empty value is a template error here
@@ -1371,7 +1371,7 @@ class SamTransformProcessor {
/**
* Converts SAM's string-to-string {@code Tags} map into the {@code {Key, Value}} list
* {@code AWS::StepFunctions::StateMachine} reads (see {@code parseCfnTags} in
* {@code CloudFormationResourceProvisioner}, which returns an empty set for anything that is
* {@code StepFunctionsCfnProvisioner}, which returns an empty set for anything that is
* not an array; a verbatim map copy would silently tag nothing). Emitted unconditionally,
* even for an absent or empty {@code Tags} map: measured against real AWS, us-east-1, a
* change set's Processed template for a state machine with no source {@code Tags} declared
@@ -24,15 +24,14 @@ import java.util.function.Function;
* Provisions {@code AWS::AutoScaling::AutoScalingGroup} and
* {@code AWS::AutoScaling::LaunchConfiguration}.
*
* <p>Extracted from {@code CloudFormationResourceProvisioner}. The two types share a provisioner
* <p>Extracted from the former CloudFormation monolith. The two types share a provisioner
* because they share {@code AutoScalingService} and because a group names a launch configuration:
* splitting them would put the same service behind two classes for no gain. The per-type
* siblings {@link AutoScalingLifecycleHookCfnProvisioner} and
* {@link AutoScalingScalingPolicyCfnProvisioner} stay separate: they attach to a group rather
* than being one.
*
* <p>Both types delete by physical id alone, so the id-only delete override serves them and
* neither is in the engine's {@code DELETE_NEEDS_STACK_RESOURCE} set.
* <p>Both types delete by physical id alone, so the id-only delete override serves them.
*/
@ApplicationScoped
public class AutoScalingGroupCfnProvisioner implements CfnResourceProvisioner {
@@ -19,7 +19,7 @@ import java.util.function.Function;
/**
* CloudFormation provisioning for Batch: {@code AWS::Batch::ComputeEnvironment},
* {@code AWS::Batch::JobQueue} and {@code AWS::Batch::JobDefinition}. Extracted from
* {@code CloudFormationResourceProvisioner}.
* the former CloudFormation monolith.
*
* <p>The template property names are PascalCase and {@link BatchService} speaks the wire
* shape's camelCase, so every arm builds a request node rather than passing properties
@@ -0,0 +1,279 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Consumer;
/**
* Routes each CloudFormation resource to the per-service provisioner that owns its type, through
* {@link CloudFormationResourceRegistry}, and holds the two behaviours no provisioner owns: a type
* nothing serves is stubbed (or refused, in strict mode), and a delete nothing serves is reported.
* It also answers the engine's update-lifecycle questions (cleanup, rollback, replacement tracking)
* by delegating to the owner, and offers Cloud Control its stack-less entry points.
*
* <p>No type-specific code belongs here. A new type gets a per-service provisioner; this class
* only dispatches.
*/
@ApplicationScoped
public class CfnResourceDispatcher {
private static final Logger LOG = Logger.getLogger(CfnResourceDispatcher.class);
private final ObjectMapper objectMapper;
private final CloudFormationResourceRegistry registry;
private final CfnDynamicReferences dynamicReferences;
private final EmulatorConfig config;
@Inject
public CfnResourceDispatcher(ObjectMapper objectMapper, CloudFormationResourceRegistry registry,
CfnDynamicReferences dynamicReferences, EmulatorConfig config) {
this.objectMapper = objectMapper;
this.registry = registry;
this.dynamicReferences = dynamicReferences;
this.config = config;
}
/**
* Provisions a single resource and returns the populated StackResource (physical id and
* attributes set).
*
* <p>A resource type with no provisioner is stubbed: a synthetic physical id, an
* {@code arn:aws:stub:::} ARN attribute and {@code CREATE_COMPLETE}, logged at warn and
* carrying a status reason saying nothing was created. With
* {@code floci.services.cloudformation.allow-stub-unsupported-resource-types} off it comes back
* {@code CREATE_FAILED} instead, with no physical id.
*/
public StackResource provision(String logicalId, String resourceType, JsonNode properties,
CloudFormationTemplateEngine engine, String region, String accountId,
String stackName) {
return provision(logicalId, resourceType, properties, engine, region, accountId, stackName,
null, Map.of());
}
public StackResource provision(String logicalId, String resourceType, JsonNode properties,
CloudFormationTemplateEngine engine, String region, String accountId,
String stackName, String existingPhysicalId,
Map<String, String> existingAttributes) {
return provision(logicalId, resourceType, properties, engine, region, accountId, stackName,
existingPhysicalId, existingAttributes, event -> {});
}
public StackResource provision(String logicalId, String resourceType, JsonNode properties,
CloudFormationTemplateEngine engine, String region, String accountId,
String stackName, String existingPhysicalId,
Map<String, String> existingAttributes, Consumer<StackEvent> progress) {
StackResource resource = new StackResource();
resource.setLogicalId(logicalId);
resource.setResourceType(resourceType);
resource.setPhysicalId(existingPhysicalId);
resource.setAttributes(new HashMap<>(existingAttributes != null ? existingAttributes : Map.of()));
try {
CfnResourceProvisioner owner = registry.forType(resourceType).orElse(null);
if (owner != null) {
owner.provision(resource, properties,
new ProvisionContext(engine, region, accountId, stackName, existingPhysicalId, progress));
} else if (!stubUnsupportedResourceTypesAllowed()) {
// Before the physical id below is assigned, so the Cloud Control path sees a
// resource with none and reports this message rather than a success. On the stack
// path the catch below turns it into CREATE_FAILED with the same sentence, which
// rolls the stack back.
throw new AwsException("ValidationError", unsupportedResourceTypeMessage(resourceType), 400);
} else {
// Warn, not debug, and a status reason on the resource: the stub reports
// CREATE_COMPLETE while creating nothing, so without both the stack is
// indistinguishable from one where every resource was really provisioned. The
// reason reaches DescribeStackEvents through the event CloudFormationService
// already builds from it.
LOG.warnv("Stubbing unsupported resource type {0} ({1}): nothing is created "
+ "for it. Set floci.services.cloudformation."
+ "allow-stub-unsupported-resource-types=false to fail the "
+ "stack instead.",
resourceType, logicalId);
resource.setStatusReason(unsupportedResourceTypeMessage(resourceType)
+ " It was stubbed and nothing was created for it.");
resource.setPhysicalId(logicalId + "-" + UUID.randomUUID().toString().substring(0, 8));
resource.getAttributes().put("Arn", "arn:aws:stub:::" + logicalId);
}
resource.setStatus("CREATE_COMPLETE");
} catch (Exception e) {
LOG.warnv("Failed to provision {0} ({1}): {2}", resourceType, logicalId, e.getMessage());
resource.setStatus("CREATE_FAILED");
resource.setStatusReason(e.getMessage());
}
return resource;
}
/**
* Whether a resource type with no provisioner may be stubbed. The dispatchers hand-built in
* unit tests carry no config; absent configuration means the documented default, which here is
* the lenient behaviour, so the test reads {@code config == null ||}.
*/
private boolean stubUnsupportedResourceTypesAllowed() {
return config == null || config.services().cloudformation().allowStubUnsupportedResourceTypes();
}
/** The one sentence Floci says about a resource type it has no provisioner for. */
private static String unsupportedResourceTypeMessage(String resourceType) {
return "Resource type " + resourceType + " is not supported by Floci.";
}
/**
* Provisions a single resource with no enclosing CloudFormation stack, the Cloud Control
* {@code CreateResource} path. Cloud Control DesiredState carries resolved values (no
* intrinsics), so a minimal template engine suffices; any type a stack can create, Cloud
* Control can too.
*/
public StackResource provisionStandalone(String resourceType, JsonNode properties, String region,
String accountId) {
CloudFormationTemplateEngine engine = CloudFormationTemplateEngine.standalone(accountId, region,
"cloudcontrol", objectMapper,
value -> dynamicReferences.resolveDynamicReferences(value, region, false));
return provision("resource", resourceType, properties, engine, region, accountId, "cloudcontrol");
}
/**
* Deletes a resource by type and physical id with no enclosing stack, the Cloud Control
* {@code DeleteResource} path, with the attributes recorded when the resource was created:
* custom resources, EKS nodegroups and IAM inline policies cannot be deleted from type and
* physical id alone, so without these their delete silently no-ops.
*/
public void deleteStandalone(String resourceType, String identifier, String region,
Map<String, String> attributes) {
StackResource resource = new StackResource();
resource.setResourceType(resourceType);
resource.setPhysicalId(identifier);
resource.setAttributes(new HashMap<>(attributes == null ? Map.of() : attributes));
delete(resource, region);
}
/**
* Deletes a provisioned resource. The owning provisioner gets the whole resource, so an
* attribute-aware delete can read its create-time attributes, and an exact type match always
* beats the {@code Custom::} fallback the registry applies.
*/
public void delete(StackResource resource, String region) {
String resourceType = resource.getResourceType();
CfnResourceProvisioner owner = registry.forType(resourceType).orElse(null);
if (owner != null) {
owner.delete(resource, region);
return;
}
delete(resourceType, resource.getPhysicalId(), region);
}
/**
* Deletes a single resource by type and physical id. Failures propagate to the caller so the
* stack transitions to DELETE_FAILED, matching AWS: deleting a non-empty S3 bucket raises
* BucketNotEmpty and must not be reported as a successful stack deletion.
*/
public void delete(String resourceType, String physicalId, String region) {
CfnResourceProvisioner owner = registry.forType(resourceType).orElse(null);
if (owner != null) {
owner.delete(resourceType, physicalId, region);
return;
}
// Warn for the same reason the create path does: the delete reports success over a type
// nothing here removes, and at debug that is invisible at the default log level. The line
// names the physical id without claiming a resource survives it: a stubbed type left
// nothing behind.
LOG.warnv("No delete implemented for resource type {0}: {1} is not removed here.",
resourceType, physicalId);
}
/**
* One attempt at deleting what this update's replacement displaced, delegated to the
* provisioner that owns the type.
*/
public UpdateCleanupResult completeUpdate(StackResource resource) {
return registry.forType(resource.getResourceType())
.map(owner -> owner.completeUpdate(resource))
.filter(UpdateCleanupResult::applicable)
.orElseGet(UpdateCleanupResult::notApplicable);
}
/**
* The physical id this update displaced, announced as DELETE_IN_PROGRESS before the stack
* update closes. A type whose {@code UpdateReplacePolicy} is {@code Retain} owes no cleanup.
*/
public String updateCleanupPhysicalId(StackResource resource) {
if ("Retain".equals(resource.getUpdateReplacePolicy())) {
return null;
}
return registry.forType(resource.getResourceType())
.map(owner -> owner.updateCleanupPhysicalId(resource))
.orElse(null);
}
/** Only an opted-in provisioner may identify cleanup owed by an UPDATE_FAILED resource. */
public boolean hasPendingRollbackCleanup(StackResource resource) {
return registry.forType(resource.getResourceType())
.map(owner -> owner.hasPendingRollbackCleanup(resource))
.orElse(false);
}
/** Only an opted-in provisioner may keep a failed update attempt in place of the previous resource. */
public boolean retainsFailedUpdateState(StackResource resource) {
return registry.forType(resource.getResourceType())
.map(owner -> owner.retainsFailedUpdateState(resource))
.orElse(false);
}
/** Whether this update replaced the resource's physical entity, so the stack has cleanup pending. */
public boolean hasReplacementUpdate(StackResource resource) {
return registry.forType(resource.getResourceType())
.map(owner -> owner.hasReplacementUpdate(resource))
.orElse(false);
}
/** Drops the cleanup bookkeeping this update left on the resource. */
public void clearUpdate(StackResource resource) {
registry.forType(resource.getResourceType())
.ifPresent(owner -> owner.clearUpdate(resource));
}
/**
* Puts the physical entity back to its pre-update configuration when a later resource fails
* the stack update, delegated to the provisioner that owns the type.
*/
public boolean rollbackUpdate(StackResource resource) {
return rollbackUpdate(resource, event -> {});
}
public boolean rollbackUpdate(StackResource resource, Consumer<StackEvent> progress) {
return registry.forType(resource.getResourceType())
.map(owner -> owner.rollbackUpdate(resource, progress))
.orElse(false);
}
/**
* Carries ownership discovered by a failed update onto the last known-good resource metadata
* that CloudFormation restores. Only additive cleanup tracking belongs here; normal attempted
* attributes must not overwrite the committed resource state.
*/
public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) {
// Any provisioner using ReplacementCleanup: an entity the failed attempt created and could
// not remove is owed to the next cleanup, which runs on the restored resource.
ReplacementCleanup.mergeDisplaced(previous, attempted);
if (!Objects.equals(previous.getResourceType(), attempted.getResourceType())) {
return;
}
// Provisioners that track their own generated sub-resources (ApiGatewayV2's Api body
// routes, integrations and authorizers) carry that tracking forward themselves.
registry.forType(previous.getResourceType())
.ifPresent(owner -> owner.mergeFailedUpdateResourceTracking(previous, attempted));
}
}
@@ -8,8 +8,8 @@ import java.util.Set;
import java.util.function.Consumer;
/**
* Provisions and deletes the CloudFormation resource types for a single service, replacing one
* arm of the switch in {@code CloudFormationResourceProvisioner}. Implementations inject only
* Provisions and deletes the CloudFormation resource types for a single service. Implementations
* inject only
* the service they wrap and are discovered via CDI by {@link CloudFormationResourceRegistry}.
*
* <p>{@code provision} mutates the passed {@link StackResource} in place — setting its physical
@@ -3,11 +3,9 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
import org.jboss.logging.Logger;
/**
* Rollback bookkeeping shared by every resource handler, on both sides of the ongoing
* decomposition: the remaining {@code CloudFormationResourceProvisioner} switch arms and the
* extracted {@link CfnResourceProvisioner} implementations. It lives here instead of in either
* half so the ownership marker and the cleanup logging stay single-sourced while types migrate
* out one service at a time.
* Rollback bookkeeping shared by every {@link CfnResourceProvisioner} and read by
* {@code CloudFormationService}. It lives here so the ownership marker and the cleanup logging
* stay single-sourced across the per-service provisioners.
*/
public final class CfnRollback {
@@ -23,8 +21,7 @@ public final class CfnRollback {
* Marks a resource whose prior physical entity is still intact after a failed update, so the
* rollback must not try to restore it. Set by a provisioner that creates the replacement before
* deleting the original; read by {@code CloudFormationService} when deciding what a rollback
* owes. Lives here rather than on {@code CloudFormationResourceProvisioner} so extracted
* provisioners in this package can set it.
* owes. Lives here so every provisioner in this package can set it.
*/
public static final String UPDATE_ROLLBACK_RESTORED_ATTR = "__FlociUpdateRollbackRestored";
@@ -12,8 +12,8 @@ import java.util.Set;
/**
* Maps a CloudFormation resource type to the {@link CfnResourceProvisioner} that serves it.
* {@code CloudFormationResourceProvisioner} consults this first and falls through to its own
* switch for types not yet extracted, so the two coexist during the incremental migration.
* {@code CfnResourceDispatcher} consults this for every type; a type nothing here serves is stubbed
* by the dispatcher, never provisioned.
*/
@ApplicationScoped
public class CloudFormationResourceRegistry {
@@ -315,7 +315,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
return node.asText();
}
// The distribution itself, moved out of CloudFormationResourceProvisioner. It reads the
// The distribution itself, moved out of the former CloudFormation monolith. It reads the
// policy ids the types above hand it, which is why the two live in one provisioner.
@@ -25,7 +25,7 @@ import java.util.concurrent.TimeoutException;
/**
* Provisions {@code AWS::CloudFormation::CustomResource} and every {@code Custom::*} type, moved out
* of the {@code CloudFormationResourceProvisioner} monolith.
* of the former CloudFormation monolith.
*
* <p>A custom resource is backed by a Lambda named by its {@code ServiceToken}. CloudFormation
* invokes that Lambda with a request event and the Lambda PUTs its result to the event's
@@ -24,7 +24,7 @@ import java.util.Set;
* Provisions {@code AWS::DynamoDB::Table}, {@code AWS::DynamoDB::GlobalTable} and the CDK legacy
* global-table custom resource {@code Custom::DynamoDBReplica}.
*
* <p>Extracted from {@code CloudFormationResourceProvisioner}. A global table is provisioned as a
* <p>Extracted from the former CloudFormation monolith. A global table is provisioned as a
* plain table and then its {@code Replicas} property is reconciled against the tracked replica
* regions: declared regions are added and dropped ones removed, so an UpdateStack that changes the
* Replicas list converges. The deployment region is served by the table itself and is filtered out
@@ -31,7 +31,7 @@ import java.util.function.Supplier;
/**
* CloudFormation provisioning for the EC2 networking types: {@code AWS::EC2::Subnet},
* {@code InternetGateway}, {@code RouteTable}, {@code Route}, {@code NatGateway}, {@code EIP} and
* {@code SubnetRouteTableAssociation}. Extracted from {@code CloudFormationResourceProvisioner} as
* {@code SubnetRouteTableAssociation}. Extracted from the former CloudFormation monolith as
* part of the per-service decomposition. The physical id is the EC2 id the service assigns, except
* for a Route, whose id is the registry primary identifier {@code <RouteTableId>|<destination>} (what
* Ref returns on AWS and what a delete needs), and an EIP, whose Ref is its public IP.
@@ -15,7 +15,7 @@ import java.util.Set;
/**
* CloudFormation provisioning for {@code AWS::EC2::VPC}. Extracted verbatim from
* {@code CloudFormationResourceProvisioner} as part of the per-service decomposition.
* the former CloudFormation monolith as part of the per-service decomposition.
*/
@ApplicationScoped
public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
@@ -20,7 +20,7 @@ import java.util.Set;
/**
* CloudFormation provisioning for ECS capacity: {@code AWS::ECS::CapacityProvider} and
* {@code AWS::ECS::ClusterCapacityProviderAssociations}. Injects only {@link EcsService}, per the
* per-service provisioner decomposition of {@code CloudFormationResourceProvisioner}.
* per-service provisioner decomposition of the former CloudFormation monolith.
*
* <p>CloudFormation spells these properties in PascalCase while {@code EcsService} stores the ECS
* JSON API's camelCase shape (that is what {@code CreateCapacityProvider} puts there). The whole
@@ -32,7 +32,7 @@ import java.util.Set;
/**
* CloudFormation provisioning for the ECS core types, {@code AWS::ECS::Cluster},
* {@code AWS::ECS::TaskDefinition} and {@code AWS::ECS::Service}, moved out of the
* {@code CloudFormationResourceProvisioner} switch. Capacity providers live in
* former CloudFormation monolith's switch. Capacity providers live in
* {@link EcsCapacityCfnProvisioner}.
*/
@ApplicationScoped
@@ -24,7 +24,7 @@ import java.util.UUID;
/**
* CloudFormation provisioning for the Elastic Load Balancing v2 types,
* {@code AWS::ElasticLoadBalancingV2::LoadBalancer}, {@code TargetGroup}, {@code Listener} and
* {@code ListenerRule}, moved out of the {@code CloudFormationResourceProvisioner} switch.
* {@code ListenerRule}, moved out of the former CloudFormation monolith's switch.
*/
@ApplicationScoped
public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
@@ -35,7 +35,7 @@ import java.util.regex.Pattern;
/**
* CloudFormation provisioning for EventBridge: {@code AWS::Events::Rule},
* {@code AWS::Events::EventBus} and {@code AWS::Events::EventBusPolicy}. Extracted from
* {@code CloudFormationResourceProvisioner}.
* the former CloudFormation monolith.
*
* <p>Two of these types need the resource's stored attributes to delete, not just the physical
* id, so they are served by the {@link #delete(StackResource, String)} override rather than the
@@ -21,7 +21,7 @@ import java.util.Set;
/**
* CloudFormation provisioning for {@code AWS::IAM::Role}, moved out of the
* {@code CloudFormationResourceProvisioner} switch. The other IAM types (User, AccessKey, Policy,
* former CloudFormation monolith's switch. The other IAM types (User, AccessKey, Policy,
* ManagedPolicy, InstanceProfile) still live there and share {@link CfnRollback} with this class.
*/
@ApplicationScoped
@@ -22,7 +22,7 @@ import java.util.Set;
/**
* CloudFormation provisioning for {@code AWS::IAM::User}, moved out of the
* {@code CloudFormationResourceProvisioner} switch.
* former CloudFormation monolith's switch.
*/
@ApplicationScoped
public class IamUserCfnProvisioner implements CfnResourceProvisioner {
@@ -67,10 +67,8 @@ public class KmsCfnProvisioner implements CfnResourceProvisioner {
}
/**
* Copied from {@code CloudFormationResourceProvisioner} rather than delegating to
* {@link ProvisionContext#resolveTags}, which is not equivalent: it skips a blank key this
* keeps and orders entries by insertion rather than hash. This copy dies when the monolith's
* last caller migrates.
* Kept rather than delegating to {@link ProvisionContext#resolveTags}, which is not
* equivalent: it skips a blank key this keeps and orders entries by insertion rather than hash.
*/
private Map<String, String> parseCfnTags(JsonNode tagsNode, ProvisionContext ctx) {
tagsNode = ctx.engine().resolveNode(tagsNode);
@@ -37,7 +37,7 @@ import java.util.zip.ZipOutputStream;
/**
* Provisions {@code AWS::Lambda::Function} and {@code AWS::Lambda::LayerVersion}, moved verbatim out
* of the {@code CloudFormationResourceProvisioner} monolith. Function provisioning covers create,
* of the former CloudFormation monolith. Function provisioning covers create,
* in-place configuration/code update, and replacement on a name or package-type change; layer
* version provisioning publishes a new version and exposes its ARN for {@code Ref}/{@code Fn::GetAtt}.
*/
@@ -18,8 +18,8 @@ import java.util.Set;
/**
* CloudFormation provisioning for {@code AWS::Lambda::Version} and {@code AWS::Lambda::Alias}.
*
* <p>Covers only these two types, not {@code AWS::Lambda::Function} — that one still lives in
* {@code CloudFormationResourceProvisioner}'s switch, which the registry falls through to. The
* <p>Covers only these two types, not {@code AWS::Lambda::Function}, which
* {@code LambdaCfnProvisioner} owns. The
* two types are what SAM's {@code AutoPublishAlias} expands into, and without them an
* alias-qualified invoke ({@code <function>:production}) fails with "Alias not found" even though
* the template declared the alias and the stack reported CREATE_COMPLETE.
@@ -14,7 +14,7 @@ import java.util.function.Consumer;
/**
* The per-provision context every resource handler drew from: the template engine (for resolving
* intrinsic functions in properties) plus the region/account/stack it is being created in. The
* helpers are lifted verbatim from {@code CloudFormationResourceProvisioner}'s private methods
* helpers were lifted verbatim from the former CloudFormation monolith's private methods
* so extracted provisioners produce byte-identical physical ids and resolved values.
*/
public record ProvisionContext(CloudFormationTemplateEngine engine, String region,
@@ -28,11 +28,10 @@ import java.util.Set;
/**
* CloudFormation provisioning for RDS: the two parameter-group types, {@code DBSubnetGroup},
* {@code DBInstance}, {@code DBCluster}, {@code DBProxy} and {@code DBProxyTargetGroup}.
* Extracted from {@code CloudFormationResourceProvisioner}.
* Extracted from the former CloudFormation monolith.
*
* <p>Every type here deletes by physical id alone, so the id-only
* {@link #delete(String, String, String)} serves all seven and none of them appears in the
* engine's {@code DELETE_NEEDS_STACK_RESOURCE} set. {@code DBCluster} is the one type that
* {@link #delete(String, String, String)} serves all seven. {@code DBCluster} is the one type that
* replaces through {@link ReplacementCleanup}; see {@code provisionDbCluster}.
*
* <p>Unlike most extractions this one does not take {@code RdsService} out of the monolith.
@@ -27,7 +27,7 @@ import java.util.Set;
/**
* Provisions {@code AWS::SecretsManager::SecretTargetAttachment}.
*
* <p>Extracted from {@code CloudFormationResourceProvisioner}. Unlike most provisioners this one
* <p>Extracted from the former CloudFormation monolith. Unlike most provisioners this one
* wraps three services rather than one: an attachment reads the endpoint of the RDS or DocumentDB
* instance or cluster it points at, so it can write the connection detail (engine, host, port,
* dbname, identifier) into the target secret. That dependency is inherent to the type, and it is
@@ -37,9 +37,8 @@ import java.util.Set;
* overrides {@code delete(StackResource, String)}. The delete needs two create-time attributes
* that no physical id carries: which secret fields this attachment managed, so only those are
* stripped, and which attachment owns the secret, so a second attachment's fields are left alone.
* Registering that here is what lets the type leave the engine's
* {@code DELETE_NEEDS_STACK_RESOURCE} set; the two must change together or
* {@code CfnDeletePrecedenceTest} fails with both claiming it.
* The dispatcher hands the owner the whole resource on delete, which is what makes that
* possible.
*/
@ApplicationScoped
public class SecretTargetAttachmentCfnProvisioner implements CfnResourceProvisioner {
@@ -18,14 +18,13 @@ import java.util.Set;
/**
* Provisions {@code AWS::SecretsManager::Secret}.
*
* <p>Extracted from {@code CloudFormationResourceProvisioner}. The sibling type
* <p>Extracted from the former CloudFormation monolith. The sibling type
* {@code AWS::SecretsManager::SecretTargetAttachment} lives in
* {@link SecretTargetAttachmentCfnProvisioner} instead of here, because it has to read an RDS or
* DocumentDB endpoint to build the connection detail it writes into the secret, so it needs three
* services where this one needs only its own.
*
* <p>The secret deletes by physical id alone, so the id-only delete override serves it and it is
* not in the engine's {@code DELETE_NEEDS_STACK_RESOURCE} set.
* <p>The secret deletes by physical id alone, so the id-only delete override serves it.
*/
@ApplicationScoped
public class SecretsManagerCfnProvisioner implements CfnResourceProvisioner {
@@ -17,7 +17,7 @@ import java.util.UUID;
/**
* CloudFormation provisioning for SQS: {@code AWS::SQS::Queue} and {@code AWS::SQS::QueuePolicy}.
* Extracted verbatim from {@code CloudFormationResourceProvisioner} (item 15 decomposition).
* Extracted verbatim from the former CloudFormation monolith (item 15 decomposition).
*/
@ApplicationScoped
public class SqsCfnProvisioner implements CfnResourceProvisioner {
@@ -29,7 +29,7 @@ import java.util.regex.Pattern;
/**
* Provisions {@code AWS::StepFunctions::StateMachine}.
*
* <p>Extracted from {@code CloudFormationResourceProvisioner}. This type carried the last
* <p>Extracted from the former CloudFormation monolith. This type carried the last
* fall-through arm in that class's five update-cleanup hooks, so moving it here reduces every
* one of them to plain registry delegation: a replacement's bookkeeping, its retry budget and
* its rollback now live beside the code that creates the replacement.
@@ -9,9 +9,8 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
* gone; on false the caller retries until {@code attempts} reaches 3 and then reports
* {@code failureReason} against {@code previousPhysicalId}.
*
* <p>It lives in this package rather than inside {@code CloudFormationResourceProvisioner} so an
* extracted {@link CfnResourceProvisioner} can return one without depending on the monolith it was
* extracted from.
* <p>It lives in this package so a {@link CfnResourceProvisioner} can return one and
* {@code CfnResourceDispatcher} can aggregate it.
*/
public record UpdateCleanupResult(
boolean applicable,