refactor(cloudformation): move the DynamoDB types into DynamoDbCfnProvisioner (#3699)

* refactor(cloudformation): move the DynamoDB types into DynamoDbCfnProvisioner

AWS::DynamoDB::Table, AWS::DynamoDB::GlobalTable and Custom::DynamoDBReplica leave
CloudFormationResourceProvisioner for a per-service provisioner that owns create,
update and delete for all three. The monolith drops 246 lines, its last DynamoDB
reference and the injected DynamoDbService (24 to 23 constructor parameters), and
its legacy switch goes from 27 to 24 types.

Two behaviour changes ride along, both covered by the new tests. A GlobalTable is
now deleted on stack delete: it had no delete arm and the table leaked.
Fn::GetAtt TableId resolves for both table types, from the same value
DescribeTable reports, which closes the registry schema's read-only attribute the
old arm never set. Replicas on a GlobalTable stays ignored as before.
parseCfnTags is copied rather than moved because the monolith's unused
putTagsObject still references it.

* refactor(cloudformation): publish TableId only for global tables and let a failed replica delete surface

The registry schema declares TableId read-only on AWS::DynamoDB::GlobalTable only; a
plain AWS::DynamoDB::Table exposes Arn and StreamArn, so publishing TableId there
accepted a Fn::GetAtt that CloudFormation rejects. The replica delete tolerated every
exception, which reported a clean delete over a real failure; it now goes through
CfnDeletes.safeDelete and treats only a missing table as already gone, since the
service already ignores removing an absent replica. The unused snsService constructor
parameter on the line this change touches is dropped as well.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-15 22:51:17 -05:00
1 parent e2aefa654b
commit 77007656aa
6 files changed
+753 -256

No files matched your search

@@ -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,
@@ -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);
});
}
}
@@ -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");
}
}