Light, fluffy, and always free - The AWS Local Emulator alternative
refactor(cloudformation): extract a per-service provisioner registry, migrate SQS (#1825)
Hector Ventura6856c7f1e604
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.javaindex 7c338a58e7..4e2e97d7c0 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java@@ -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;@Injectpublic 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) {diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceProvisioner.javanew file mode 100644index 0000000000..a7e4b584f9--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceProvisioner.java@@ -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+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFormationResourceRegistry.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFormationResourceRegistry.javanew file mode 100644index 0000000000..5af5febeca--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFormationResourceRegistry.java@@ -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));+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.javanew file mode 100644index 0000000000..81b20be907--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SqsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SqsCfnProvisioner.javanew file mode 100644index 0000000000..bdc004059a--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SqsCfnProvisioner.java@@ -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));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.javaindex f435a15392..d1d7944ca3 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.java@@ -48,7 +48,8 @@ class CustomResourceProvisionerTest {provisioner = new CloudFormationResourceProvisioner(null, null, null, null, lambdaService, null, null, null, null, null,- null, null, null, null, null, null, mapper, store, endpoint, null, null, null, null, null, null, null, null, null, null, null, null);+ null, null, null, null, null, null, mapper, store, endpoint, null, null, null, null, null, null, null, null, null, null, null, null,+ new io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry(java.util.List.of()));}private CloudFormationTemplateEngine engine() {diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.javaindex ee82b7f7b4..be11803e61 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java@@ -46,7 +46,8 @@ class RdsCfnProvisionerTest {null, null, null, null, null, null,mapper,null, null, null, null, null, null, null,- rdsService, null, null, null, null, null, null);+ rdsService, null, null, null, null, null, null,+ new io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry(java.util.List.of()));}private CloudFormationTemplateEngine engine() {diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SqsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SqsCfnProvisionerTest.javanew file mode 100644index 0000000000..611f1a6fae--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SqsCfnProvisionerTest.java@@ -0,0 +1,101 @@+package io.github.hectorvent.floci.services.cloudformation.provisioners;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;+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 org.junit.jupiter.api.Test;++import java.util.HashMap;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++/**+ * The SQS CFN provisioner in isolation — the payoff of item 15's decomposition: one mocked+ * service instead of the ~30 the monolithic provisioner needed.+ */+class SqsCfnProvisionerTest {++ private final SqsService sqs = mock(SqsService.class);+ private final SqsCfnProvisioner provisioner = new SqsCfnProvisioner(sqs);+ private final ObjectMapper mapper = new ObjectMapper();++ private ProvisionContext ctx() {+ // The engine is a collaborator; for scalar properties it just returns the node's text,+ // which is all these SQS cases exercise. Mocking keeps this a true isolated unit test.+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);+ when(engine.resolve(any())).thenAnswer(inv -> {+ JsonNode node = inv.getArgument(0);+ return node == null ? null : node.asText();+ });+ return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");+ }++ private StackResource resource(String type, String logicalId) {+ StackResource r = new StackResource();+ r.setLogicalId(logicalId);+ r.setResourceType(type);+ r.setAttributes(new HashMap<>());+ return r;+ }++ @Test+ void queueSetsPhysicalIdAndGetAttAttributes() {+ when(sqs.createQueue(eq("the-queue"), any(), eq("us-east-1")))+ .thenReturn(new Queue("the-queue", "http://localhost:4566/000000000000/the-queue"));+ StackResource r = resource("AWS::SQS::Queue", "MyQueue");+ ObjectNode props = mapper.createObjectNode().put("QueueName", "the-queue");++ provisioner.provision(r, props, ctx());++ assertEquals("http://localhost:4566/000000000000/the-queue", r.getPhysicalId());+ assertEquals("arn:aws:sqs:us-east-1:000000000000:the-queue", r.getAttributes().get("Arn"));+ assertEquals("the-queue", r.getAttributes().get("QueueName"));+ assertEquals("http://localhost:4566/000000000000/the-queue", r.getAttributes().get("QueueUrl"));+ }++ @Test+ void queueWithoutNameGeneratesPhysicalName() {+ when(sqs.createQueue(anyString(), any(), eq("us-east-1")))+ .thenAnswer(inv -> new Queue(inv.getArgument(0), "http://q/" + inv.getArgument(0)));+ StackResource r = resource("AWS::SQS::Queue", "MyQueue");++ provisioner.provision(r, mapper.createObjectNode(), ctx());++ // <stack>-<logicalId>-<suffix>, capped at 80+ assertEquals("my-stack-MyQueue", r.getAttributes().get("QueueName").replaceAll("-[0-9a-f]{12}$", ""));+ }++ @Test+ void queuePolicyGetsAPhysicalId() {+ StackResource r = resource("AWS::SQS::QueuePolicy", "MyPolicy");+ provisioner.provision(r, mapper.createObjectNode(), ctx());+ assertNotNull(r.getPhysicalId());+ assertTrue(r.getPhysicalId().startsWith("queue-policy-"));+ verifyNoInteractions(sqs);+ }++ @Test+ void deleteQueueDelegatesToService() {+ provisioner.delete("AWS::SQS::Queue", "http://q/url", "us-east-1");+ verify(sqs).deleteQueue("http://q/url", "us-east-1");+ }++ @Test+ void deleteQueuePolicyIsNoOp() {+ provisioner.delete("AWS::SQS::QueuePolicy", "queue-policy-abc", "us-east-1");+ verifyNoInteractions(sqs);+ }+}