refactor(cloudformation): extract a per-service provisioner registry, migrate SQS (#1825)

First slice of decomposing CloudFormationResourceProvisioner (the repo's largest
class: ~30 injected services and 75 resource types in two switches).

Introduce the scaffolding for per-service provisioners:
- CfnResourceProvisioner: a provision/delete interface for one service's types.
- ProvisionContext: the {engine, region, accountId, stackName} handlers draw from,
  with resolveOptional/generatePhysicalName lifted verbatim from the monolith.
- CloudFormationResourceRegistry: a CDI-collected resource-type -> provisioner map,
  with a public factory constructor for tests; duplicate registration throws.

CloudFormationResourceProvisioner now consults the registry before its switch and
falls through for unmigrated types, so the two coexist during the migration. SQS is
the first extraction: SqsCfnProvisioner (injects only SqsService) owns Queue and
QueuePolicy; its switch cases and provisionXxx methods are removed. The registry is
added to the constructor once so later slices do not reshuffle positional args.

SqsCfnProvisionerTest exercises the provisioner with a single mocked service, the
payoff versus the ~30 mocks the monolith requires. Behavior is unchanged: the full
CloudFormation integration suite (174 tests) stays green.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-07-11 01:14:32 -05:00
1 parent eb2fa9c25f
commit 6856c7f1e6
8 files changed
+318 -34

No files matched your search

@@ -5,6 +5,9 @@ import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
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.CfnResourceProvisioner;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.eventbridge.model.BatchParameters;
@@ -153,6 +156,10 @@ public class CloudFormationResourceProvisioner {
private final CloudWatchMetricsService cloudWatchMetricsService;
private final AutoScalingService autoScalingService;
private final FirehoseService firehoseService;
// Item 15 decomposition: extracted per-service provisioners are consulted before the switch
// below. As types migrate, their switch cases and provisionXxx methods are removed here; the
// now-dead service deps above are cleared in the final cleanup once the switch is empty.
private final CloudFormationResourceRegistry resourceRegistry;
@Inject
public CloudFormationResourceProvisioner(S3Service s3Service, SqsService sqsService,
@@ -181,7 +188,8 @@ public class CloudFormationResourceProvisioner {
KinesisService kinesisService,
CloudWatchMetricsService cloudWatchMetricsService,
AutoScalingService autoScalingService,
FirehoseService firehoseService) {
FirehoseService firehoseService,
CloudFormationResourceRegistry resourceRegistry) {
this.s3Service = s3Service;
this.sqsService = sqsService;
this.snsService = snsService;
@@ -213,6 +221,7 @@ public class CloudFormationResourceProvisioner {
this.cloudWatchMetricsService = cloudWatchMetricsService;
this.autoScalingService = autoScalingService;
this.firehoseService = firehoseService;
this.resourceRegistry = resourceRegistry;
}
/**
@@ -243,9 +252,15 @@ public class CloudFormationResourceProvisioner {
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));
resource.setStatus("CREATE_COMPLETE");
return resource;
}
switch (resourceType) {
case "AWS::S3::Bucket" -> provisionS3Bucket(resource, properties, engine, region, accountId, stackName);
case "AWS::SQS::Queue" -> provisionSqsQueue(resource, properties, engine, region, accountId, stackName);
case "AWS::SNS::Topic" -> provisionSnsTopic(resource, properties, engine, region, accountId, stackName);
case "AWS::SNS::Subscription" -> provisionSnsSubscription(resource, properties, engine, region);
case "AWS::DynamoDB::Table", "AWS::DynamoDB::GlobalTable" ->
@@ -265,7 +280,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::SecretsManager::Secret" -> provisionSecret(resource, properties, engine, region, accountId, stackName);
case "AWS::CDK::Metadata" -> provisionCdkMetadata(resource);
case "AWS::S3::BucketPolicy" -> provisionS3BucketPolicy(resource, properties, engine);
case "AWS::SQS::QueuePolicy" -> provisionSqsQueuePolicy(resource, properties, engine);
case "AWS::ECR::Repository" -> provisionEcrRepository(resource, properties, engine, stackName, region);
case "AWS::Route53::HostedZone" -> provisionRoute53HostedZone(resource, properties, engine);
case "AWS::Route53::RecordSet" -> provisionRoute53RecordSet(resource, properties, engine);
@@ -400,9 +414,13 @@ public class CloudFormationResourceProvisioner {
* 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) {
case "AWS::S3::Bucket" -> s3Service.deleteBucket(physicalId);
case "AWS::SQS::Queue" -> sqsService.deleteQueue(physicalId, region);
case "AWS::SNS::Topic" -> snsService.deleteTopic(physicalId, region);
case "AWS::SNS::Subscription" -> snsService.unsubscribe(physicalId, region);
case "AWS::DynamoDB::Table" -> dynamoDbService.deleteTable(physicalId, region);
@@ -524,31 +542,6 @@ public class CloudFormationResourceProvisioner {
}
}
private void provisionSqsQueue(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String region, String accountId, String stackName) {
String queueName = resolveOptional(props, "QueueName", engine);
if (queueName == null || queueName.isBlank()) {
queueName = generatePhysicalName(stackName, r.getLogicalId(), 80, false);
}
Map<String, String> attrs = new HashMap<>();
if (props != null) {
if(props.has("VisibilityTimeout")) {
attrs.put("VisibilityTimeout", engine.resolve(props.get("VisibilityTimeout")));
}
if(props.has("ContentBasedDeduplication")) {
attrs.put("ContentBasedDeduplication", engine.resolve(props.get("ContentBasedDeduplication")));
}
}
var queue = sqsService.createQueue(queueName, attrs, region);
// QueueArn is computed on demand in SqsService#getQueueAttributes and is not
// stored on the Queue object, so build it here from region + accountId + queueName.
// Without this, Fn::GetAtt [Queue, Arn] references resolve to an empty string.
String queueArn = AwsArnUtils.Arn.of("sqs", region, accountId, queueName).toString();
r.setPhysicalId(queue.getQueueUrl());
r.getAttributes().put("Arn", queueArn);
r.getAttributes().put("QueueName", queueName);
r.getAttributes().put("QueueUrl", queue.getQueueUrl());
}
// ── EC2 networking ─────────────────────────────────────────────────────────
// Each method delegates to Ec2Service so the resource really exists (describe-subnets,
@@ -2490,9 +2483,6 @@ public class CloudFormationResourceProvisioner {
r.setPhysicalId("bucket-policy-" + UUID.randomUUID().toString().substring(0, 8));
}
private void provisionSqsQueuePolicy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) {
r.setPhysicalId("queue-policy-" + UUID.randomUUID().toString().substring(0, 8));
}
private void provisionIamUser(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String stackName) {
@@ -0,0 +1,28 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import java.util.Set;
/**
* Provisions and deletes the CloudFormation resource types for a single service, replacing one
* arm of the switch in {@code CloudFormationResourceProvisioner}. 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
* id and populating its attributes for {@code Fn::GetAtt} — exactly as the original per-type
* methods did. {@code resource.getResourceType()} disambiguates when a provisioner serves more
* than one type.
*/
public interface CfnResourceProvisioner {
Set<String> resourceTypes();
void provision(StackResource resource, JsonNode properties, ProvisionContext ctx);
/** Most implementations delegate to {@code service.deleteX(physicalId, region)}. */
default void delete(String resourceType, String physicalId, String region) {
// no-op by default: some resource types have no backing delete
}
}
@@ -0,0 +1,46 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* 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.
*/
@ApplicationScoped
public class CloudFormationResourceRegistry {
private final Map<String, CfnResourceProvisioner> byType = new HashMap<>();
@Inject
public CloudFormationResourceRegistry(Instance<CfnResourceProvisioner> provisioners) {
provisioners.forEach(this::register);
}
/** Factory constructor: build a registry from an explicit list, bypassing CDI (tests). */
public CloudFormationResourceRegistry(Collection<CfnResourceProvisioner> provisioners) {
provisioners.forEach(this::register);
}
private void register(CfnResourceProvisioner provisioner) {
for (String type : provisioner.resourceTypes()) {
CfnResourceProvisioner existing = byType.put(type, provisioner);
if (existing != null) {
throw new IllegalStateException("Duplicate CloudFormation provisioner for " + type
+ ": " + existing.getClass().getSimpleName() + " and "
+ provisioner.getClass().getSimpleName());
}
}
}
public Optional<CfnResourceProvisioner> forType(String resourceType) {
return Optional.ofNullable(byType.get(resourceType));
}
}
@@ -0,0 +1,37 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import java.util.UUID;
/**
* 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
* two helpers are lifted verbatim from {@code CloudFormationResourceProvisioner}'s private methods
* so extracted provisioners produce byte-identical physical ids and resolved values.
*/
public record ProvisionContext(CloudFormationTemplateEngine engine, String region,
String accountId, String stackName) {
/** Resolves an optional property through the engine, or null when absent/explicitly null. */
public String resolveOptional(JsonNode props, String name) {
if (props == null || !props.has(name) || props.get(name).isNull()) {
return null;
}
return engine.resolve(props.get(name));
}
/** Generates a CloudFormation-style physical name: {@code <stack>-<logicalId>-<suffix>}. */
public String generatePhysicalName(String logicalId, int maxLength, boolean lowercase) {
String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
String name = stackName + "-" + logicalId + "-" + suffix;
if (lowercase) {
name = name.toLowerCase();
}
if (maxLength > 0 && name.length() > maxLength) {
name = name.substring(0, maxLength);
}
return name;
}
}
@@ -0,0 +1,80 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.sqs.model.Queue;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
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).
*/
@ApplicationScoped
public class SqsCfnProvisioner implements CfnResourceProvisioner {
private final SqsService sqsService;
@Inject
public SqsCfnProvisioner(SqsService sqsService) {
this.sqsService = sqsService;
}
@Override
public Set<String> resourceTypes() {
return Set.of("AWS::SQS::Queue", "AWS::SQS::QueuePolicy");
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
switch (r.getResourceType()) {
case "AWS::SQS::Queue" -> provisionQueue(r, props, ctx);
case "AWS::SQS::QueuePolicy" -> provisionQueuePolicy(r);
default -> throw new IllegalStateException("SqsCfnProvisioner cannot handle " + r.getResourceType());
}
}
@Override
public void delete(String resourceType, String physicalId, String region) {
if ("AWS::SQS::Queue".equals(resourceType)) {
sqsService.deleteQueue(physicalId, region);
}
// AWS::SQS::QueuePolicy has no backing resource to delete (matches prior behavior).
}
private void provisionQueue(StackResource r, JsonNode props, ProvisionContext ctx) {
String queueName = ctx.resolveOptional(props, "QueueName");
if (queueName == null || queueName.isBlank()) {
queueName = ctx.generatePhysicalName(r.getLogicalId(), 80, false);
}
Map<String, String> attrs = new HashMap<>();
if (props != null) {
if (props.has("VisibilityTimeout")) {
attrs.put("VisibilityTimeout", ctx.engine().resolve(props.get("VisibilityTimeout")));
}
if (props.has("ContentBasedDeduplication")) {
attrs.put("ContentBasedDeduplication", ctx.engine().resolve(props.get("ContentBasedDeduplication")));
}
}
Queue queue = sqsService.createQueue(queueName, attrs, ctx.region());
// QueueArn is computed on demand in SqsService#getQueueAttributes and is not stored on the
// Queue object, so build it here from region + accountId + queueName. Without this,
// Fn::GetAtt [Queue, Arn] references resolve to an empty string.
String queueArn = AwsArnUtils.Arn.of("sqs", ctx.region(), ctx.accountId(), queueName).toString();
r.setPhysicalId(queue.getQueueUrl());
r.getAttributes().put("Arn", queueArn);
r.getAttributes().put("QueueName", queueName);
r.getAttributes().put("QueueUrl", queue.getQueueUrl());
}
private void provisionQueuePolicy(StackResource r) {
r.setPhysicalId("queue-policy-" + UUID.randomUUID().toString().substring(0, 8));
}
}