diff --git a/AGENTS.md b/AGENTS.md index 280a2fe4d1..69b8ebf8ed 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -275,9 +275,9 @@ When adding functionality: ## Adding a CloudFormation Resource Type -**Do not add cases to `CloudFormationResourceProvisioner`.** That class is a legacy -monolith being dismantled; new types go in per-service provisioners under -`services/cloudformation/provisioners/`. +**Every type is served by a per-service provisioner under +`services/cloudformation/provisioners/`.** `CfnResourceDispatcher` only routes a resource to +the registry and stubs what nothing serves; never add type-specific code to it. 1. Add the type to the existing `CfnProvisioner`, or create one: `@ApplicationScoped`, injecting only the service it wraps. CDI discovery via @@ -514,8 +514,8 @@ Treat release workflows as critical infrastructure. - Producing inconsistent URLs or ARNs - Testing only with raw HTTP - Introducing unnecessary new patterns -- Adding a CloudFormation type to `CloudFormationResourceProvisioner` instead of a - per-service provisioner +- Adding type-specific code to `CfnResourceDispatcher` instead of a per-service + provisioner - Setting a CloudFormation resource's physical id but not its `Fn::GetAtt` attributes (they are two separate mechanisms, and the miss is silent) - Hand-editing the resource-type table in `docs/services/cloudformation.md`, which is diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7a868646c7..a30b601dae 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -185,10 +185,10 @@ Always implement the **real AWS wire protocol**. Never invent custom endpoints. ## Adding a CloudFormation Resource Type -CloudFormation resource types live in **per-service provisioner classes**, not in -`CloudFormationResourceProvisioner`. That class is a legacy monolith being dismantled, so please do -not add cases to it. If the service you need already has a `*CfnProvisioner`, add your type there; -otherwise create one. +CloudFormation resource types live in **per-service provisioner classes** under +`services/cloudformation/provisioners/`; `CfnResourceDispatcher` only routes a resource to the +registry and stubs what nothing serves, so please do not add type-specific code to it. If the +service you need already has a `*CfnProvisioner`, add your type there; otherwise create one. 1. Create `services/cloudformation/provisioners/CfnProvisioner.java`, annotate it `@ApplicationScoped`, and inject **only** the service it wraps. Registration is automatic: diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerReachableEndpoint.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerReachableEndpoint.java index 1dbde68256..fb91c4b761 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerReachableEndpoint.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerReachableEndpoint.java @@ -20,7 +20,7 @@ import java.net.URI; *
  • {@link LaunchedContainerAwsEnv}, which sets the AWS endpoint for Lambda, ECS, Flink and MWAA * containers
  • *
  • {@code Ec2ContainerManager}, for the {@code AWS_ENDPOINT_URL} of EC2 instance containers
  • - *
  • {@code CloudFormationResourceProvisioner}, for the {@code ResponseURL} a custom resource + *
  • {@code CustomResourceCfnProvisioner}, for the {@code ResponseURL} a custom resource * Lambda PUTs its result to
  • * * diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlService.java b/src/main/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlService.java index f34488c9d2..fc59a63975 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlService.java @@ -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 requestStore; private final AccountAwareStorageBackend 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 requestStore, AccountAwareStorageBackend 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, 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.java deleted file mode 100644 index e7814e3f3d..0000000000 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ /dev/null @@ -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 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 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). - * - *

    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 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 existingAttributes, Consumer 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 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 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 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; - } -} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index 63c855d822..583482c9a5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -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 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 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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java index fbf118b1e2..3182194d7d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java @@ -40,6 +40,20 @@ public class CloudFormationTemplateEngine { private final UnaryOperator dynamicReferenceResolver; private final List 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 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 parameters, Map physicalIds, diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/InlineZipPackager.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/InlineZipPackager.java index 447d7c3741..4cc12dc0c2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/InlineZipPackager.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/InlineZipPackager.java @@ -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.

    + * Kept separate from {@code LambdaCfnProvisioner} so other callers can share it unchanged.

    */ public final class InlineZipPackager { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java index c06b419cd6..831a64c3cb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java @@ -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 diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisioner.java index 22ef0c0a15..400a399d8e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisioner.java @@ -24,15 +24,14 @@ import java.util.function.Function; * Provisions {@code AWS::AutoScaling::AutoScalingGroup} and * {@code AWS::AutoScaling::LaunchConfiguration}. * - *

    Extracted from {@code CloudFormationResourceProvisioner}. The two types share a provisioner + *

    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. * - *

    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. + *

    Both types delete by physical id alone, so the id-only delete override serves them. */ @ApplicationScoped public class AutoScalingGroupCfnProvisioner implements CfnResourceProvisioner { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BatchCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BatchCfnProvisioner.java index 730da3e32d..236d882cc5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BatchCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BatchCfnProvisioner.java @@ -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. * *

    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 diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java new file mode 100644 index 0000000000..ee6e3503a8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java @@ -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. + * + *

    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). + * + *

    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 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 existingAttributes, Consumer 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 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 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)); + } +} 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.java index 5a438609f8..4a424c1f08 100644 --- 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.java @@ -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}. * *

    {@code provision} mutates the passed {@link StackResource} in place — setting its physical diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java index e6c9c34534..a123e0b544 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java @@ -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"; 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.java index a62c389b67..952497427d 100644 --- 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.java @@ -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 { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java index ad7c280156..ddd9d0fb99 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java @@ -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. diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CustomResourceCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CustomResourceCfnProvisioner.java index 30ac751942..b973ac13a9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CustomResourceCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CustomResourceCfnProvisioner.java @@ -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. * *

    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 diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisioner.java index 8ae05a236f..d1f31a04ad 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisioner.java @@ -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}. * - *

    Extracted from {@code CloudFormationResourceProvisioner}. A global table is provisioned as a + *

    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 diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java index 70823677cf..df058bc4d3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java @@ -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 |} (what * Ref returns on AWS and what a delete needs), and an EIP, whose Ref is its public IP. diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java index d428c560b9..30fa7dd50d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java @@ -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 { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisioner.java index 84f69cac29..7b31d852db 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisioner.java @@ -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. * *

    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 diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCfnProvisioner.java index 104272da0c..86631a5721 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCfnProvisioner.java @@ -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 diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.java index 86e09394c4..dd2c4c9662 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.java @@ -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 { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java index 59b5c959de..a6d5c090c9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java @@ -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. * *

    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 diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java index 7383dcfeca..d03f570004 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java @@ -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 diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamUserCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamUserCfnProvisioner.java index 091971270d..bac757d20c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamUserCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamUserCfnProvisioner.java @@ -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 { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KmsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KmsCfnProvisioner.java index 71bbfba5c0..e321c4d39f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KmsCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KmsCfnProvisioner.java @@ -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 parseCfnTags(JsonNode tagsNode, ProvisionContext ctx) { tagsNode = ctx.engine().resolveNode(tagsNode); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java index 6d0e54488a..859d498afa 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java @@ -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}. */ diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisioner.java index a3c50baf9c..8d4b8ea101 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisioner.java @@ -18,8 +18,8 @@ import java.util.Set; /** * CloudFormation provisioning for {@code AWS::Lambda::Version} and {@code AWS::Lambda::Alias}. * - *

    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 + *

    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 :production}) fails with "Alias not found" even though * the template declared the alias and the stack reported CREATE_COMPLETE. 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.java index c9e4ca9e10..e9047eb40e 100644 --- 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.java @@ -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, diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java index ee2d37ffad..e9a8f38edb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java @@ -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. * *

    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}. * *

    Unlike most extractions this one does not take {@code RdsService} out of the monolith. diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SecretTargetAttachmentCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SecretTargetAttachmentCfnProvisioner.java index 2db6fce57d..9765e5b574 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SecretTargetAttachmentCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SecretTargetAttachmentCfnProvisioner.java @@ -27,7 +27,7 @@ import java.util.Set; /** * Provisions {@code AWS::SecretsManager::SecretTargetAttachment}. * - *

    Extracted from {@code CloudFormationResourceProvisioner}. Unlike most provisioners this one + *

    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 { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SecretsManagerCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SecretsManagerCfnProvisioner.java index 05966efb18..160787c30d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SecretsManagerCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SecretsManagerCfnProvisioner.java @@ -18,14 +18,13 @@ import java.util.Set; /** * Provisions {@code AWS::SecretsManager::Secret}. * - *

    Extracted from {@code CloudFormationResourceProvisioner}. The sibling type + *

    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. * - *

    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. + *

    The secret deletes by physical id alone, so the id-only delete override serves it. */ @ApplicationScoped public class SecretsManagerCfnProvisioner implements CfnResourceProvisioner { 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.java index 68c8ea4f47..ebea149958 100644 --- 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.java @@ -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 { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/StepFunctionsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/StepFunctionsCfnProvisioner.java index b1e662959b..108eeede4a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/StepFunctionsCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/StepFunctionsCfnProvisioner.java @@ -29,7 +29,7 @@ import java.util.regex.Pattern; /** * Provisions {@code AWS::StepFunctions::StateMachine}. * - *

    Extracted from {@code CloudFormationResourceProvisioner}. This type carried the last + *

    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. diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/UpdateCleanupResult.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/UpdateCleanupResult.java index 6db7396fd0..8757695094 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/UpdateCleanupResult.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/UpdateCleanupResult.java @@ -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}. * - *

    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. + *

    It lives in this package so a {@link CfnResourceProvisioner} can return one and + * {@code CfnResourceDispatcher} can aggregate it. */ public record UpdateCleanupResult( boolean applicable, diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlServiceTest.java index e0289a7021..15a5dc6485 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlServiceTest.java @@ -4,7 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; -import io.github.hectorvent.floci.services.cloudformation.CloudFormationResourceProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ec2.model.Tag; @@ -33,7 +33,7 @@ class CloudControlServiceTest { @Test void accountScopesCreateStatusLookupAndDelete() throws Exception { - CloudFormationResourceProvisioner provisioner = mock(CloudFormationResourceProvisioner.class); + CfnResourceDispatcher provisioner = mock(CfnResourceDispatcher.class); StackResource resource = new StackResource(); resource.setPhysicalId("vpc-account-a"); resource.setAttributes(Map.of("VpcId", "vpc-account-a")); @@ -61,20 +61,18 @@ class CloudControlServiceTest { CloudControlService.ProgressEvent deniedDelete = service.deleteResource( "us-east-1", "222222222222", "AWS::EC2::VPC", "vpc-account-a"); assertEquals("FAILED", deniedDelete.operationStatus()); - verify(provisioner, never()).deleteStandalone(anyString(), - anyString(), anyString(), - anyString(), anyMap()); + verify(provisioner, never()).deleteStandalone(anyString(), anyString(), anyString(), anyMap()); CloudControlService.ProgressEvent deleted = service.deleteResource( "us-east-1", "111111111111", "AWS::EC2::VPC", "vpc-account-a"); assertEquals("SUCCESS", deleted.operationStatus()); verify(provisioner).deleteStandalone("AWS::EC2::VPC", "vpc-account-a", "us-east-1", - "111111111111", Map.of("VpcId", "vpc-account-a")); + Map.of("VpcId", "vpc-account-a")); } @Test void restoresAccountOwnersAndRequestStateFromMetadataStores() throws Exception { - CloudFormationResourceProvisioner provisioner = mock(CloudFormationResourceProvisioner.class); + CfnResourceDispatcher provisioner = mock(CfnResourceDispatcher.class); StackResource resource = new StackResource(); resource.setPhysicalId("igw-persisted"); when(provisioner.provisionStandalone(eq("AWS::EC2::InternetGateway"), @@ -120,7 +118,7 @@ class CloudControlServiceTest { ObjectMapper mapper = new ObjectMapper(); CloudControlService service = new CloudControlService( mock(S3Service.class), ec2Service, mock(IamService.class), - mock(CloudFormationResourceProvisioner.class), mapper); + mock(CfnResourceDispatcher.class), mapper); String properties = service.listResources("us-east-1", "AWS::EC2::VPC").getFirst().properties(); JsonNode tags = mapper.readTree(properties).path("Tags"); @@ -140,7 +138,7 @@ class CloudControlServiceTest { void listResourcesRejectsARealButUnbackedTypeInsteadOfReturningEmpty() { CloudControlService service = new CloudControlService( mock(S3Service.class), mock(Ec2Service.class), mock(IamService.class), - mock(CloudFormationResourceProvisioner.class), new ObjectMapper()); + mock(CfnResourceDispatcher.class), new ObjectMapper()); AwsException e = assertThrows(AwsException.class, () -> service.listResources("us-east-1", "AWS::SQS::Queue")); @@ -153,7 +151,7 @@ class CloudControlServiceTest { void listResourcesRejectsATypeThatDoesNotExistInAwsAtAll() { CloudControlService service = new CloudControlService( mock(S3Service.class), mock(Ec2Service.class), mock(IamService.class), - mock(CloudFormationResourceProvisioner.class), new ObjectMapper()); + mock(CfnResourceDispatcher.class), new ObjectMapper()); AwsException e = assertThrows(AwsException.class, () -> service.listResources("us-east-1", "AWS::NoSuch::Type")); @@ -168,7 +166,7 @@ class CloudControlServiceTest { when(s3Service.listBuckets()).thenReturn(List.of()); CloudControlService service = new CloudControlService( s3Service, mock(Ec2Service.class), mock(IamService.class), - mock(CloudFormationResourceProvisioner.class), new ObjectMapper()); + mock(CfnResourceDispatcher.class), new ObjectMapper()); assertTrue(service.listResources("us-east-1", "AWS::S3::Bucket").isEmpty()); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java index 50f1cf339b..8f66ba67f6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java @@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer; import io.github.hectorvent.floci.services.apigatewayv2.model.Route; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayV2CfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry; import io.github.hectorvent.floci.services.s3.S3Service; import org.junit.jupiter.api.BeforeEach; @@ -37,7 +38,7 @@ class ApiGatewayV2CfnProvisionerTest { private static final String API_ID = "api-123"; private final ObjectMapper mapper = new ObjectMapper(); private ApiGatewayV2Service apiGatewayV2Service; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnDeletePrecedenceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnDeletePrecedenceTest.java deleted file mode 100644 index 85e70a76e0..0000000000 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnDeletePrecedenceTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package io.github.hectorvent.floci.services.cloudformation; - -import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry; -import io.quarkus.test.junit.QuarkusTest; -import jakarta.inject.Inject; -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Guards the delete dispatch order in {@link CloudFormationResourceProvisioner}. - * - *

    Deleting a resource takes one of three routes: an extracted provisioner, the attribute-aware - * branches for {@code DELETE_NEEDS_STACK_RESOURCE}, or the generic type/physicalId switch. The - * registry is consulted first so an exact match beats the {@code Custom::} prefix branch, which is - * what lets {@code Custom::DynamoDBReplica} move to a provisioner at all. - * - *

    The cost of registry-first is that a leftover attribute-aware branch for a migrated type - * becomes unreachable rather than wrong. That is the safe direction, but it would let a slice quietly - * drop delete logic that only that branch implemented, so this test makes the overlap a build - * failure: migrating one of those types must move its logic into the provisioner's - * {@code delete(StackResource, String)} override and drop its entry from the set. - */ -@QuarkusTest -class CfnDeletePrecedenceTest { - - @Inject - CloudFormationResourceRegistry registry; - - @Test - void noTypeIsServedByBothAProvisionerAndAnAttributeAwareBranch() { - List both = CloudFormationResourceProvisioner.DELETE_NEEDS_STACK_RESOURCE.stream() - .filter(type -> registry.forType(type).isPresent()) - .sorted() - .toList(); - - assertTrue(both.isEmpty(), - "These types have an extracted provisioner, so their attribute-aware delete branch " - + "is now unreachable. Move that logic into the provisioner's " - + "delete(StackResource, String) override and remove the entry from " - + "DELETE_NEEDS_STACK_RESOURCE: " + both); - } - - /** - * Every attribute-aware type is one Floci actually provisions. A typo in the set - * ({@code AWS::Events::Rules}) would never match, sending the real type down the - * type/physicalId path where its delete silently no-ops and leaves the resource live. - */ - @Test - void everyAttributeAwareTypeIsAProvisionedType() { - List unknown = CloudFormationResourceProvisioner.DELETE_NEEDS_STACK_RESOURCE.stream() - .filter(type -> registry.forType(type).isEmpty()) - .filter(type -> !CloudFormationResourceProvisioner.LEGACY_SWITCH_TYPES.contains(type)) - .sorted() - .toList(); - - assertTrue(unknown.isEmpty(), - "DELETE_NEEDS_STACK_RESOURCE names types that nothing provisions, so the entry is " - + "dead and the real type (if misspelled here) deletes by physical id alone: " - + unknown); - } -} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index 9a011299fe..200406f847 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.appsync.AppSyncService; import io.github.hectorvent.floci.services.autoscaling.AutoScalingService; import io.github.hectorvent.floci.services.batch.BatchService; 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.CloudFrontCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.ConfigCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.DynamoDbCfnProvisioner; @@ -132,7 +133,7 @@ import java.util.Arrays; import java.util.List; /** - * Builds {@link CloudFormationResourceProvisioner} for tests without a wall of positional nulls. + * Builds {@link CfnResourceDispatcher} for tests without a wall of positional nulls. * *

    The provisioner takes one constructor argument per service it still provisions, so every test * that built it directly had to pass 30-plus {@code null}s in the right order, and every argument @@ -704,12 +705,12 @@ final class CfnProvisionerFixture { : new CloudFormationResourceRegistry(inferredProvisioners()); } - public CloudFormationResourceProvisioner build() { + public CfnResourceDispatcher build() { if (!registryChosenByTest) { resourceRegistry = buildRegistry(); } ensureDynamicReferences(); - return new CloudFormationResourceProvisioner( + return new CfnResourceDispatcher( objectMapper, resourceRegistry, dynamicReferences, diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnResourceInventoryTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnResourceInventoryTest.java index a1fe13c8fb..b4c2fb3315 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnResourceInventoryTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnResourceInventoryTest.java @@ -24,11 +24,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; /** * Pins the full set of CloudFormation resource types Floci provisions, and who serves each one. * - *

    This is the guard for the per-service provisioner migration. {@code provision}'s default arm + *

    This is the guard against a type quietly losing its provisioner. {@code CfnResourceDispatcher} * stubs an unknown type with {@code arn:aws:stub:::} and reports CREATE_COMPLETE, so a - * type that falls out of both the switch and the registry would otherwise pass every test while - * provisioning nothing. Making the inventory a checked-in file turns each migration slice into an - * intentional two-line diff. + * type that falls out of the registry would otherwise pass every test while provisioning nothing. + * Making the inventory a checked-in file turns each ownership change into an intentional diff. * *

    Runs under {@code @QuarkusTest} deliberately: the registry is compared as CDI resolved it, so * a provisioner written without {@code @ApplicationScoped} is caught. That mistake leaves the @@ -40,7 +39,6 @@ class CfnResourceInventoryTest { private static final Path INVENTORY = Path.of("src/test/resources/cloudformation/supported-resource-types.tsv"); private static final Path SCHEMA_DIR = Path.of("local/aws/cfn-resource-schemas/us-east-1"); - private static final String LEGACY_OWNER = "LEGACY_SWITCH"; /** * Types with no CloudFormation registry schema. {@code AWS::CDK::Metadata} is emitted by the @@ -52,32 +50,17 @@ class CfnResourceInventoryTest { CloudFormationResourceRegistry registry; @Test - void inventoryMatchesTheRegistryAndTheLegacySwitch() { + void inventoryMatchesTheRegistry() { Map actual = new TreeMap<>(); for (String type : registry.registeredTypes()) { actual.put(type, registry.ownerOf(type)); } - for (String type : CloudFormationResourceProvisioner.LEGACY_SWITCH_TYPES) { - actual.put(type, LEGACY_OWNER); - } assertEquals(render(readInventory()), render(actual), "The provisioned resource-type inventory changed. If that was intentional, write " + "this exact content to " + INVENTORY + "."); } - @Test - void noTypeIsServedByBothTheRegistryAndTheSwitch() { - List both = registry.registeredTypes().stream() - .filter(CloudFormationResourceProvisioner.LEGACY_SWITCH_TYPES::contains) - .sorted() - .toList(); - - assertTrue(both.isEmpty(), - "A type served by an extracted provisioner must have its switch arm removed; the " - + "registry wins, leaving the arm as dead code that still looks live: " + both); - } - @Test void inventoryFileIsSortedAndFreeOfDuplicates() { List types = readTypeColumn(); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnSchemaCoverageTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnSchemaCoverageTest.java index 13cbfd1f5c..d66224eae0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnSchemaCoverageTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnSchemaCoverageTest.java @@ -134,10 +134,6 @@ class CfnSchemaCoverageTest { for (Map.Entry entry : inventory().entrySet()) { String type = entry.getKey(); String owner = entry.getValue(); - if ("LEGACY_SWITCH".equals(owner)) { - // The switch is being dismantled type by type; its arms are audited as they move. - continue; - } Set declared = schemaReadOnlyAttributes(type); ProvisionerScan scan = scans.get(owner); Set set = scan == null ? Set.of() : scan.attributesFor(type); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteIdempotencyTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteIdempotencyTest.java index b1b11250a2..2741b329bd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteIdempotencyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteIdempotencyTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.cloudformation; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaService; import org.junit.jupiter.api.BeforeEach; @@ -20,7 +21,7 @@ class CloudFormationDeleteIdempotencyTest { private DynamoDbService dynamoDbService; private LambdaService lambdaService; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2ProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2ProvisionerTest.java index d49f64ba08..77855ab316 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2ProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2ProvisionerTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ec2.model.Instance; @@ -31,7 +32,7 @@ class CloudFormationEc2ProvisionerTest { private final ObjectMapper mapper = new ObjectMapper(); private Ec2Service ec2Service; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java index 9dfac042af..a1268e2f3e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +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.IamManagedPolicyCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.IamPolicyCfnProvisioner; @@ -43,7 +44,7 @@ class CloudFormationIamAttachmentProvisionerTest { private final ObjectMapper mapper = new ObjectMapper(); private IamService iamService; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { @@ -404,7 +405,7 @@ class CloudFormationIamAttachmentProvisionerTest { assertEquals("old-user", result.getAttributes().get("InlineUserTargets")); assertEquals("old-group", result.getAttributes().get("InlineGroupTargets")); assertEquals("true", result.getAttributes().get( - CloudFormationResourceProvisioner.UPDATE_ROLLBACK_RESTORED_ATTR)); + CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR)); verify(iamService).deleteRolePolicy("new-role", policyName); verify(iamService, never()).deleteRolePolicy("old-role", policyName); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java index d8d6f6c116..674191a0d4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java @@ -8441,7 +8441,7 @@ class CloudFormationIntegrationTest { @Test void createStack_samFunctionWithPackageTypeImageDeploysAsImageFunction() { - // Without PackageType carried through by the SAM transform, CloudFormationResourceProvisioner + // Without PackageType carried through by the SAM transform, the Lambda provisioner // defaults PackageType to "Zip" (buildLambdaDesiredState's resolveOrDefault), which then also // forces Runtime/Handler defaults onto a function that declared neither — the function is // created as a broken Zip function instead of running the real container image. @@ -8495,7 +8495,7 @@ class CloudFormationIntegrationTest { @Test void createStack_samFunctionWithImageConfigDeploysWithOverrides() { - // ImageConfig must also be carried through the SAM transform to CloudFormationResourceProvisioner, + // ImageConfig must also be carried through the SAM transform to the Lambda provisioner, // which already reads it (provisionLambda's putResolvedMapIfPresent(configRequest, props, // "ImageConfig", ...)) — without the transform copying it, a PackageType: Image SAM function's // EntryPoint/Command/WorkingDirectory override silently never reaches the deployed function. @@ -8660,7 +8660,7 @@ class CloudFormationIntegrationTest { void createStack_samHttpApiAuthorizerHonorsCustomIdentitySource() { // SAM's Authorizers..IdentitySource lets a JWT authorizer read the token from // somewhere other than the default Authorization header — e.g. a query-string token, - // the same case CloudFormationResourceProvisioner/ApiGatewayExecuteController already + // the same case the API Gateway provisioner/ApiGatewayExecuteController already // support end-to-end for raw (non-SAM) templates. The SAM transform must forward it // rather than always emitting the header default. String template = """ diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaHotReloadCodeTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaHotReloadCodeTest.java index 8700a269a4..1358887a1a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaHotReloadCodeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaHotReloadCodeTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambda.model.LambdaFunction; import io.github.hectorvent.floci.services.s3.S3Service; @@ -39,7 +40,7 @@ class CloudFormationLambdaHotReloadCodeTest { private final ObjectMapper mapper = new ObjectMapper(); private S3Service s3Service; private LambdaService lambdaService; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaLegacyNameModeTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaLegacyNameModeTest.java index 590c46e8b7..e2ef44f2c6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaLegacyNameModeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaLegacyNameModeTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaCfnProvisioner; import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambda.model.LambdaFunction; @@ -39,7 +40,7 @@ class CloudFormationLambdaLegacyNameModeTest { private final ObjectMapper mapper = new ObjectMapper(); private LambdaService lambdaService; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaS3CodeProbeTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaS3CodeProbeTest.java index 27ec049fd3..6319447fc9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaS3CodeProbeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaS3CodeProbeTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambda.model.LambdaFunction; import io.github.hectorvent.floci.services.s3.S3Service; @@ -43,7 +44,7 @@ class CloudFormationLambdaS3CodeProbeTest { private final ObjectMapper mapper = new ObjectMapper(); private S3Service s3Service; private LambdaService lambdaService; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.java index 504862439b..1ed00071cb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -34,7 +35,7 @@ class CloudFormationLogGroupProvisionerTest { private final ObjectMapper mapper = new ObjectMapper(); private CloudWatchLogsService logsService; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRestoreIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRestoreIntegrationTest.java index 7b4ce05572..d5bcce023a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRestoreIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRestoreIntegrationTest.java @@ -4,6 +4,7 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet; import io.github.hectorvent.floci.services.cloudformation.model.Stack; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.quarkus.arc.ClientProxy; import io.quarkus.test.junit.QuarkusMock; import io.quarkus.test.junit.QuarkusTest; @@ -35,11 +36,10 @@ import static org.mockito.Mockito.withSettings; * provisioning, then checks that the execution it rejects leaves its stack and change set as * they were. * - *

    The provisioner bean is swapped for a mock whose default answer blocks {@code provision} - * for this test's stacks and forwards everything else to the real provisioner. The answer - * recognises those calls by method name and stack name rather than by stubbing one overload, - * because the service picks whichever {@code provision} overload the current main branch has, - * and a stubbing tied to an older overload silently returns null once main adds a new one. + *

    The dispatcher bean is swapped for a mock whose default answer blocks {@code provision} + * for this test's stacks and forwards everything else to the real dispatcher. The answer + * recognises those calls by method name and stack name rather than by stubbing one overload, so + * it does not depend on which {@code provision} overload the service calls. */ @QuarkusTest class CloudFormationServiceRestoreIntegrationTest { @@ -57,20 +57,20 @@ class CloudFormationServiceRestoreIntegrationTest { CloudFormationService service; @Inject - CloudFormationResourceProvisioner provisioner; + CfnResourceDispatcher provisioner; private final CountDownLatch activeOperations = new CountDownLatch(ACTIVE_OPERATIONS); private final CountDownLatch releaseOperations = new CountDownLatch(1); - private CloudFormationResourceProvisioner blockingProvisioner; + private CfnResourceDispatcher blockingProvisioner; @BeforeEach void blockProvisioningForTestStacks() { Answer realProvisioner = AdditionalAnswers.delegatesTo(ClientProxy.unwrap(provisioner)); - blockingProvisioner = Mockito.mock(CloudFormationResourceProvisioner.class, + blockingProvisioner = Mockito.mock(CfnResourceDispatcher.class, withSettings().defaultAnswer(invocation -> isTestStackProvision(invocation) ? provisionAfterRelease(invocation) : realProvisioner.answer(invocation))); - QuarkusMock.installMockForType(blockingProvisioner, CloudFormationResourceProvisioner.class); + QuarkusMock.installMockForType(blockingProvisioner, CfnResourceDispatcher.class); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.java index ae576626f1..0656b36ca0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.java @@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.cloudformation.model.Stack; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.s3.S3Service; import io.github.hectorvent.floci.services.ssm.SsmService; import org.junit.jupiter.api.BeforeEach; @@ -35,12 +36,12 @@ class CloudFormationServiceRollbackTest { private static final String ACCOUNT = "000000000000"; private static final String REGION = "us-east-1"; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; private CloudFormationService service; @BeforeEach void setUp() { - provisioner = mock(CloudFormationResourceProvisioner.class); + provisioner = mock(CfnResourceDispatcher.class); EmulatorConfig config = mock(EmulatorConfig.class); when(config.defaultAccountId()).thenReturn(ACCOUNT); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStepFunctionsCleanupIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStepFunctionsCleanupIntegrationTest.java index 438f67699b..e1616acea0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStepFunctionsCleanupIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStepFunctionsCleanupIntegrationTest.java @@ -167,7 +167,7 @@ class CloudFormationStepFunctionsCleanupIntegrationTest { void updateAfterStubUpgradeProvisionsTheRealStateMachine() { // A stack that was created by a floci build that did not yet expand // AWS::Serverless::StateMachine had this resource stubbed with a non-ARN physical id - // (-<8 hex>, see CloudFormationResourceProvisioner's default provisioning arm). + // (-<8 hex>, see CfnResourceDispatcher's stub arm). // Its next update must provision the real state machine instead of failing with InvalidArn // when findStateMachine tries to describe that non-ARN value. String suffix = Long.toString(System.nanoTime(), 36); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationUnsupportedResourceTypeTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationUnsupportedResourceTypeTest.java index 9ba8cc0143..9dfc15ebfd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationUnsupportedResourceTypeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationUnsupportedResourceTypeTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -56,7 +57,7 @@ class CloudFormationUnsupportedResourceTypeTest { + "MyThing-11a79dff is not removed here."; private final ObjectMapper mapper = new ObjectMapper(); - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { @@ -114,8 +115,8 @@ class CloudFormationUnsupportedResourceTypeTest { @Test void deleteOfUnsupportedTypeDoesNotThrow() { - // The same arm catches a type no provisioner ever created and a type the create switch does - // provision and this switch does not remove, so the line says what it leaves behind rather + // The same path catches a type no provisioner ever created and one that was only stubbed, + // neither of which left anything behind, so the line says what it leaves behind rather // than claiming nothing was created. List logged = new CopyOnWriteArrayList<>(); @@ -130,7 +131,7 @@ class CloudFormationUnsupportedResourceTypeTest { "expected the skipped delete to be reported at warn, got: " + rendered(logged)); } - private CloudFormationResourceProvisioner provisionerWithStubAllowed(boolean allowed) { + private CfnResourceDispatcher provisionerWithStubAllowed(boolean allowed) { EmulatorConfig config = mock(EmulatorConfig.class); EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); EmulatorConfig.CloudFormationServiceConfig cloudformation = @@ -150,7 +151,7 @@ class CloudFormationUnsupportedResourceTypeTest { private T whileCapturingProvisionerLogs(List collected, java.util.function.Supplier action) { java.util.logging.Logger logger = - java.util.logging.Logger.getLogger(CloudFormationResourceProvisioner.class.getName()); + java.util.logging.Logger.getLogger(CfnResourceDispatcher.class.getName()); Level original = logger.getLevel(); Handler handler = new Handler() { @Override diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProviderFrameworkTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProviderFrameworkTest.java index 6772b04c4a..1004ae8dba 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProviderFrameworkTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProviderFrameworkTest.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambda.model.InvocationType; import io.github.hectorvent.floci.services.lambda.model.InvokeResult; @@ -42,7 +43,7 @@ class CustomResourceProviderFrameworkTest { private LambdaService lambdaService; private ProviderFrameworkDetector detector; private CustomResourceResponseStore store; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { 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.java index 6943663e7e..1b81ca98dc 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 @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambda.model.InvocationType; import io.github.hectorvent.floci.services.lambda.model.InvokeResult; @@ -37,7 +38,7 @@ class CustomResourceProvisionerTest { private final ObjectMapper mapper = new ObjectMapper(); private LambdaService lambdaService; private CustomResourceResponseStore store; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbReplicaCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbReplicaCfnProvisionerTest.java index 64649172f7..c01865ddad 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbReplicaCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbReplicaCfnProvisionerTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -25,7 +26,7 @@ class DynamoDbReplicaCfnProvisionerTest { private final ObjectMapper mapper = new ObjectMapper(); private DynamoDbService dynamoDbService; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbStreamSpecificationCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbStreamSpecificationCfnProvisionerTest.java index 2a2e2f3682..e5763f20f4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbStreamSpecificationCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbStreamSpecificationCfnProvisionerTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition; import org.junit.jupiter.api.BeforeEach; @@ -42,7 +43,7 @@ class DynamoDbStreamSpecificationCfnProvisionerTest { private final ObjectMapper mapper = new ObjectMapper(); private DynamoDbService dynamoDbService; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusDeleteOwnershipTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusDeleteOwnershipTest.java index cf2eedaae4..80423e6616 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusDeleteOwnershipTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusDeleteOwnershipTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudformation; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; import io.github.hectorvent.floci.services.eventbridge.model.EventBus; import org.junit.jupiter.api.BeforeEach; @@ -30,7 +31,7 @@ class EventBusDeleteOwnershipTest { private static final String CREATED_TIME_ATTR = "FlociEventBusCreatedTime"; private EventBridgeService eventBridgeService; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusProvisionOwnershipTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusProvisionOwnershipTest.java index 5284565cee..4bafd252a8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusProvisionOwnershipTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusProvisionOwnershipTest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; import io.github.hectorvent.floci.services.eventbridge.model.EventBus; import org.junit.jupiter.api.BeforeEach; @@ -44,7 +45,7 @@ class EventBusProvisionOwnershipTest { private static final ObjectMapper MAPPER = new ObjectMapper(); private EventBridgeService eventBridgeService; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { 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.java index 5eb57ddd70..c6f9bb8c67 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 @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.cloudformation.provisioners.UpdateCleanupResult; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.rds.RdsService; @@ -66,7 +67,7 @@ class RdsCfnProvisionerTest { private RdsService rdsService; private SecretsManagerService secretsManagerService; private SsmService ssmService; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; private Function importResolver; private Map conditions; @@ -122,7 +123,7 @@ class RdsCfnProvisionerTest { */ private StackResource provisionUpdate(String logicalId, String type, String json, String existingPhysicalId) { return provisioner.provision(logicalId, type, props(json), engine(), - "us-east-1", "000000000000", "my-stack", existingPhysicalId); + "us-east-1", "000000000000", "my-stack", existingPhysicalId, Map.of()); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java index fe6ac1b9bc..e45e4ddf3b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java @@ -1321,7 +1321,7 @@ class SamTransformIntegrationTest { .extract().asString(); // AGENTS.md:289-291 asks for the exact Fn::GetAtt key set the provisioner publishes - // (CloudFormationResourceProvisioner.java:4231-4233): Arn, Name, StateMachineRevisionId. + // (StepFunctionsCfnProvisioner): Arn, Name, StateMachineRevisionId. // Asserting only "not a stub ARN" (as red loop 2 did) would also pass on an empty Output. String machineArn = stackOutputValue(describeStacks, "MachineArn"); assertThat(machineArn, startsWith("arn:aws:states:")); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java index b9c29de3ca..a22865171f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java @@ -250,7 +250,7 @@ class SamTransformProcessorTest { @Test void expandSamTemplate_functionWithPackageTypeImage() throws Exception { // PackageType must be carried through to the expanded AWS::Lambda::Function: without it, - // CloudFormationResourceProvisioner.buildLambdaDesiredState defaults PackageType to "Zip" + // LambdaCfnProvisioner.buildLambdaDesiredState defaults PackageType to "Zip" // (resolveOrDefault(props, "PackageType", engine, "Zip")), which then forces Runtime/Handler // defaults (nodejs18.x / index.handler) onto a function that never had either — the function // gets created as a Zip function running the wrong runtime instead of the real container image. @@ -276,7 +276,7 @@ class SamTransformProcessorTest { assertEquals("000000000000.dkr.ecr.us-east-1.localhost:4566/my-repo:latest", lambdaProps.path("Code").path("ImageUri").asText()); // No Handler/Runtime were declared and none should be synthesized by the transform itself — - // CloudFormationResourceProvisioner is responsible for not defaulting them once it sees + // LambdaCfnProvisioner is responsible for not defaulting them once it sees // PackageType: Image (verified separately in CloudFormationIntegrationTest). assertTrue(lambdaProps.path("Handler").isMissingNode()); assertTrue(lambdaProps.path("Runtime").isMissingNode()); @@ -325,7 +325,7 @@ class SamTransformProcessorTest { @Test void expandSamTemplate_functionWithImageConfig() throws Exception { // ImageConfig (EntryPoint/Command/WorkingDirectory overrides for a container-image - // function) must also be carried through: CloudFormationResourceProvisioner.provisionLambda + // function) must also be carried through: LambdaCfnProvisioner // already reads it (putResolvedMapIfPresent(configRequest, props, "ImageConfig", ...)), but // the SAM transform previously dropped it, silently losing any container entry-point/command // override on a PackageType: Image SAM function. diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.java index f44e212c22..8848d6b29f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; import io.github.hectorvent.floci.services.docdb.DocDbService; import io.github.hectorvent.floci.services.docdb.model.DocDbCluster; import io.github.hectorvent.floci.services.docdb.model.DocDbInstance; @@ -54,7 +55,7 @@ class SecretTargetAttachmentCfnProvisionerTest { private SecretsManagerService secretsManagerService; private RdsService rdsService; private DocDbService docDbService; - private CloudFormationResourceProvisioner provisioner; + private CfnResourceDispatcher provisioner; @BeforeEach void setUp() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcherTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcherTest.java new file mode 100644 index 0000000000..c086ef5510 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcherTest.java @@ -0,0 +1,119 @@ +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.services.cloudformation.model.StackResource; +import org.junit.jupiter.api.Test; + +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * The dispatch itself: what reaches the owning provisioner and how Cloud Control's stack-less + * path is wired. The stub arm and strict mode are pinned by + * {@code CloudFormationUnsupportedResourceTypeTest}. + */ +class CfnResourceDispatcherTest { + + private static final String TYPE = "AWS::Test::Thing"; + + private final ObjectMapper mapper = new ObjectMapper(); + private final CloudFormationResourceRegistry registry = mock(CloudFormationResourceRegistry.class); + private final CfnDynamicReferences dynamicReferences = mock(CfnDynamicReferences.class); + private final CfnResourceDispatcher dispatcher = + new CfnResourceDispatcher(mapper, registry, dynamicReferences, null); + + @Test + void provisionStandaloneResolvesDynamicReferencesThroughTheService() { + // Cloud Control desired state can carry {{resolve:...}}; the throwaway engine must reach + // the same resolver a stack's engine does. + when(dynamicReferences.resolveDynamicReferences("{{resolve:ssm:/p}}", "us-east-1", false)) + .thenReturn("resolved"); + AtomicReference seen = new AtomicReference<>(); + when(registry.forType(TYPE)).thenReturn(Optional.of(provisioner((resource, ctx) -> { + seen.set(ctx.engine().resolve(mapper.getNodeFactory().textNode("{{resolve:ssm:/p}}"))); + resource.setPhysicalId("thing-1"); + }))); + + StackResource resource = dispatcher.provisionStandalone(TYPE, mapper.createObjectNode(), + "us-east-1", "000000000000"); + + assertEquals("resolved", seen.get()); + assertEquals("thing-1", resource.getPhysicalId()); + assertEquals("CREATE_COMPLETE", resource.getStatus()); + } + + @Test + void provisionSeedsTheResourceAndTheContextWithThePriorIdentity() { + AtomicReference seenContext = new AtomicReference<>(); + AtomicReference> seenAttributes = new AtomicReference<>(); + when(registry.forType(TYPE)).thenReturn(Optional.of(provisioner((resource, ctx) -> { + seenContext.set(ctx); + seenAttributes.set(Map.copyOf(resource.getAttributes())); + }))); + + StackResource resource = dispatcher.provision("Thing", TYPE, mapper.createObjectNode(), null, + "us-east-1", "000000000000", "my-stack", "thing-prior", Map.of("Arn", "arn-prior")); + + assertEquals("thing-prior", seenContext.get().priorPhysicalId()); + assertEquals("my-stack", seenContext.get().stackName()); + assertEquals(Map.of("Arn", "arn-prior"), seenAttributes.get()); + assertEquals("thing-prior", resource.getPhysicalId(), "an owner that sets nothing keeps the prior id"); + assertEquals("CREATE_COMPLETE", resource.getStatus()); + } + + @Test + void deleteHandsTheOwnerTheWholeResource() { + CfnResourceProvisioner owner = mock(CfnResourceProvisioner.class); + when(registry.forType(TYPE)).thenReturn(Optional.of(owner)); + StackResource resource = new StackResource(); + resource.setResourceType(TYPE); + resource.setPhysicalId("thing-1"); + + dispatcher.delete(resource, "us-east-1"); + + verify(owner).delete(resource, "us-east-1"); + verify(owner, never()).delete(anyString(), anyString(), anyString()); + } + + @Test + void deleteStandaloneCarriesTheRecordedAttributes() { + CfnResourceProvisioner owner = mock(CfnResourceProvisioner.class); + when(registry.forType(TYPE)).thenReturn(Optional.of(owner)); + + dispatcher.deleteStandalone(TYPE, "thing-1", "us-east-1", Map.of("Role", "r")); + + verify(owner).delete(any(StackResource.class), anyString()); + verify(owner).delete(org.mockito.ArgumentMatchers.argThat((StackResource r) -> + "thing-1".equals(r.getPhysicalId()) && "r".equals(r.getAttributes().get("Role"))), any()); + } + + private static CfnResourceProvisioner provisioner(Provision body) { + return new CfnResourceProvisioner() { + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public void provision(StackResource resource, JsonNode properties, ProvisionContext ctx) { + body.run(resource, ctx); + } + }; + } + + @FunctionalInterface + private interface Provision { + void run(StackResource resource, ProvisionContext ctx); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java index d4fb00ef9d..57955b4873 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java @@ -33,9 +33,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** - * The single-service CloudFormation provisioners extracted from - * {@code CloudFormationResourceProvisioner} together, since each is a handful of lines with one - * service call. + * The single-service CloudFormation provisioners extracted from the former CloudFormation + * monolith together, since each is a handful of lines with one service call. * *

    Every case asserts the exact physical id and the exact {@code Fn::GetAtt} attribute keys. * Asserting status alone would prove nothing: an unmapped type still reports CREATE_COMPLETE via diff --git a/tools/docs/regen_cfn_resource_types.py b/tools/docs/regen_cfn_resource_types.py index 7b760df479..df334f53f9 100644 --- a/tools/docs/regen_cfn_resource_types.py +++ b/tools/docs/regen_cfn_resource_types.py @@ -2,8 +2,7 @@ """Regenerate the "Supported Resource Types" table in docs/services/cloudformation.md. The set of types comes from src/test/resources/cloudformation/supported-resource-types.tsv, -which CfnResourceInventoryTest pins to the CDI-resolved provisioner registry plus the legacy -switch. Presentation (row order, service labels, notes) comes from cfn_resource_types.yaml. +which CfnResourceInventoryTest pins to the CDI-resolved provisioner registry. Presentation (row order, service labels, notes) comes from cfn_resource_types.yaml. Deliberately reads the TSV rather than parsing the Java: several provisioners return `Set.of(CONSTANT, CONSTANT)` from resourceTypes(), so a source regex sees only a subset. The @@ -154,15 +153,14 @@ def check_provisioner_annotations() -> list[str]: def check_no_double_ownership(inventory) -> list[str]: - """A type served by a provisioner must not also sit in the legacy switch.""" + """A type has exactly one provisioner; the registry refuses a duplicate only at boot.""" owners: dict[str, set[str]] = {} for resource_type, owner in inventory: owners.setdefault(resource_type, set()).add(owner) return [ - f"{resource_type} is claimed by both the legacy switch and {sorted(o - {'LEGACY_SWITCH'})[0]}; " - f"the registry wins, leaving the switch arm as dead code" + f"{resource_type} is claimed by {' and '.join(sorted(o))}; a type has exactly one provisioner" for resource_type, o in sorted(owners.items()) - if len(o) > 1 and "LEGACY_SWITCH" in o + if len(o) > 1 ] diff --git a/tools/docs/test_regen_cfn_resource_types.py b/tools/docs/test_regen_cfn_resource_types.py index d8e55b9b68..35096c42e8 100644 --- a/tools/docs/test_regen_cfn_resource_types.py +++ b/tools/docs/test_regen_cfn_resource_types.py @@ -44,7 +44,7 @@ def test_two_segment_type_keeps_its_prefix(): # --------------------------------------------------------------------------- # def test_renders_one_row_per_namespace_in_configured_order(): lines, warnings = render( - [("AWS::SQS::Queue", "SqsCfnProvisioner"), ("AWS::S3::Bucket", "LEGACY_SWITCH")] + [("AWS::SQS::Queue", "SqsCfnProvisioner"), ("AWS::S3::Bucket", "S3CfnProvisioner")] ) assert lines[0] == "| Service | Resource types |" # S3 is in the order list, SQS is not, so SQS is appended after it. @@ -55,9 +55,9 @@ def test_renders_one_row_per_namespace_in_configured_order(): def test_unlisted_types_sort_alphabetically_after_curated_ones(): inventory = [ - ("AWS::S3::AccessPoint", "LEGACY_SWITCH"), - ("AWS::S3::Bucket", "LEGACY_SWITCH"), - ("AWS::S3::BucketPolicy", "LEGACY_SWITCH"), + ("AWS::S3::AccessPoint", "S3CfnProvisioner"), + ("AWS::S3::Bucket", "S3CfnProvisioner"), + ("AWS::S3::BucketPolicy", "S3CfnProvisioner"), ] lines, _ = render(inventory, type_order={"AWS::S3": ["Bucket", "BucketPolicy"]}) assert lines[2] == "| S3 | `Bucket`, `BucketPolicy`, `AccessPoint` |" @@ -65,7 +65,7 @@ def test_unlisted_types_sort_alphabetically_after_curated_ones(): def test_notes_and_row_notes_are_appended(): lines, _ = render( - [("AWS::S3::Bucket", "LEGACY_SWITCH")], + [("AWS::S3::Bucket", "S3CfnProvisioner")], notes={"AWS::S3::Bucket": "accepted; policy not enforced"}, row_notes={"AWS::S3": "Trailing prose."}, ) @@ -74,7 +74,7 @@ def test_notes_and_row_notes_are_appended(): def test_display_names_override_the_leaf(): lines, _ = render( - [("AWS::CDK::Metadata", "LEGACY_SWITCH")], + [("AWS::CDK::Metadata", "CdkMetadataCfnProvisioner")], service_labels={**BASE_CONFIG["service_labels"], "AWS::CDK": "CDK"}, display_names={"AWS::CDK::Metadata": "CDK::Metadata"}, ) @@ -84,8 +84,8 @@ def test_display_names_override_the_leaf(): def test_merged_namespace_folds_into_one_row(): lines, _ = render( [ - ("AWS::CloudFormation::CustomResource", "LEGACY_SWITCH"), - ("Custom::DynamoDBReplica", "LEGACY_SWITCH"), + ("AWS::CloudFormation::CustomResource", "CustomResourceCfnProvisioner"), + ("Custom::DynamoDBReplica", "DynamoDbCfnProvisioner"), ], merge_namespaces={"Custom": "AWS::CloudFormation"}, ) @@ -96,7 +96,7 @@ def test_merged_namespace_folds_into_one_row(): def test_extra_types_appear_after_inventory_types(): lines, _ = render( - [("AWS::CloudFormation::CustomResource", "LEGACY_SWITCH")], + [("AWS::CloudFormation::CustomResource", "CustomResourceCfnProvisioner")], extra_types={ "AWS::CloudFormation": [ {"name": "Stack", "note": "nested stacks", "reason": "not a provisioner type"} @@ -116,7 +116,7 @@ def test_warns_when_a_namespace_has_no_label(): def test_warns_when_type_order_names_a_type_nothing_provisions(): _, warnings = render( - [("AWS::S3::Bucket", "LEGACY_SWITCH")], + [("AWS::S3::Bucket", "S3CfnProvisioner")], type_order={"AWS::S3": ["Bucket", "Buckett"]}, ) assert any("lists Buckett" in w for w in warnings) @@ -124,24 +124,24 @@ def test_warns_when_type_order_names_a_type_nothing_provisions(): def test_warns_when_an_extra_type_has_no_reason(): _, warnings = render( - [("AWS::CloudFormation::CustomResource", "LEGACY_SWITCH")], + [("AWS::CloudFormation::CustomResource", "CustomResourceCfnProvisioner")], extra_types={"AWS::CloudFormation": [{"name": "Stack"}]}, ) assert any("has no reason" in w for w in warnings) -def test_warns_when_a_type_is_claimed_by_both_the_switch_and_a_provisioner(): - # The registry wins, so the switch arm is dead code that still looks live. +def test_warns_when_a_type_is_claimed_by_two_provisioners(): + # The registry throws on a duplicate at boot; the inventory check catches it before that. warnings = r.check_no_double_ownership( - [("AWS::SQS::Queue", "LEGACY_SWITCH"), ("AWS::SQS::Queue", "SqsCfnProvisioner")] + [("AWS::SQS::Queue", "OtherCfnProvisioner"), ("AWS::SQS::Queue", "SqsCfnProvisioner")] ) assert len(warnings) == 1 - assert "SqsCfnProvisioner" in warnings[0] + assert "SqsCfnProvisioner" in warnings[0] and "OtherCfnProvisioner" in warnings[0] def test_no_double_ownership_warning_when_each_type_has_one_owner(): assert r.check_no_double_ownership( - [("AWS::SQS::Queue", "SqsCfnProvisioner"), ("AWS::S3::Bucket", "LEGACY_SWITCH")] + [("AWS::SQS::Queue", "SqsCfnProvisioner"), ("AWS::S3::Bucket", "S3CfnProvisioner")] ) == []