Light, fluffy, and always free - The AWS Local Emulator alternative
refactor(cloudformation): move the DynamoDB types into DynamoDbCfnProvisioner (#3699)
Hector Ventura77007656aac7
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.javaindex f5fe70dd35..b21f9b7618 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java@@ -12,17 +12,11 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamiimport io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceProvisioner;import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2SecurityGroupRuleCfnProvisioner;import io.github.hectorvent.floci.services.cloudformation.provisioners.UpdateCleanupResult;-import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;import io.github.hectorvent.floci.services.eventbridge.model.BatchParameters;import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer;import io.github.hectorvent.floci.services.eventbridge.model.RuleState;import io.github.hectorvent.floci.services.eventbridge.model.SqsParameters;import io.github.hectorvent.floci.services.eventbridge.model.Target;-import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;-import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;-import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;-import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;-import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;import io.github.hectorvent.floci.services.ecr.EcrService;import io.github.hectorvent.floci.services.ecr.model.Repository;import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;@@ -55,7 +49,6 @@ import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion;import io.github.hectorvent.floci.services.pipes.PipesService;import io.github.hectorvent.floci.services.pipes.model.DesiredState;import io.github.hectorvent.floci.services.s3.S3Service;-import io.github.hectorvent.floci.services.sns.SnsService;import io.github.hectorvent.floci.services.sqs.SqsService;import io.github.hectorvent.floci.services.ssm.SsmService;import io.github.hectorvent.floci.services.ssm.model.Parameter;@@ -109,9 +102,6 @@ public class CloudFormationResourceProvisioner {private static final String NAME_MODE_EXPLICIT = "explicit";private static final String NAME_MODE_GENERATED = "generated";private static final int GENERATED_NAME_SUFFIX_LENGTH = 12;- private static final String DDB_REPLICA_TABLE_NAME_ATTR = "TableName";- private static final String DDB_REPLICA_REGION_ATTR = "__FlociDynamoDbReplicaRegion";- private static final String DDB_REPLICA_SKIP_DELETION_ATTR = "__FlociDynamoDbReplicaSkipDeletion";private static final int LAMBDA_DEFAULT_TIMEOUT_SECONDS = 3;private static final int LAMBDA_DEFAULT_MEMORY_MB = 128;private static final int LAMBDA_DEFAULT_EPHEMERAL_STORAGE_MB = 512;@@ -146,8 +136,7 @@ public class CloudFormationResourceProvisioner {"AWS::CloudFormation::CustomResource","AWS::EKS::Nodegroup","AWS::IAM::ManagedPolicy",- "AWS::IAM::Policy",- "Custom::DynamoDBReplica");+ "AWS::IAM::Policy");static final Set<String> LEGACY_SWITCH_TYPES = Set.of("AWS::ApiGateway::Authorizer",@@ -163,8 +152,6 @@ public class CloudFormationResourceProvisioner {"AWS::ApiGatewayV2::Route","AWS::ApiGatewayV2::Stage","AWS::CloudFormation::CustomResource",- "AWS::DynamoDB::GlobalTable",- "AWS::DynamoDB::Table","AWS::EC2::Instance","AWS::EC2::SecurityGroup","AWS::EKS::Cluster",@@ -175,8 +162,7 @@ public class CloudFormationResourceProvisioner {"AWS::IAM::Policy","AWS::Lambda::Function","AWS::Lambda::LayerVersion",- "AWS::Route53::RecordSet",- "Custom::DynamoDBReplica");+ "AWS::Route53::RecordSet");/** Reserved attribute keys used to carry custom-resource state to the later Delete invocation. */private static final String CR_SERVICE_TOKEN_ATTR = "__FlociServiceToken";@@ -189,7 +175,6 @@ public class CloudFormationResourceProvisioner {private static final Duration CR_RESPONSE_TIMEOUT = Duration.ofSeconds(10);private final S3Service s3Service;- private final DynamoDbService dynamoDbService;private final LambdaService lambdaService;private final IamService iamService;private final ApiGatewayService apiGatewayService;@@ -209,7 +194,6 @@ public class CloudFormationResourceProvisioner {@Injectpublic CloudFormationResourceProvisioner(S3Service s3Service,- SnsService snsService, DynamoDbService dynamoDbService,LambdaService lambdaService, IamService iamService,SsmService ssmService, KmsService kmsService,ApiGatewayService apiGatewayService,@@ -231,7 +215,6 @@ public class CloudFormationResourceProvisioner {EmulatorConfig config) {this.config = config;this.s3Service = s3Service;- this.dynamoDbService = dynamoDbService;this.lambdaService = lambdaService;this.iamService = iamService;this.apiGatewayService = apiGatewayService;@@ -287,8 +270,6 @@ public class CloudFormationResourceProvisioner {return resource;}switch (resourceType) {- case "AWS::DynamoDB::Table", "AWS::DynamoDB::GlobalTable" ->- provisionDynamoTable(resource, properties, engine, region, accountId, stackName);case "AWS::Lambda::Function" -> provisionLambda(resource, properties, engine, region, accountId, stackName);case "AWS::Lambda::LayerVersion" ->provisionLambdaLayerVersion(resource, properties, engine, region, stackName);@@ -312,7 +293,6 @@ public class CloudFormationResourceProvisioner {case "AWS::ApiGatewayV2::Deployment" -> provisionApiGatewayV2Deployment(resource, properties, engine, region);case "AWS::CloudFormation::CustomResource" ->provisionCustomResource(resource, properties, engine, region, accountId, stackName);- case "Custom::DynamoDBReplica" -> provisionDynamoDbReplica(resource, properties, engine, region);// EC2 networking. These delegate to Ec2Service so the resources actually exist// (describe-subnets, ELBv2, etc. can find them) instead of being stubbed with a// fake physical id. Topological ordering guarantees parents are provisioned first.@@ -432,7 +412,7 @@ public class CloudFormationResourceProvisioner {// 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- // (so Custom::DynamoDBReplica can move to a provisioner), and that migrating one of the+ // (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) {@@ -458,12 +438,6 @@ public class CloudFormationResourceProvisioner {*/private void deleteUsingCreateTimeAttributes(StackResource resource, String region) {String resourceType = resource.getResourceType();- // Custom::DynamoDBReplica is applied natively against the DynamoDB service (not via its- // provider Lambda), so remove the replica the same way rather than invoking the handler.- if ("Custom::DynamoDBReplica".equals(resourceType)) {- deleteDynamoDbReplicaSafe(resource, region);- return;- }if ("AWS::CloudFormation::CustomResource".equals(resourceType)) {deleteCustomResource(resource, region);return;@@ -528,7 +502,6 @@ public class CloudFormationResourceProvisioner {return;}switch (resourceType) {- case "AWS::DynamoDB::Table" -> deleteDynamoTableSafe(physicalId, region);case "AWS::Lambda::Function" -> deleteLambdaFunctionSafe(physicalId, region);// AWS::IAM::Policy is inline: it is removed together with its owning principal (see// IamRoleCfnProvisioner#delete), or precisely via the StackResource-aware delete path.@@ -944,139 +917,6 @@ public class CloudFormationResourceProvisioner {// ── SNS ───────────────────────────────────────────────────────────────────- // ── DynamoDB ──────────────────────────────────────────────────────────────-- private void provisionDynamoTable(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,- String region, String accountId, String stackName) {- String tableName = resolveOptional(props, "TableName", engine);- if (tableName == null || tableName.isBlank()) {- tableName = generatePhysicalName(stackName, r.getLogicalId(), 255, false);- }-- List<KeySchemaElement> keySchema = new ArrayList<>();- List<AttributeDefinition> attrDefs = new ArrayList<>();- List<GlobalSecondaryIndex> gsis = new ArrayList<>();- List<LocalSecondaryIndex> lsis = new ArrayList<>();-- if (props != null && props.has("KeySchema")) {- for (JsonNode ks : props.get("KeySchema")) {- String attrName = engine.resolve(ks.get("AttributeName"));- String keyType = engine.resolve(ks.get("KeyType"));- keySchema.add(new KeySchemaElement(attrName, keyType));- }- }- if (props != null && props.has("AttributeDefinitions")) {- for (JsonNode ad : props.get("AttributeDefinitions")) {- String attrName = engine.resolve(ad.get("AttributeName"));- String attrType = engine.resolve(ad.get("AttributeType"));- attrDefs.add(new AttributeDefinition(attrName, attrType));- }- }-- if (props != null && props.has("GlobalSecondaryIndexes")) {- for (JsonNode gsiNode : props.get("GlobalSecondaryIndexes")) {- String indexName = engine.resolve(gsiNode.get("IndexName"));- List<KeySchemaElement> gsiKeySchema = new ArrayList<>();- if (gsiNode.has("KeySchema")) {- for (JsonNode ks : gsiNode.get("KeySchema")) {- String attrName = engine.resolve(ks.get("AttributeName"));- String keyType = engine.resolve(ks.get("KeyType"));- gsiKeySchema.add(new KeySchemaElement(attrName, keyType));- }- }- String projectionType = "ALL";- JsonNode projection = gsiNode.get("Projection");- List<String> nonKeyAttributes = new ArrayList<>();- if (projection != null && projection.has("ProjectionType")) {- projectionType = engine.resolve(projection.get("ProjectionType"));- JsonNode nonKeyAttrArray = projection.path("NonKeyAttributes");- if (!nonKeyAttrArray.isMissingNode() && nonKeyAttrArray.isArray()){- for (JsonNode nonKeyAttr : nonKeyAttrArray){- nonKeyAttributes.add(nonKeyAttr.asText());- }- }- }- gsis.add(new GlobalSecondaryIndex(indexName, gsiKeySchema, null, projectionType, nonKeyAttributes));- }- }-- if (props != null && props.has("LocalSecondaryIndexes")) {- for (JsonNode lsiNode : props.get("LocalSecondaryIndexes")) {- String indexName = engine.resolve(lsiNode.get("IndexName"));- List<KeySchemaElement> lsiKeySchema = new ArrayList<>();- if (lsiNode.has("KeySchema")) {- for (JsonNode ks : lsiNode.get("KeySchema")) {- String attrName = engine.resolve(ks.get("AttributeName"));- String keyType = engine.resolve(ks.get("KeyType"));- lsiKeySchema.add(new KeySchemaElement(attrName, keyType));- }- }- String projectionType = "ALL";- JsonNode projection = lsiNode.get("Projection");- if (projection != null && projection.has("ProjectionType")) {- projectionType = engine.resolve(projection.get("ProjectionType"));- }- lsis.add(new LocalSecondaryIndex(indexName, lsiKeySchema, null, projectionType));- }- }-- if (keySchema.isEmpty()) {- keySchema.add(new KeySchemaElement("id", "HASH"));- attrDefs.add(new AttributeDefinition("id", "S"));- }-- TableDefinition table;- try {- table = dynamoDbService.createTable(tableName, keySchema, attrDefs, null, null, gsis, lsis, region);- } catch (AwsException e) {- if (!"ResourceInUseException".equals(e.getErrorCode())) {- throw e;- }- table = dynamoDbService.describeTable(tableName, region);- }-- Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);- List<String> staleTags = ProvisionContext.staleTagKeys(- dynamoDbService.listTagsOfResource(table.getTableArn(), region), tags);- if (!staleTags.isEmpty()) {- dynamoDbService.untagResource(table.getTableArn(), staleTags, region);- }- if (!tags.isEmpty()) {- dynamoDbService.tagResource(table.getTableArn(), tags, region);- }-- // A template that declares StreamSpecification wants a stream. Unlike the DynamoDB API,- // the CloudFormation property carries no StreamEnabled flag — declaring the block IS the- // request — so its presence alone turns the stream on. Without this the table is created- // streamless and an event source mapping polls its ARN forever.- //- // Removing the block on an update is the inverse request: the stream is reconciled off,- // or a table updated out of streaming would keep emitting records to whatever still holds- // its ARN.- JsonNode streamSpec = props != null ? props.path("StreamSpecification") : null;- if (streamSpec != null && streamSpec.isObject()) {- String viewType = streamSpec.has("StreamViewType")- ? engine.resolve(streamSpec.get("StreamViewType"))- : null;- table = dynamoDbService.enableStream(tableName, viewType, region);- } else if (table.isStreamEnabled()) {- table = dynamoDbService.disableStream(tableName, region);- }-- r.setPhysicalId(tableName);- r.getAttributes().put("Arn", table.getTableArn());- // Only a live stream has an ARN worth handing to Fn::GetAtt. Publishing one unconditionally- // resolved to nothing on a streamless table; publishing the retained ARN of a stream that- // has since been switched off would resolve to something no longer running. An update- // starts from the previous attributes, so the stale entry has to be removed rather than- // merely left unwritten.- if (table.isStreamEnabled() && table.getStreamArn() != null) {- r.getAttributes().put("StreamArn", table.getStreamArn());- } else {- r.getAttributes().remove("StreamArn");- }- }-// ── Lambda ────────────────────────────────────────────────────────────────private void provisionLambda(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,@@ -3427,79 +3267,6 @@ public class CloudFormationResourceProvisioner {}}- /**- * Provisions a {@code Custom::DynamoDBReplica} — the custom resource the CDK legacy global-table- * (dynamodb.Table.replicationRegions) emits per replica region. Its provider Lambda simply calls- * DynamoDB UpdateTable with a ReplicaUpdates Create, so apply that directly rather than running- * the async CDK Provider framework. {@code Ref} (PhysicalResourceId) follows CDK's- * {@code <tableName>-<region>} format.- */- private void provisionDynamoDbReplica(StackResource r, JsonNode props,- CloudFormationTemplateEngine engine, String region) {- String tableName = resolveOptional(props, "TableName", engine);- String replicaRegion = resolveOptional(props, "Region", engine);- if (tableName == null || tableName.isBlank()) {- throw new AwsException("ValidationError",- "Custom::DynamoDBReplica " + r.getLogicalId() + " is missing TableName", 400);- }- if (replicaRegion == null || replicaRegion.isBlank()) {- throw new AwsException("ValidationError",- "Custom::DynamoDBReplica " + r.getLogicalId() + " is missing Region", 400);- }- String priorTableName = r.getAttributes().get(DDB_REPLICA_TABLE_NAME_ATTR);- String priorRegion = r.getAttributes().get(DDB_REPLICA_REGION_ATTR);- if (priorRegion == null || priorRegion.isBlank()) {- priorRegion = replicaRegionFromPhysicalId(- r.getPhysicalId(), priorTableName != null ? priorTableName : tableName);- }- List<String> removeRegions = priorRegion != null- && !priorRegion.isBlank()- && !priorRegion.equals(replicaRegion)- ? List.of(priorRegion)- : List.of();- // Validate and persist replacement as one operation so an old-replica removal failure- // cannot leave the new replica applied while the resource still points at the old region.- dynamoDbService.applyReplicaUpdates(- tableName, List.of(replicaRegion), removeRegions, region);- r.setPhysicalId(tableName + "-" + replicaRegion);- r.getAttributes().put(DDB_REPLICA_TABLE_NAME_ATTR, tableName);- r.getAttributes().put(DDB_REPLICA_REGION_ATTR, replicaRegion);- r.getAttributes().put(DDB_REPLICA_SKIP_DELETION_ATTR,- Boolean.toString(Boolean.TRUE.equals(- parseBooleanOrNull(resolveOptional(props, "SkipReplicaDeletion", engine)))));- }-- private void deleteDynamoDbReplicaSafe(StackResource r, String region) {- if (Boolean.parseBoolean(r.getAttributes().get(DDB_REPLICA_SKIP_DELETION_ATTR))) {- LOG.debugv("Keeping replica for retained Custom::DynamoDBReplica {0}", r.getLogicalId());- return;- }- String tableName = r.getAttributes().get(DDB_REPLICA_TABLE_NAME_ATTR);- String replicaRegion = r.getAttributes().get(DDB_REPLICA_REGION_ATTR);- if (replicaRegion == null || replicaRegion.isBlank()) {- replicaRegion = replicaRegionFromPhysicalId(r.getPhysicalId(), tableName);- }- if (tableName == null || tableName.isBlank() || replicaRegion == null || replicaRegion.isBlank()) {- return;- }- try {- dynamoDbService.applyReplicaUpdates(tableName, List.of(), List.of(replicaRegion), region);- } catch (Exception e) {- LOG.debugv("Could not remove replica {0} from table {1}: {2}",- replicaRegion, tableName, e.getMessage());- }- }-- private static String replicaRegionFromPhysicalId(String physicalId, String tableName) {- if (physicalId == null || physicalId.isBlank()) {- return null;- }- String prefix = tableName + "-";- return tableName != null && !tableName.isBlank() && physicalId.startsWith(prefix)- ? physicalId.substring(prefix.length())- : physicalId;- }-// Reads the ResourceProperties stashed at the last create/update (CR_PROPERTIES_ATTR).// Returns null when nothing is stashed or it cannot be parsed.private ObjectNode readStashedProperties(StackResource r) {@@ -3618,10 +3385,6 @@ public class CloudFormationResourceProvisioner {}}- private static Boolean parseBooleanOrNull(String value) {- return (value == null || value.isBlank()) ? null : Boolean.valueOf(value);- }-private static String textOrNull(JsonNode node, String field) {return node != null && node.hasNonNull(field) ? node.path(field).asText() : null;}@@ -3688,17 +3451,6 @@ public class CloudFormationResourceProvisioner {}}- private void deleteDynamoTableSafe(String tableName, String region) {- try {- dynamoDbService.deleteTable(tableName, region);- } catch (AwsException e) {- if (!"ResourceNotFoundException".equals(e.getErrorCode())) {- throw e;- }- LOG.debugv("DynamoDB table already gone, treating as deleted: {0}", tableName);- }- }-private void deleteLambdaFunctionSafe(String functionName, String region) {try {lambdaService.deleteFunction(region, functionName);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.javanew file mode 100644index 0000000000..f555540726--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisioner.java@@ -0,0 +1,325 @@+package io.github.hectorvent.floci.services.cloudformation.provisioners;++import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;+import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;+import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;+import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;+import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;+import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;+import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;++/**+ * Provisions {@code AWS::DynamoDB::Table}, {@code AWS::DynamoDB::GlobalTable} and the CDK legacy+ * global-table custom resource {@code Custom::DynamoDBReplica}.+ *+ * <p>Extracted from {@code CloudFormationResourceProvisioner}. A global table is provisioned as a+ * plain table: its {@code Replicas} property is not applied. The replica custom resource is the+ * one the CDK legacy global table ({@code dynamodb.Table.replicationRegions}) emits per replica+ * region. Its provider Lambda only calls UpdateTable with a ReplicaUpdates Create, so that call is+ * applied directly against the DynamoDB service rather than through the async CDK Provider+ * framework, and its delete removes the replica the same way instead of invoking the handler.+ * {@code Ref} of a replica follows CDK's {@code <tableName>-<region>} format.+ */+@ApplicationScoped+public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {++ static final String TABLE = "AWS::DynamoDB::Table";+ static final String GLOBAL_TABLE = "AWS::DynamoDB::GlobalTable";+ static final String REPLICA = "Custom::DynamoDBReplica";++ private static final Logger LOG = Logger.getLogger(DynamoDbCfnProvisioner.class);++ private static final String REPLICA_TABLE_NAME_ATTR = "TableName";+ private static final String REPLICA_REGION_ATTR = "__FlociDynamoDbReplicaRegion";+ private static final String REPLICA_SKIP_DELETION_ATTR = "__FlociDynamoDbReplicaSkipDeletion";+ private static final int TABLE_NAME_MAX_LENGTH = 255;++ private final DynamoDbService dynamoDbService;++ @Inject+ public DynamoDbCfnProvisioner(DynamoDbService dynamoDbService) {+ this.dynamoDbService = dynamoDbService;+ }++ @Override+ public Set<String> resourceTypes() {+ return Set.of(TABLE, GLOBAL_TABLE, REPLICA);+ }++ @Override+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {+ switch (r.getResourceType()) {+ case "AWS::DynamoDB::Table", "AWS::DynamoDB::GlobalTable" -> provisionTable(r, props, ctx);+ case "Custom::DynamoDBReplica" -> provisionReplica(r, props, ctx);+ default -> throw new IllegalStateException(+ "DynamoDbCfnProvisioner received an unsupported type: " + r.getResourceType());+ }+ }++ /**+ * A replica's delete needs the table name and region recorded at create time; the physical id+ * alone only carries them in CDK's {@code <tableName>-<region>} form, which is the fallback.+ */+ @Override+ public void delete(StackResource resource, String region) {+ switch (resource.getResourceType()) {+ case "Custom::DynamoDBReplica" -> deleteReplica(resource, region);+ default -> delete(resource.getResourceType(), resource.getPhysicalId(), region);+ }+ }++ @Override+ public void delete(String resourceType, String physicalId, String region) {+ switch (resourceType) {+ case "AWS::DynamoDB::Table", "AWS::DynamoDB::GlobalTable" -> CfnDeletes.safeDelete(+ "DynamoDB table", physicalId,+ () -> dynamoDbService.deleteTable(physicalId, region),+ "ResourceNotFoundException");+ // Nothing to derive from the id alone once the attributes are gone; the replica stays.+ case "Custom::DynamoDBReplica" -> LOG.warnv(+ "No delete implemented for resource type {0}: {1} is not removed here.",+ resourceType, physicalId);+ default -> throw new IllegalStateException(+ "DynamoDbCfnProvisioner received an unsupported type: " + resourceType);+ }+ }++ private void provisionTable(StackResource r, JsonNode props, ProvisionContext ctx) {+ CloudFormationTemplateEngine engine = ctx.engine();+ String region = ctx.region();+ String tableName = ctx.resolveOptional(props, "TableName");+ if (tableName == null || tableName.isBlank()) {+ tableName = ctx.generatePhysicalName(r.getLogicalId(), TABLE_NAME_MAX_LENGTH, false);+ }++ List<KeySchemaElement> keySchema = new ArrayList<>();+ List<AttributeDefinition> attrDefs = new ArrayList<>();+ List<GlobalSecondaryIndex> gsis = new ArrayList<>();+ List<LocalSecondaryIndex> lsis = new ArrayList<>();++ if (props != null && props.has("KeySchema")) {+ for (JsonNode ks : props.get("KeySchema")) {+ String attrName = engine.resolve(ks.get("AttributeName"));+ String keyType = engine.resolve(ks.get("KeyType"));+ keySchema.add(new KeySchemaElement(attrName, keyType));+ }+ }+ if (props != null && props.has("AttributeDefinitions")) {+ for (JsonNode ad : props.get("AttributeDefinitions")) {+ String attrName = engine.resolve(ad.get("AttributeName"));+ String attrType = engine.resolve(ad.get("AttributeType"));+ attrDefs.add(new AttributeDefinition(attrName, attrType));+ }+ }++ if (props != null && props.has("GlobalSecondaryIndexes")) {+ for (JsonNode gsiNode : props.get("GlobalSecondaryIndexes")) {+ String indexName = engine.resolve(gsiNode.get("IndexName"));+ List<KeySchemaElement> gsiKeySchema = new ArrayList<>();+ if (gsiNode.has("KeySchema")) {+ for (JsonNode ks : gsiNode.get("KeySchema")) {+ String attrName = engine.resolve(ks.get("AttributeName"));+ String keyType = engine.resolve(ks.get("KeyType"));+ gsiKeySchema.add(new KeySchemaElement(attrName, keyType));+ }+ }+ String projectionType = "ALL";+ JsonNode projection = gsiNode.get("Projection");+ List<String> nonKeyAttributes = new ArrayList<>();+ if (projection != null && projection.has("ProjectionType")) {+ projectionType = engine.resolve(projection.get("ProjectionType"));+ JsonNode nonKeyAttrArray = projection.path("NonKeyAttributes");+ if (!nonKeyAttrArray.isMissingNode() && nonKeyAttrArray.isArray()) {+ for (JsonNode nonKeyAttr : nonKeyAttrArray) {+ nonKeyAttributes.add(nonKeyAttr.asText());+ }+ }+ }+ gsis.add(new GlobalSecondaryIndex(indexName, gsiKeySchema, null, projectionType, nonKeyAttributes));+ }+ }++ if (props != null && props.has("LocalSecondaryIndexes")) {+ for (JsonNode lsiNode : props.get("LocalSecondaryIndexes")) {+ String indexName = engine.resolve(lsiNode.get("IndexName"));+ List<KeySchemaElement> lsiKeySchema = new ArrayList<>();+ if (lsiNode.has("KeySchema")) {+ for (JsonNode ks : lsiNode.get("KeySchema")) {+ String attrName = engine.resolve(ks.get("AttributeName"));+ String keyType = engine.resolve(ks.get("KeyType"));+ lsiKeySchema.add(new KeySchemaElement(attrName, keyType));+ }+ }+ String projectionType = "ALL";+ JsonNode projection = lsiNode.get("Projection");+ if (projection != null && projection.has("ProjectionType")) {+ projectionType = engine.resolve(projection.get("ProjectionType"));+ }+ lsis.add(new LocalSecondaryIndex(indexName, lsiKeySchema, null, projectionType));+ }+ }++ if (keySchema.isEmpty()) {+ keySchema.add(new KeySchemaElement("id", "HASH"));+ attrDefs.add(new AttributeDefinition("id", "S"));+ }++ TableDefinition table;+ try {+ table = dynamoDbService.createTable(tableName, keySchema, attrDefs, null, null, gsis, lsis, region);+ } catch (AwsException e) {+ if (!"ResourceInUseException".equals(e.getErrorCode())) {+ throw e;+ }+ table = dynamoDbService.describeTable(tableName, region);+ }++ Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);+ List<String> staleTags = ProvisionContext.staleTagKeys(+ dynamoDbService.listTagsOfResource(table.getTableArn(), region), tags);+ if (!staleTags.isEmpty()) {+ dynamoDbService.untagResource(table.getTableArn(), staleTags, region);+ }+ if (!tags.isEmpty()) {+ dynamoDbService.tagResource(table.getTableArn(), tags, region);+ }++ // A template that declares StreamSpecification wants a stream. Unlike the DynamoDB API,+ // the CloudFormation property carries no StreamEnabled flag: declaring the block IS the+ // request, so its presence alone turns the stream on. Without this the table is created+ // streamless and an event source mapping polls its ARN forever.+ //+ // Removing the block on an update is the inverse request: the stream is reconciled off,+ // or a table updated out of streaming would keep emitting records to whatever still holds+ // its ARN.+ JsonNode streamSpec = props != null ? props.path("StreamSpecification") : null;+ if (streamSpec != null && streamSpec.isObject()) {+ String viewType = streamSpec.has("StreamViewType")+ ? engine.resolve(streamSpec.get("StreamViewType"))+ : null;+ table = dynamoDbService.enableStream(tableName, viewType, region);+ } else if (table.isStreamEnabled()) {+ table = dynamoDbService.disableStream(tableName, region);+ }++ r.setPhysicalId(tableName);+ r.getAttributes().put("Arn", table.getTableArn());+ // Only the global table's registry schema declares TableId read-only; a plain table exposes+ // Arn and StreamArn alone, so publishing it there would accept a Fn::GetAtt CloudFormation+ // rejects. DescribeTable reports the same value, so Fn::GetAtt and the API agree.+ if (GLOBAL_TABLE.equals(r.getResourceType())) {+ r.getAttributes().put("TableId", table.getTableId());+ }+ // Only a live stream has an ARN worth handing to Fn::GetAtt. Publishing one unconditionally+ // resolved to nothing on a streamless table; publishing the retained ARN of a stream that+ // has since been switched off would resolve to something no longer running. An update+ // starts from the previous attributes, so the stale entry has to be removed rather than+ // merely left unwritten.+ if (table.isStreamEnabled() && table.getStreamArn() != null) {+ r.getAttributes().put("StreamArn", table.getStreamArn());+ } else {+ r.getAttributes().remove("StreamArn");+ }+ }++ private void provisionReplica(StackResource r, JsonNode props, ProvisionContext ctx) {+ String tableName = ctx.resolveOptional(props, "TableName");+ String replicaRegion = ctx.resolveOptional(props, "Region");+ if (tableName == null || tableName.isBlank()) {+ throw new AwsException("ValidationError",+ "Custom::DynamoDBReplica " + r.getLogicalId() + " is missing TableName", 400);+ }+ if (replicaRegion == null || replicaRegion.isBlank()) {+ throw new AwsException("ValidationError",+ "Custom::DynamoDBReplica " + r.getLogicalId() + " is missing Region", 400);+ }+ String priorTableName = r.getAttributes().get(REPLICA_TABLE_NAME_ATTR);+ String priorRegion = r.getAttributes().get(REPLICA_REGION_ATTR);+ if (priorRegion == null || priorRegion.isBlank()) {+ priorRegion = replicaRegionFromPhysicalId(+ r.getPhysicalId(), priorTableName != null ? priorTableName : tableName);+ }+ List<String> removeRegions = priorRegion != null+ && !priorRegion.isBlank()+ && !priorRegion.equals(replicaRegion)+ ? List.of(priorRegion)+ : List.of();+ // Validate and persist replacement as one operation so an old-replica removal failure+ // cannot leave the new replica applied while the resource still points at the old region.+ dynamoDbService.applyReplicaUpdates(+ tableName, List.of(replicaRegion), removeRegions, ctx.region());+ r.setPhysicalId(tableName + "-" + replicaRegion);+ r.getAttributes().put(REPLICA_TABLE_NAME_ATTR, tableName);+ r.getAttributes().put(REPLICA_REGION_ATTR, replicaRegion);+ r.getAttributes().put(REPLICA_SKIP_DELETION_ATTR,+ Boolean.toString(Boolean.TRUE.equals(+ parseBooleanOrNull(ctx.resolveOptional(props, "SkipReplicaDeletion")))));+ }++ private void deleteReplica(StackResource r, String region) {+ Map<String, String> attributes = r.getAttributes() != null ? r.getAttributes() : Map.of();+ if (Boolean.parseBoolean(attributes.get(REPLICA_SKIP_DELETION_ATTR))) {+ LOG.debugv("Keeping replica for retained Custom::DynamoDBReplica {0}", r.getLogicalId());+ return;+ }+ String tableName = attributes.get(REPLICA_TABLE_NAME_ATTR);+ String replicaRegion = attributes.get(REPLICA_REGION_ATTR);+ if (replicaRegion == null || replicaRegion.isBlank()) {+ replicaRegion = replicaRegionFromPhysicalId(r.getPhysicalId(), tableName);+ }+ if (tableName == null || tableName.isBlank() || replicaRegion == null || replicaRegion.isBlank()) {+ return;+ }+ // Removing a replica the table no longer has is already a no-op in the service, so the one+ // "already gone" case is the table itself; anything else must reach the stack as DELETE_FAILED.+ String removedTableName = tableName;+ String removedRegion = replicaRegion;+ CfnDeletes.safeDelete("DynamoDB replica", removedTableName + "-" + removedRegion,+ () -> dynamoDbService.applyReplicaUpdates(+ removedTableName, List.of(), List.of(removedRegion), region),+ "ResourceNotFoundException");+ }++ private static String replicaRegionFromPhysicalId(String physicalId, String tableName) {+ if (physicalId == null || physicalId.isBlank()) {+ return null;+ }+ String prefix = tableName + "-";+ return tableName != null && !tableName.isBlank() && physicalId.startsWith(prefix)+ ? physicalId.substring(prefix.length())+ : physicalId;+ }++ private static Boolean parseBooleanOrNull(String value) {+ return (value == null || value.isBlank()) ? null : Boolean.valueOf(value);+ }++ private Map<String, String> parseCfnTags(JsonNode tagsNode, CloudFormationTemplateEngine engine) {+ tagsNode = engine.resolveNode(tagsNode);+ Map<String, String> out = new HashMap<>();+ if (tagsNode == null || tagsNode.isNull() || !tagsNode.isArray()) {+ return out;+ }+ for (JsonNode entry : tagsNode) {+ JsonNode resolved = engine.resolveNode(entry);+ String key = resolved.path("Key").asText(null);+ String value = resolved.path("Value").asText("");+ if (key != null) {+ out.put(key, value);+ }+ }+ return out;+ }+}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.javaindex 0e3591dd6d..0fc8be7459 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@@ -13,6 +13,7 @@ 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.CloudFrontCfnProvisioner;import io.github.hectorvent.floci.services.cloudformation.provisioners.ConfigCfnProvisioner;+import io.github.hectorvent.floci.services.cloudformation.provisioners.DynamoDbCfnProvisioner;import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2FlowLogCfnProvisioner;import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaMicrovmsCfnProvisioner;import io.github.hectorvent.floci.services.cloudformation.provisioners.OrganizationsCfnProvisioner;@@ -239,6 +240,9 @@ final class CfnProvisionerFixture {if (snsService != null) {discovered.add(new SnsCfnProvisioner(snsService));}+ if (dynamoDbService != null) {+ discovered.add(new DynamoDbCfnProvisioner(dynamoDbService));+ }if (ssmService != null) {discovered.add(new SsmCfnProvisioner(ssmService));}@@ -661,8 +665,6 @@ final class CfnProvisionerFixture {ensureDynamicReferences();return new CloudFormationResourceProvisioner(s3Service,- snsService,- dynamoDbService,lambdaService,iamService,ssmService,diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDynamoDbGlobalTableIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDynamoDbGlobalTableIntegrationTest.javanew file mode 100644index 0000000000..042fba9ee0--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDynamoDbGlobalTableIntegrationTest.java@@ -0,0 +1,174 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.path.json.JsonPath;+import io.restassured.response.Response;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.time.Duration;++import static io.restassured.RestAssured.given;+import static org.awaitility.Awaitility.await;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.junit.jupiter.api.Assertions.fail;++/**+ * {@code AWS::DynamoDB::GlobalTable} through the per-service provisioner: {@code Ref} is the table+ * name, every read-only attribute the registry schema declares ({@code Arn}, {@code TableId})+ * resolves through {@code Fn::GetAtt} to the value DescribeTable reports, and deleting the stack+ * removes the table. A stack status alone proves nothing here: an unowned type is stubbed+ * CREATE_COMPLETE with an {@code arn:aws:stub} attribute, so the assertions compare against the+ * DynamoDB API.+ */+@QuarkusTest+class CloudFormationDynamoDbGlobalTableIntegrationTest {++ private static final String CFN_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";+ private static final String DDB_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/dynamodb/aws4_request";+ private static final String SSM_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ssm/aws4_request";+ private static final Duration STACK_DELETE_TIMEOUT = Duration.ofSeconds(30);+ private static final Duration STACK_DELETE_POLL_INTERVAL = Duration.ofMillis(50);++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void globalTableRefAndGetAttResolveToTheDescribedTableAndStackDeleteRemovesIt() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String tableName = "gt-v2-table-" + suffix;+ String stackName = "gt-v2-stack-" + suffix;+ String template = """+ {+ "Resources": {+ "Orders": {+ "Type": "AWS::DynamoDB::GlobalTable",+ "Properties": {+ "TableName": "%s",+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],+ "BillingMode": "PAY_PER_REQUEST",+ "Replicas": [{"Region": "us-east-1"}]+ }+ },+ "RefParam": {+ "Type": "AWS::SSM::Parameter",+ "Properties": {"Name": "/gt-v2/%s/ref", "Type": "String", "Value": {"Ref": "Orders"}}+ },+ "ArnParam": {+ "Type": "AWS::SSM::Parameter",+ "Properties": {"Name": "/gt-v2/%s/arn", "Type": "String",+ "Value": {"Fn::GetAtt": ["Orders", "Arn"]}}+ },+ "TableIdParam": {+ "Type": "AWS::SSM::Parameter",+ "Properties": {"Name": "/gt-v2/%s/table-id", "Type": "String",+ "Value": {"Fn::GetAtt": ["Orders", "TableId"]}}+ }+ }+ }+ """.formatted(tableName, suffix, suffix, suffix);++ createStack(stackName, template);+ assertStackStatus(stackName, "CREATE_COMPLETE");++ JsonPath described = describeTable(tableName).jsonPath();+ String tableArn = described.getString("Table.TableArn");+ String tableId = described.getString("Table.TableId");+ assertTrue(tableArn != null && tableArn.startsWith("arn:aws:dynamodb:"), "TableArn: " + tableArn);+ assertFalse(tableId == null || tableId.isBlank(), "DescribeTable reported no TableId");++ assertEquals(tableName, parameterValue("/gt-v2/" + suffix + "/ref"));+ assertEquals(tableArn, parameterValue("/gt-v2/" + suffix + "/arn"));+ assertEquals(tableId, parameterValue("/gt-v2/" + suffix + "/table-id"));++ deleteStack(stackName);+ awaitStackGone(stackName);++ given()+ .contentType("application/x-amz-json-1.0")+ .header("Authorization", DDB_AUTH)+ .header("X-Amz-Target", "DynamoDB_20120810.DescribeTable")+ .body("{\"TableName\":\"" + tableName + "\"}")+ .when().post("/").then().statusCode(400)+ .body("__type", containsString("ResourceNotFoundException"));+ }++ private void createStack(String stackName, String template) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when().post("/").then().statusCode(200);+ }++ private void assertStackStatus(String stackName, String status) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when().post("/").then().statusCode(200)+ .body(containsString("<StackStatus>" + status + "</StackStatus>"));+ }++ private void deleteStack(String stackName) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DeleteStack")+ .formParam("StackName", stackName)+ .when().post("/").then().statusCode(200);+ }++ private Response describeTable(String tableName) {+ return given()+ .contentType("application/x-amz-json-1.0")+ .header("Authorization", DDB_AUTH)+ .header("X-Amz-Target", "DynamoDB_20120810.DescribeTable")+ .body("{\"TableName\":\"" + tableName + "\"}")+ .when().post("/").then().statusCode(200)+ .body("Table.TableName", equalTo(tableName))+ .extract().response();+ }++ private String parameterValue(String name) {+ return given()+ .contentType("application/x-amz-json-1.1")+ .header("Authorization", SSM_AUTH)+ .header("X-Amz-Target", "AmazonSSM.GetParameter")+ .body("{\"Name\":\"" + name + "\"}")+ .when().post("/").then().statusCode(200)+ .extract().jsonPath().getString("Parameter.Value");+ }++ private void awaitStackGone(String stackName) {+ await()+ .atMost(STACK_DELETE_TIMEOUT)+ .pollInterval(STACK_DELETE_POLL_INTERVAL)+ .untilAsserted(() -> {+ String body = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when().post("/").then().extract().asString();+ if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {+ fail("stack delete failed: " + body);+ }+ assertTrue(body.contains("does not exist"), "stack still exists: " + body);+ });+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisionerTest.javanew file mode 100644index 0000000000..5726d7cc19--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisionerTest.java@@ -0,0 +1,244 @@+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.core.common.AwsException;+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;+import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;+import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;+import org.junit.jupiter.api.Test;++import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyList;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++/**+ * The DynamoDB CFN provisioner in isolation: the exact {@code Fn::GetAtt} keys the registry+ * schema declares, and the delete contract for each of its three types. The stream and replica+ * behaviour keeps its own coverage in {@code DynamoDbStreamSpecificationCfnProvisionerTest} and+ * {@code DynamoDbReplicaCfnProvisionerTest}, which reach this class through the fixture.+ */+class DynamoDbCfnProvisionerTest {++ private static final String TABLE_NAME = "orders";+ private static final String TABLE_ARN = "arn:aws:dynamodb:us-east-1:000000000000:table/" + TABLE_NAME;+ private static final String TABLE_ID = "2d4c5c3a-1b6e-4a1d-9f0a-7b1c2d3e4f50";+ private static final String STREAM_ARN = TABLE_ARN + "/stream/2026-01-01T00:00:00.000";++ private final DynamoDbService dynamoDb = mock(DynamoDbService.class);+ private final DynamoDbCfnProvisioner provisioner = new DynamoDbCfnProvisioner(dynamoDb);+ private final ObjectMapper mapper = new ObjectMapper();++ private ProvisionContext ctx() {+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);+ when(engine.resolve(any())).thenAnswer(inv -> {+ JsonNode node = inv.getArgument(0);+ return node == null ? null : node.asText();+ });+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));+ return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");+ }++ private StackResource resource(String type, String logicalId) {+ StackResource r = new StackResource();+ r.setLogicalId(logicalId);+ r.setResourceType(type);+ r.setAttributes(new HashMap<>());+ return r;+ }++ private TableDefinition table(boolean streamed) {+ TableDefinition table = new TableDefinition();+ table.setTableName(TABLE_NAME);+ table.setTableArn(TABLE_ARN);+ table.setTableId(TABLE_ID);+ if (streamed) {+ table.setStreamEnabled(true);+ table.setStreamArn(STREAM_ARN);+ table.setStreamViewType("NEW_AND_OLD_IMAGES");+ }+ return table;+ }++ private JsonNode props(String json) throws Exception {+ return mapper.readTree(json);+ }++ @Test+ void ownsExactlyTheThreeDynamoDbTypes() {+ assertEquals(Set.of("AWS::DynamoDB::Table", "AWS::DynamoDB::GlobalTable", "Custom::DynamoDBReplica"),+ provisioner.resourceTypes());+ }++ /** The registry schema declares only Arn and StreamArn read-only on a plain table; TableId belongs to the global table. */+ @Test+ void tablePublishesOnlyArnWithoutAStream() throws Exception {+ when(dynamoDb.createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(), anyString()))+ .thenReturn(table(false));+ StackResource r = resource("AWS::DynamoDB::Table", "Orders");++ provisioner.provision(r, props("{\"TableName\":\"orders\"}"), ctx());++ assertEquals(TABLE_NAME, r.getPhysicalId());+ assertEquals(Set.of("Arn"), r.getAttributes().keySet());+ assertEquals(TABLE_ARN, r.getAttributes().get("Arn"));+ }++ @Test+ void globalTableIsProvisionedAsATableAndPublishesTableId() throws Exception {+ when(dynamoDb.createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(), anyString()))+ .thenReturn(table(false));+ StackResource r = resource("AWS::DynamoDB::GlobalTable", "Orders");++ provisioner.provision(r, props("{\"TableName\":\"orders\"}"), ctx());++ verify(dynamoDb).createTable(eq(TABLE_NAME), anyList(), anyList(), any(), any(), anyList(), anyList(),+ eq("us-east-1"));+ assertEquals(TABLE_NAME, r.getPhysicalId());+ assertEquals(Set.of("Arn", "TableId"), r.getAttributes().keySet());+ assertEquals(TABLE_ID, r.getAttributes().get("TableId"));+ }++ @Test+ void streamedTablePublishesStreamArn() throws Exception {+ when(dynamoDb.createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(), anyString()))+ .thenReturn(table(false));+ when(dynamoDb.enableStream(TABLE_NAME, "NEW_AND_OLD_IMAGES", "us-east-1")).thenReturn(table(true));+ StackResource r = resource("AWS::DynamoDB::Table", "Orders");++ provisioner.provision(r, props("{\"TableName\":\"orders\",\"StreamSpecification\":"+ + "{\"StreamViewType\":\"NEW_AND_OLD_IMAGES\"}}"), ctx());++ assertEquals(Set.of("Arn", "StreamArn"), r.getAttributes().keySet());+ assertEquals(STREAM_ARN, r.getAttributes().get("StreamArn"));+ }++ @Test+ void tableDeleteTreatsResourceNotFoundAsAlreadyGone() {+ doThrow(new AwsException("ResourceNotFoundException", "Requested resource not found", 400))+ .when(dynamoDb).deleteTable("missing", "us-east-1");++ provisioner.delete("AWS::DynamoDB::Table", "missing", "us-east-1");++ verify(dynamoDb).deleteTable("missing", "us-east-1");+ }++ @Test+ void tableDeletePropagatesAnyOtherError() {+ doThrow(new AwsException("InternalServerError", "boom", 500))+ .when(dynamoDb).deleteTable(TABLE_NAME, "us-east-1");++ AwsException e = assertThrows(AwsException.class,+ () -> provisioner.delete("AWS::DynamoDB::Table", TABLE_NAME, "us-east-1"));++ assertEquals("InternalServerError", e.getErrorCode());+ }++ @Test+ void globalTableDeleteRemovesTheTable() {+ provisioner.delete("AWS::DynamoDB::GlobalTable", TABLE_NAME, "us-east-1");++ verify(dynamoDb).deleteTable(TABLE_NAME, "us-east-1");+ }++ @Test+ void replicaDeleteWithCreateTimeAttributesRemovesTheReplicaRegion() {+ StackResource r = resource("Custom::DynamoDBReplica", "Replica");+ r.setPhysicalId("orders-us-west-2");+ r.getAttributes().put("TableName", TABLE_NAME);+ r.getAttributes().put("__FlociDynamoDbReplicaRegion", "us-west-2");+ r.getAttributes().put("__FlociDynamoDbReplicaSkipDeletion", "false");++ provisioner.delete(r, "us-east-1");++ verify(dynamoDb).applyReplicaUpdates(TABLE_NAME, List.of(), List.of("us-west-2"), "us-east-1");+ }++ @Test+ void replicaDeleteWithoutAttributesFallsBackToTheCdkPhysicalId() {+ StackResource r = resource("Custom::DynamoDBReplica", "Replica");+ r.setPhysicalId("orders-us-west-2");+ r.getAttributes().put("TableName", TABLE_NAME);++ provisioner.delete(r, "us-east-1");++ verify(dynamoDb).applyReplicaUpdates(TABLE_NAME, List.of(), List.of("us-west-2"), "us-east-1");+ }++ /** Only a table that is already gone is "already deleted"; any other failure must reach the stack as DELETE_FAILED. */+ @Test+ void replicaDeletePropagatesAnythingButANotFoundTable() {+ StackResource r = resource("Custom::DynamoDBReplica", "Replica");+ r.setPhysicalId("orders-us-west-2");+ r.getAttributes().put("TableName", TABLE_NAME);+ r.getAttributes().put("__FlociDynamoDbReplicaRegion", "us-west-2");+ doThrow(new AwsException("ValidationException", "Replica RegionName must not be empty", 400))+ .when(dynamoDb).applyReplicaUpdates(TABLE_NAME, List.of(), List.of("us-west-2"), "us-east-1");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.delete(r, "us-east-1"));+ assertEquals("ValidationException", e.getErrorCode());++ doThrow(new AwsException("ResourceNotFoundException", "Requested resource not found", 400))+ .when(dynamoDb).applyReplicaUpdates(TABLE_NAME, List.of(), List.of("us-west-2"), "us-east-1");++ provisioner.delete(r, "us-east-1");+ }++ @Test+ void replicaDeleteByIdAloneLeavesTheReplicaInPlace() {+ provisioner.delete("Custom::DynamoDBReplica", "orders-us-west-2", "us-east-1");++ verifyNoInteractions(dynamoDb);+ }++ @Test+ void tableDeleteThroughTheResourceOverloadUsesTheIdPath() {+ StackResource r = resource("AWS::DynamoDB::Table", "Orders");+ r.setPhysicalId(TABLE_NAME);++ provisioner.delete(r, "us-east-1");++ verify(dynamoDb).deleteTable(TABLE_NAME, "us-east-1");+ verify(dynamoDb, never()).applyReplicaUpdates(anyString(), anyList(), anyList(), anyString());+ }++ @Test+ void unsupportedTypeIsRejectedOnProvisionAndDelete() throws Exception {+ StackResource r = resource("AWS::SQS::Queue", "Queue");+ JsonNode props = props("{}");+ ProvisionContext ctx = ctx();++ assertThrows(IllegalStateException.class, () -> provisioner.provision(r, props, ctx));+ assertThrows(IllegalStateException.class, () -> provisioner.delete("AWS::SQS::Queue", "q", "us-east-1"));+ verifyNoInteractions(dynamoDb);+ }++ @Test+ void tagsAreAppliedAndStaleOnesRemoved() throws Exception {+ when(dynamoDb.createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(), anyString()))+ .thenReturn(table(false));+ when(dynamoDb.listTagsOfResource(TABLE_ARN, "us-east-1")).thenReturn(Map.of("old", "1", "env", "dev"));+ StackResource r = resource("AWS::DynamoDB::Table", "Orders");++ provisioner.provision(r, props("{\"TableName\":\"orders\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"prod\"}]}"),+ ctx());++ verify(dynamoDb).untagResource(TABLE_ARN, List.of("old"), "us-east-1");+ verify(dynamoDb).tagResource(TABLE_ARN, Map.of("env", "prod"), "us-east-1");+ }+}diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsvindex 5a5e65ea3b..1af2a716d2 100644--- a/src/test/resources/cloudformation/supported-resource-types.tsv+++ b/src/test/resources/cloudformation/supported-resource-types.tsv@@ -50,8 +50,8 @@ AWS::Cognito::UserPool CognitoCfnProvisionerAWS::Cognito::UserPoolClient CognitoCfnProvisionerAWS::Cognito::UserPoolDomain CognitoCfnProvisionerAWS::Config::ConfigRule ConfigCfnProvisioner-AWS::DynamoDB::GlobalTable LEGACY_SWITCH-AWS::DynamoDB::Table LEGACY_SWITCH+AWS::DynamoDB::GlobalTable DynamoDbCfnProvisioner+AWS::DynamoDB::Table DynamoDbCfnProvisionerAWS::EC2::EIP Ec2NetworkCfnProvisionerAWS::EC2::FlowLog Ec2FlowLogCfnProvisionerAWS::EC2::Instance LEGACY_SWITCH@@ -143,4 +143,4 @@ AWS::SecretsManager::Secret SecretsManagerCfnProvisionerAWS::SecretsManager::SecretTargetAttachment SecretTargetAttachmentCfnProvisionerAWS::StepFunctions::StateMachine StepFunctionsCfnProvisionerAWS::WAFv2::WebACL WafV2CfnProvisioner-Custom::DynamoDBReplica LEGACY_SWITCH+Custom::DynamoDBReplica DynamoDbCfnProvisioner