feat(cloudformation): apply DynamoDB table ProvisionedThroughput and WarmThroughput (#9113)

* feat(cloudformation): apply ProvisionedThroughput and WarmThroughput of a DynamoDB table
* fix(cloudformation): refuse DynamoDB throughput values that CloudFormation refuses
* refactor(cloudformation): reuse the shared messages and test helpers for DynamoDB throughput
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-20 20:28:47 -04:00
1 parent d427b31e07
commit f3c21892a6
10 files changed
+1236 -24

No files matched your search

@@ -0,0 +1,308 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.testing.CfnRequests;
import io.floci.aws.testing.CfnStackWaits;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
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.assertTrue;
/**
* {@code ProvisionedThroughput} and {@code WarmThroughput} on {@code AWS::DynamoDB::Table}, on the
* table and on a global secondary index.
*/
@QuarkusTest
class CloudFormationDynamoDbThroughputIntegrationTest {
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 TEMPLATE = """
{
"Resources": {
"Orders": {
"Type": "AWS::DynamoDB::Table",
"Properties": {
"TableName": "%s",
"AttributeDefinitions": [
{"AttributeName": "pk", "AttributeType": "S"},
{"AttributeName": "gk", "AttributeType": "S"}
],
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"GlobalSecondaryIndexes": [{
"IndexName": "gix1",
"KeySchema": [{"AttributeName": "gk", "KeyType": "HASH"}],
"Projection": {"ProjectionType": "ALL"}%s
}]%s
}
}
}
}
""";
private static String capacity(int read, int write) {
return ",\n\"ProvisionedThroughput\": {\"ReadCapacityUnits\": " + read + ", \"WriteCapacityUnits\": "
+ write + "}";
}
private static String warm(String members) {
return ",\n\"WarmThroughput\": {" + members + "}";
}
private static String template(String table, String index, String tableProperties) {
return TEMPLATE.formatted(table, index, tableProperties);
}
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void createAppliesTheTableAndIndexCapacity() {
String stack = "cfn-ddb-tp-create-" + suffix();
String table = "tp-create-" + suffix();
cloudFormation(stack, "CreateStack", template(table, capacity(2, 2), capacity(1, 1)));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describe(table)
.body("Table.ProvisionedThroughput.ReadCapacityUnits", equalTo(1))
.body("Table.ProvisionedThroughput.WriteCapacityUnits", equalTo(1))
.body("Table.GlobalSecondaryIndexes[0].ProvisionedThroughput.ReadCapacityUnits", equalTo(2))
.body("Table.GlobalSecondaryIndexes[0].ProvisionedThroughput.WriteCapacityUnits", equalTo(2));
CfnStackWaits.deleteStack(stack, CFN_AUTH);
}
@Test
void createStoresTheWarmThroughputOfTheTableAndTheIndex() {
String stack = "cfn-ddb-tp-warm-" + suffix();
String table = "tp-warm-" + suffix();
cloudFormation(stack, "CreateStack", template(table,
capacity(2, 2) + warm("\"WriteUnitsPerSecond\": 4000"),
capacity(1, 1) + warm("\"ReadUnitsPerSecond\": 5000")));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describe(table)
.body("Table.WarmThroughput.ReadUnitsPerSecond", equalTo(5000))
.body("Table.WarmThroughput.WriteUnitsPerSecond", equalTo(1))
.body("Table.GlobalSecondaryIndexes[0].WarmThroughput.ReadUnitsPerSecond", equalTo(2))
.body("Table.GlobalSecondaryIndexes[0].WarmThroughput.WriteUnitsPerSecond", equalTo(4000));
CfnStackWaits.deleteStack(stack, CFN_AUTH);
}
@Test
void createBelowTheInitialWarmThroughputFailsWithTheApiMessage() {
String stack = "cfn-ddb-tp-low-" + suffix();
String table = "tp-low-" + suffix();
cloudFormation(stack, "CreateStack", template(table, capacity(2, 2),
capacity(2, 2) + warm("\"ReadUnitsPerSecond\": 1")));
assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
assertTrue(CfnStackWaits.failedResourceReason(stack, CFN_AUTH).contains("Requested ReadUnitsPerSecond for"
+ " WarmThroughput for table is lower than ReadCapacityUnits of ProvisionedThroughput"));
CfnStackWaits.deleteStack(stack, CFN_AUTH);
}
@Test
void anUpdateChangesTheCapacityOfTheSameTable() {
String stack = "cfn-ddb-tp-update-" + suffix();
String table = "tp-update-" + suffix();
cloudFormation(stack, "CreateStack", template(table, capacity(2, 2), capacity(1, 1)));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
String tableId = describe(table).extract().path("Table.TableId");
cloudFormation(stack, "UpdateStack", template(table, capacity(1, 1), capacity(3, 3)));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describe(table)
.body("Table.TableId", equalTo(tableId))
.body("Table.ProvisionedThroughput.ReadCapacityUnits", equalTo(3))
.body("Table.ProvisionedThroughput.WriteCapacityUnits", equalTo(3))
.body("Table.GlobalSecondaryIndexes[0].ProvisionedThroughput.ReadCapacityUnits", equalTo(1))
.body("Table.GlobalSecondaryIndexes[0].ProvisionedThroughput.WriteCapacityUnits", equalTo(1));
CfnStackWaits.deleteStack(stack, CFN_AUTH);
}
@Test
void anUpdateRaisesTheWarmThroughputAndAnEqualValueChangesNothing() {
String stack = "cfn-ddb-tp-raise-" + suffix();
String table = "tp-raise-" + suffix();
String declared = capacity(1, 1) + warm("\"ReadUnitsPerSecond\": 5000");
cloudFormation(stack, "CreateStack", template(table, capacity(2, 2), declared));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
cloudFormation(stack, "UpdateStack", template(table, capacity(3, 3), declared));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describe(table)
.body("Table.WarmThroughput.ReadUnitsPerSecond", equalTo(5000))
.body("Table.GlobalSecondaryIndexes[0].ProvisionedThroughput.ReadCapacityUnits", equalTo(3));
cloudFormation(stack, "UpdateStack", template(table, capacity(3, 3),
capacity(1, 1) + warm("\"ReadUnitsPerSecond\": 6000")));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describe(table).body("Table.WarmThroughput.ReadUnitsPerSecond", equalTo(6000));
CfnStackWaits.deleteStack(stack, CFN_AUTH);
}
@Test
void aWarmThroughputTheTemplateKeptIsNotSentAgainWhenCapacityGrowsPastIt() {
String stack = "cfn-ddb-tp-kept-" + suffix();
String table = "tp-kept-" + suffix();
String warmOne = warm("\"ReadUnitsPerSecond\": 1, \"WriteUnitsPerSecond\": 1");
cloudFormation(stack, "CreateStack", template(table, capacity(2, 2), capacity(1, 1) + warmOne));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
cloudFormation(stack, "UpdateStack", template(table, capacity(2, 2), capacity(3, 3) + warmOne));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describe(table).body("Table.WarmThroughput.ReadUnitsPerSecond", equalTo(3));
cloudFormation(stack, "UpdateStack", template(table, capacity(2, 2), capacity(4, 4) + warmOne));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describe(table).body("Table.WarmThroughput.ReadUnitsPerSecond", equalTo(4));
cloudFormation(stack, "UpdateStack", template(table, capacity(2, 2), capacity(4, 4)
+ warm("\"ReadUnitsPerSecond\": 2, \"WriteUnitsPerSecond\": 2")));
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
assertTrue(CfnStackWaits.failedResourceReason(stack, CFN_AUTH).contains("lower than current WarmThroughput,"
+ " decreasing WarmThroughput is not supported"));
describe(table).body("Table.WarmThroughput.ReadUnitsPerSecond", equalTo(4));
CfnStackWaits.deleteStack(stack, CFN_AUTH);
}
@Test
void anUpdateRaisingCapacityAndWarmThroughputTogetherPasses() {
String stack = "cfn-ddb-tp-both-" + suffix();
String table = "tp-both-" + suffix();
cloudFormation(stack, "CreateStack", template(table, capacity(2, 2), capacity(1, 1)));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
cloudFormation(stack, "UpdateStack", template(table, capacity(2, 2),
capacity(10, 10) + warm("\"ReadUnitsPerSecond\": 10, \"WriteUnitsPerSecond\": 10")));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describe(table)
.body("Table.ProvisionedThroughput.ReadCapacityUnits", equalTo(10))
.body("Table.WarmThroughput.ReadUnitsPerSecond", equalTo(10))
.body("Table.WarmThroughput.WriteUnitsPerSecond", equalTo(10));
CfnStackWaits.deleteStack(stack, CFN_AUTH);
}
@Test
void anUpdateBelowTheCurrentWarmThroughputFailsAndRollsBack() {
String stack = "cfn-ddb-tp-lower-" + suffix();
String table = "tp-lower-" + suffix();
cloudFormation(stack, "CreateStack", template(table, capacity(2, 2),
capacity(1, 1) + warm("\"ReadUnitsPerSecond\": 5000")));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
cloudFormation(stack, "UpdateStack", template(table, capacity(2, 2),
capacity(3, 3) + warm("\"ReadUnitsPerSecond\": 4000")));
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
assertTrue(CfnStackWaits.failedResourceReason(stack, CFN_AUTH).contains("Requested ReadUnitsPerSecond for"
+ " WarmThroughput for table is lower than current WarmThroughput,"
+ " decreasing WarmThroughput is not supported"));
describe(table)
.body("Table.ProvisionedThroughput.ReadCapacityUnits", equalTo(1))
.body("Table.WarmThroughput.ReadUnitsPerSecond", equalTo(5000));
CfnStackWaits.deleteStack(stack, CFN_AUTH);
}
@Test
void aFailedUpdatePutsThePreviousCapacityBack() {
String stack = "cfn-ddb-tp-rollback-" + suffix();
String table = "tp-rollback-" + suffix();
String missingStream = ",\n\"KinesisStreamSpecification\": {\"StreamArn\":"
+ " \"arn:aws:kinesis:us-east-1:000000000000:stream/no-such-stream-" + suffix() + "\"}";
cloudFormation(stack, "CreateStack", template(table, capacity(2, 2), capacity(1, 1)));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
cloudFormation(stack, "UpdateStack", template(table, capacity(4, 4), capacity(3, 3) + missingStream));
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describe(table)
.body("Table.ProvisionedThroughput.ReadCapacityUnits", equalTo(1))
.body("Table.ProvisionedThroughput.WriteCapacityUnits", equalTo(1))
.body("Table.GlobalSecondaryIndexes[0].ProvisionedThroughput.ReadCapacityUnits", equalTo(2))
.body("Table.GlobalSecondaryIndexes[0].ProvisionedThroughput.WriteCapacityUnits", equalTo(2));
CfnStackWaits.deleteStack(stack, CFN_AUTH);
}
@Test
void onDemandWithProvisionedThroughputFailsTheCreate() {
String stack = "cfn-ddb-tp-ondemand-" + suffix();
String table = "tp-ondemand-" + suffix();
cloudFormation(stack, "CreateStack", template(table, "",
",\n\"BillingMode\": \"PAY_PER_REQUEST\"" + capacity(1, 1)));
assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
assertTrue(CfnStackWaits.failedResourceReason(stack, CFN_AUTH)
.contains("Property ProvisionedThroughput can't be used with PAY_PER_REQUEST BillingMode."));
describe(table).statusCode(400).body("__type", containsString("ResourceNotFoundException"));
CfnStackWaits.deleteStack(stack, CFN_AUTH);
}
@Test
void onDemandWithOnlyAnIndexCapacityFailsTheCreate() {
String stack = "cfn-ddb-tp-ondemand-gsi-" + suffix();
String table = "tp-ondemand-gsi-" + suffix();
cloudFormation(stack, "CreateStack", template(table, capacity(1, 1),
",\n\"BillingMode\": \"PAY_PER_REQUEST\""));
assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
assertTrue(CfnStackWaits.failedResourceReason(stack, CFN_AUTH)
.contains("Property ProvisionedThroughput can't be used with PAY_PER_REQUEST BillingMode."));
describe(table).statusCode(400).body("__type", containsString("ResourceNotFoundException"));
CfnStackWaits.deleteStack(stack, CFN_AUTH);
}
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
private void cloudFormation(String stack, String action, String template) {
CfnRequests.cfn(action, stack)
.header("Authorization", CFN_AUTH)
.formParam("TemplateBody", template)
.when().post("/").then().statusCode(200);
}
private ValidatableResponse describe(String table) {
return given()
.contentType("application/x-amz-json-1.0")
.header("Authorization", DDB_AUTH)
.header("X-Amz-Target", "DynamoDB_20120810.DescribeTable")
.body("{\"TableName\": \"" + table + "\"}")
.when().post("/").then();
}
}
@@ -0,0 +1,526 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.dynamodb.DynamoDbFacade;
import io.floci.aws.services.dynamodb.DynamoDbService;
import io.floci.aws.services.dynamodb.NativeDynamoDbTableService;
import io.floci.aws.services.dynamodb.backend.DynamoDbTableAccess.CapacityUnits;
import io.floci.aws.services.dynamodb.backend.DynamoDbTableAccess.ThroughputChange;
import io.floci.aws.services.dynamodb.backend.DynamoDbTableAccess.ThroughputSpec;
import io.floci.aws.services.dynamodb.backend.DynamoDbTableAccess.WarmUnits;
import io.floci.aws.services.dynamodb.backend.NativeDynamoDbBackend;
import io.floci.aws.services.dynamodb.model.GlobalSecondaryIndex;
import io.floci.aws.services.dynamodb.model.ProvisionedThroughput;
import io.floci.aws.services.dynamodb.model.TableDefinition;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* {@code ProvisionedThroughput} and {@code WarmThroughput} on {@code AWS::DynamoDB::Table}, on the
* table and on each global secondary index.
*/
class DynamoDbThroughputCfnProvisionerTest {
private static final String REGION = "us-east-1";
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 INDEX = "gix1";
private static final String PROVISIONED = "{\"TableName\":\"orders\","
+ "\"ProvisionedThroughput\":{\"ReadCapacityUnits\":1,\"WriteCapacityUnits\":1},"
+ "\"GlobalSecondaryIndexes\":[{\"IndexName\":\"gix1\","
+ "\"ProvisionedThroughput\":{\"ReadCapacityUnits\":2,\"WriteCapacityUnits\":2}}]}";
private static final String RAISED = "{\"TableName\":\"orders\","
+ "\"ProvisionedThroughput\":{\"ReadCapacityUnits\":3,\"WriteCapacityUnits\":3},"
+ "\"GlobalSecondaryIndexes\":[{\"IndexName\":\"gix1\","
+ "\"ProvisionedThroughput\":{\"ReadCapacityUnits\":1,\"WriteCapacityUnits\":1}}]}";
private static final String WARM = "{\"TableName\":\"orders\","
+ "\"ProvisionedThroughput\":{\"ReadCapacityUnits\":1,\"WriteCapacityUnits\":1},"
+ "\"WarmThroughput\":{\"ReadUnitsPerSecond\":5000},"
+ "\"GlobalSecondaryIndexes\":[{\"IndexName\":\"gix1\","
+ "\"ProvisionedThroughput\":{\"ReadCapacityUnits\":2,\"WriteCapacityUnits\":2},"
+ "\"WarmThroughput\":{\"WriteUnitsPerSecond\":4000}}]}";
private static final String CAPACITY_AND_WARM = "{\"TableName\":\"orders\","
+ "\"ProvisionedThroughput\":{\"ReadCapacityUnits\":3,\"WriteCapacityUnits\":3},"
+ "\"WarmThroughput\":{\"ReadUnitsPerSecond\":3,\"WriteUnitsPerSecond\":3}}";
private static final String ON_DEMAND_WARM = "{\"TableName\":\"orders\",\"BillingMode\":\"PAY_PER_REQUEST\","
+ "\"WarmThroughput\":{\"ReadUnitsPerSecond\":12000,\"WriteUnitsPerSecond\":4000}}";
private static final String ON_DEMAND_CAPACITY = "{\"TableName\":\"orders\",\"BillingMode\":\"PAY_PER_REQUEST\","
+ "\"ProvisionedThroughput\":{\"ReadCapacityUnits\":1,\"WriteCapacityUnits\":1}}";
private static final String EMPTY_WARM = "{\"TableName\":\"orders\","
+ "\"ProvisionedThroughput\":{\"ReadCapacityUnits\":1,\"WriteCapacityUnits\":1},"
+ "\"WarmThroughput\":{}}";
private static final String UNCHANGED_WARM = "{\"TableName\":\"orders\","
+ "\"ProvisionedThroughput\":{\"ReadCapacityUnits\":3,\"WriteCapacityUnits\":3},"
+ "\"WarmThroughput\":{\"ReadUnitsPerSecond\":1,\"WriteUnitsPerSecond\":1}}";
private static final String UNCHANGED_WARM_RAISED = "{\"TableName\":\"orders\","
+ "\"ProvisionedThroughput\":{\"ReadCapacityUnits\":4,\"WriteCapacityUnits\":4},"
+ "\"WarmThroughput\":{\"ReadUnitsPerSecond\":1,\"WriteUnitsPerSecond\":1}}";
private static final String CHANGED_WARM = "{\"TableName\":\"orders\","
+ "\"ProvisionedThroughput\":{\"ReadCapacityUnits\":3,\"WriteCapacityUnits\":3},"
+ "\"WarmThroughput\":{\"ReadUnitsPerSecond\":2,\"WriteUnitsPerSecond\":2}}";
private static final String INDEX_WARM = "{\"TableName\":\"orders\","
+ "\"GlobalSecondaryIndexes\":[{\"IndexName\":\"gix1\","
+ "\"WarmThroughput\":{\"ReadUnitsPerSecond\":1,\"WriteUnitsPerSecond\":1}}]}";
private static final String INDEX_WARM_CHANGED = "{\"TableName\":\"orders\","
+ "\"GlobalSecondaryIndexes\":[{\"IndexName\":\"gix1\","
+ "\"WarmThroughput\":{\"ReadUnitsPerSecond\":2,\"WriteUnitsPerSecond\":2}}]}";
private static final String UNDECLARED = "{\"TableName\":\"orders\"}";
private final DynamoDbService dynamoDb = mock(DynamoDbService.class);
private final NativeDynamoDbTableService tableService = mock(NativeDynamoDbTableService.class);
private final ObjectMapper mapper = new ObjectMapper();
private final NativeDynamoDbBackend backend =
new NativeDynamoDbBackend(null, null, tableService, dynamoDb, null, null, mapper);
private final DynamoDbCfnProvisioner provisioner = new DynamoDbCfnProvisioner(
new DynamoDbFacade(backend, backend, new RegionResolver(REGION, "000000000000")));
private ProvisionContext ctx() {
return new ProvisionContext(ProvisionContexts.passthroughEngine(), REGION, "000000000000", "my-stack");
}
private ProvisionContext updateCtx(String priorProperties) throws Exception {
return ProvisionContexts.update(REGION, "000000000000", "my-stack", TABLE_NAME, priorProperties);
}
private JsonNode props(String json) throws Exception {
return mapper.readTree(json);
}
private StackResource resource(String type) {
StackResource r = new StackResource();
r.setLogicalId("Orders");
r.setResourceType(type);
r.setAttributes(new HashMap<>());
return r;
}
private StackResource existingResource() {
StackResource r = resource("AWS::DynamoDB::Table");
r.setPhysicalId(TABLE_NAME);
r.getAttributes().put("Arn", TABLE_ARN);
return r;
}
private static TableDefinition table(long tableCapacity, long indexCapacity, boolean onDemand) {
TableDefinition table = new TableDefinition(TABLE_NAME, List.of(), List.of());
table.setTableArn(TABLE_ARN);
table.setProvisionedThroughput(new ProvisionedThroughput(tableCapacity, tableCapacity));
table.setBillingMode(onDemand ? "PAY_PER_REQUEST" : "PROVISIONED");
GlobalSecondaryIndex gsi = new GlobalSecondaryIndex();
gsi.setIndexName(INDEX);
gsi.setProvisionedThroughput(new ProvisionedThroughput(indexCapacity, indexCapacity));
table.getGlobalSecondaryIndexes().add(gsi);
return table;
}
private void newTable() {
when(tableService.createTable(anyString(), anyList(), anyList(), anyBoolean(), any(), anyList(), anyList(),
anyString())).thenReturn(table(1, 2, false));
when(dynamoDb.describeTable(TABLE_NAME, REGION)).thenReturn(table(1, 2, false));
}
private void existingTable(TableDefinition current) {
when(tableService.createTable(anyString(), anyList(), anyList(), anyBoolean(), any(), anyList(), anyList(),
anyString())).thenThrow(new AwsException("ResourceInUseException", "Table already exists", 400));
when(dynamoDb.describeTable(TABLE_NAME, REGION)).thenReturn(current);
when(tableService.updateThroughput(anyString(), any(), anyString())).thenReturn(current);
}
private ThroughputChange updatedThroughput() {
ArgumentCaptor<ThroughputChange> change = ArgumentCaptor.forClass(ThroughputChange.class);
verify(tableService).updateThroughput(eq(TABLE_NAME), change.capture(), eq(REGION));
return change.getValue();
}
@Test
void createAppliesTheTableAndIndexCapacity() throws Exception {
newTable();
provisioner.provision(resource("AWS::DynamoDB::Table"), props(PROVISIONED), ctx());
ArgumentCaptor<ThroughputSpec> table = ArgumentCaptor.forClass(ThroughputSpec.class);
ArgumentCaptor<List<GlobalSecondaryIndex>> indexes = ArgumentCaptor.forClass(List.class);
verify(tableService).createTable(eq(TABLE_NAME), anyList(), anyList(), eq(false), table.capture(),
indexes.capture(), anyList(), eq(REGION));
assertEquals(new CapacityUnits(1, 1), table.getValue().capacity());
assertNull(table.getValue().warm());
ProvisionedThroughput index = indexes.getValue().get(0).getProvisionedThroughput();
assertEquals(2, index.getReadCapacityUnits());
assertEquals(2, index.getWriteCapacityUnits());
}
@Test
void createStoresTheTableAndIndexWarmThroughputWithOneMemberGiven() throws Exception {
newTable();
provisioner.provision(resource("AWS::DynamoDB::Table"), props(WARM), ctx());
ArgumentCaptor<ThroughputSpec> table = ArgumentCaptor.forClass(ThroughputSpec.class);
ArgumentCaptor<List<GlobalSecondaryIndex>> indexes = ArgumentCaptor.forClass(List.class);
verify(tableService).createTable(eq(TABLE_NAME), anyList(), anyList(), eq(false), table.capture(),
indexes.capture(), anyList(), eq(REGION));
assertEquals(new WarmUnits(5000L, null), table.getValue().warm());
assertNull(indexes.getValue().get(0).getWarmReadUnitsPerSecond());
assertEquals(4000L, indexes.getValue().get(0).getWarmWriteUnitsPerSecond());
}
@Test
void createOnDemandWithWarmThroughputGoesThroughTheThroughputPath() throws Exception {
newTable();
provisioner.provision(resource("AWS::DynamoDB::Table"), props(ON_DEMAND_WARM), ctx());
ArgumentCaptor<ThroughputSpec> table = ArgumentCaptor.forClass(ThroughputSpec.class);
verify(tableService).createTable(eq(TABLE_NAME), anyList(), anyList(), eq(true), table.capture(),
anyList(), anyList(), eq(REGION));
assertEquals(new WarmUnits(12000L, 4000L), table.getValue().warm());
}
@Test
void createFailsWhenTheApiRefusesTheWarmThroughput() throws Exception {
when(tableService.createTable(anyString(), anyList(), anyList(), anyBoolean(), any(), anyList(), anyList(),
anyString())).thenThrow(new AwsException("ValidationException", "lower than initial", 400));
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource("AWS::DynamoDB::Table"), props(ON_DEMAND_WARM), ctx()));
assertEquals("lower than initial", e.getMessage());
}
@Test
void onDemandWithProvisionedThroughputFailsBeforeTheTableIsCreated() throws Exception {
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource("AWS::DynamoDB::Table"), props(ON_DEMAND_CAPACITY), ctx()));
assertEquals("InvalidRequest", e.getErrorCode());
assertEquals("Property ProvisionedThroughput can't be used with PAY_PER_REQUEST BillingMode.",
e.getMessage());
verify(tableService, never()).createTable(anyString(), anyList(), anyList(), anyBoolean(), any(),
anyList(), anyList(), anyString());
}
@Test
void onDemandWithOnlyAnIndexCapacityFailsBeforeTheTableIsCreated() throws Exception {
String template = "{\"TableName\":\"orders\",\"BillingMode\":\"PAY_PER_REQUEST\","
+ "\"GlobalSecondaryIndexes\":[{\"IndexName\":\"gix1\","
+ "\"ProvisionedThroughput\":{\"ReadCapacityUnits\":1,\"WriteCapacityUnits\":1}}]}";
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource("AWS::DynamoDB::Table"), props(template), ctx()));
assertEquals("InvalidRequest", e.getErrorCode());
assertEquals("Property ProvisionedThroughput can't be used with PAY_PER_REQUEST BillingMode.",
e.getMessage());
verifyNoTableCreated();
}
@Test
void aCapacityAbove32BitsFailsBeforeTheTableIsCreated() throws Exception {
String template = "{\"TableName\":\"orders\",\"ProvisionedThroughput\":"
+ "{\"ReadCapacityUnits\":2147483648,\"WriteCapacityUnits\":1}}";
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource("AWS::DynamoDB::Table"), props(template), ctx()));
assertEquals("Model validation failed (#/ProvisionedThroughput/ReadCapacityUnits: expected type: Integer,"
+ " found: String. This may occur when a numeric value exceeds 32-bit integer max (2147483647)."
+ " Consider using 'number' type or ensure value fits in integer range.)", e.getMessage());
verifyNoTableCreated();
}
@Test
void anIndexWarmThroughputAbove64BitsFailsWithTheIndexPath() throws Exception {
String template = "{\"TableName\":\"orders\",\"GlobalSecondaryIndexes\":[{\"IndexName\":\"gix0\"},"
+ "{\"IndexName\":\"gix1\",\"WarmThroughput\":{\"WriteUnitsPerSecond\":18446744073709551617}}]}";
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource("AWS::DynamoDB::Table"), props(template), ctx()));
assertTrue(e.getMessage().startsWith(
"Model validation failed (#/GlobalSecondaryIndexes/1/WarmThroughput/WriteUnitsPerSecond:"));
verifyNoTableCreated();
}
@Test
void theLargest32BitCapacityIsPassedToTheTable() throws Exception {
newTable();
String template = "{\"TableName\":\"orders\",\"ProvisionedThroughput\":"
+ "{\"ReadCapacityUnits\":2147483647,\"WriteCapacityUnits\":1}}";
provisioner.provision(resource("AWS::DynamoDB::Table"), props(template), ctx());
ArgumentCaptor<ThroughputSpec> table = ArgumentCaptor.forClass(ThroughputSpec.class);
verify(tableService).createTable(eq(TABLE_NAME), anyList(), anyList(), eq(false), table.capture(),
anyList(), anyList(), eq(REGION));
assertEquals(new CapacityUnits(2147483647L, 1), table.getValue().capacity());
}
@Test
void aWarmThroughputMemberThatIsAnArrayFailsBeforeTheTableIsCreated() throws Exception {
String template = "{\"TableName\":\"orders\",\"WarmThroughput\":"
+ "{\"ReadUnitsPerSecond\":[],\"WriteUnitsPerSecond\":1}}";
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource("AWS::DynamoDB::Table"), props(template), ctx()));
assertEquals("Property [ReadUnitsPerSecond] expected type: Integer, found: JSONArray", e.getMessage());
verifyNoTableCreated();
}
@Test
void aCreateThatFindsAnExistingTableDoesNotChangeItsThroughput() throws Exception {
existingTable(table(9, 9, false));
provisioner.provision(resource("AWS::DynamoDB::Table"), props(RAISED), ctx());
verify(tableService, never()).updateThroughput(anyString(), any(), anyString());
}
private void verifyNoTableCreated() {
verify(tableService, never()).createTable(anyString(), anyList(), anyList(), anyBoolean(), any(),
anyList(), anyList(), anyString());
}
@Test
void anEmptyWarmThroughputFailsBeforeTheTableIsCreated() throws Exception {
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource("AWS::DynamoDB::Table"), props(EMPTY_WARM), ctx()));
assertEquals("Required property [ReadUnitsPerSecond] not found", e.getMessage());
verify(tableService, never()).createTable(anyString(), anyList(), anyList(), anyBoolean(), any(),
anyList(), anyList(), anyString());
}
@Test
void anEmptyIndexWarmThroughputFailsBeforeTheTableIsCreated() throws Exception {
String template = "{\"TableName\":\"orders\",\"GlobalSecondaryIndexes\":[{\"IndexName\":\"gix1\","
+ "\"WarmThroughput\":{}}]}";
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource("AWS::DynamoDB::Table"), props(template), ctx()));
assertEquals("Required property [ReadUnitsPerSecond] not found", e.getMessage());
verify(tableService, never()).createTable(anyString(), anyList(), anyList(), anyBoolean(), any(),
anyList(), anyList(), anyString());
}
@Test
void aCapacityWithoutAMemberFailsBeforeTheTableIsCreated() throws Exception {
String missingWrite = "{\"TableName\":\"orders\",\"ProvisionedThroughput\":{\"ReadCapacityUnits\":1}}";
String missingBoth = "{\"TableName\":\"orders\",\"ProvisionedThroughput\":{}}";
AwsException write = assertThrows(AwsException.class,
() -> provisioner.provision(resource("AWS::DynamoDB::Table"), props(missingWrite), ctx()));
AwsException read = assertThrows(AwsException.class,
() -> provisioner.provision(resource("AWS::DynamoDB::Table"), props(missingBoth), ctx()));
assertEquals("Required property [WriteCapacityUnits] not found", write.getMessage());
assertEquals("Required property [ReadCapacityUnits] not found", read.getMessage());
verify(tableService, never()).createTable(anyString(), anyList(), anyList(), anyBoolean(), any(),
anyList(), anyList(), anyString());
}
@Test
void aTemplateWithoutThroughputCreatesTheTableAsBefore() throws Exception {
when(dynamoDb.createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(),
anyString())).thenReturn(table(5, 5, false));
when(dynamoDb.describeTable(TABLE_NAME, REGION)).thenReturn(table(5, 5, false));
provisioner.provision(resource("AWS::DynamoDB::Table"), props(UNDECLARED), ctx());
verify(dynamoDb).createTable(eq(TABLE_NAME), anyList(), anyList(), eq(null), eq(null), anyList(),
anyList(), eq(REGION));
verify(tableService, never()).createTable(anyString(), anyList(), anyList(), anyBoolean(), any(),
anyList(), anyList(), anyString());
}
@Test
void aGlobalTableIgnoresTheThroughputProperties() throws Exception {
when(dynamoDb.createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(),
anyString())).thenReturn(table(5, 5, false));
when(dynamoDb.describeTable(TABLE_NAME, REGION)).thenReturn(table(5, 5, false));
provisioner.provision(resource("AWS::DynamoDB::GlobalTable"), props(PROVISIONED), ctx());
verify(tableService, never()).createTable(anyString(), anyList(), anyList(), anyBoolean(), any(),
anyList(), anyList(), anyString());
verify(tableService, never()).updateThroughput(anyString(), any(), anyString());
}
@Test
void updateChangesTheTableAndIndexCapacityInOneCall() throws Exception {
existingTable(table(1, 2, false));
provisioner.provision(existingResource(), props(RAISED), updateCtx(PROVISIONED));
ThroughputChange change = updatedThroughput();
assertEquals(new CapacityUnits(3, 3), change.table().capacity());
assertEquals(new CapacityUnits(1, 1), change.indexes().get(INDEX).capacity());
}
@Test
void updateWithTheCurrentCapacityMakesNoCall() throws Exception {
existingTable(table(1, 2, false));
provisioner.provision(existingResource(), props(PROVISIONED), updateCtx(PROVISIONED));
verify(tableService, never()).updateThroughput(anyString(), any(), anyString());
}
@Test
void updateOfAnOnDemandTableLeavesCapacityAlone() throws Exception {
existingTable(table(0, 0, true));
provisioner.provision(existingResource(), props(ON_DEMAND_WARM),
updateCtx("{\"TableName\":\"orders\",\"BillingMode\":\"PAY_PER_REQUEST\"}"));
ThroughputChange change = updatedThroughput();
assertNull(change.table().capacity());
assertEquals(new WarmUnits(12000L, 4000L), change.table().warm());
}
@Test
void updateRaisingCapacityAndWarmThroughputTogetherIsOneCall() throws Exception {
existingTable(table(1, 2, false));
provisioner.provision(existingResource(), props(CAPACITY_AND_WARM), updateCtx(PROVISIONED));
ThroughputChange change = updatedThroughput();
assertEquals(new CapacityUnits(3, 3), change.table().capacity());
assertEquals(new WarmUnits(3L, 3L), change.table().warm());
}
@Test
void updateWithTheCurrentWarmThroughputSendsNoWarmThroughput() throws Exception {
TableDefinition current = table(1, 2, false);
current.setWarmReadUnitsPerSecond(5000);
existingTable(current);
provisioner.provision(existingResource(), props(WARM), updateCtx(PROVISIONED));
ThroughputChange change = updatedThroughput();
assertNull(change.table().warm());
assertEquals(new WarmUnits(null, 4000L), change.indexes().get(INDEX).warm());
}
@Test
void anUnchangedWarmThroughputIsNotSentEvenWhenItDiffersFromTheTable() throws Exception {
TableDefinition current = table(3, 3, false);
current.setWarmReadUnitsPerSecond(3);
current.setWarmWriteUnitsPerSecond(3);
existingTable(current);
provisioner.provision(existingResource(), props(UNCHANGED_WARM_RAISED), updateCtx(UNCHANGED_WARM));
ThroughputChange change = updatedThroughput();
assertEquals(new CapacityUnits(4, 4), change.table().capacity());
assertNull(change.table().warm());
}
@Test
void aChangedWarmThroughputIsSent() throws Exception {
TableDefinition current = table(3, 3, false);
current.setWarmReadUnitsPerSecond(3);
current.setWarmWriteUnitsPerSecond(3);
existingTable(current);
provisioner.provision(existingResource(), props(CHANGED_WARM), updateCtx(UNCHANGED_WARM));
assertEquals(new WarmUnits(2L, 2L), updatedThroughput().table().warm());
}
@Test
void anIndexWarmThroughputFollowsTheSameRuleByIndexName() throws Exception {
TableDefinition current = table(1, 3, false);
existingTable(current);
provisioner.provision(existingResource(), props(INDEX_WARM_CHANGED), updateCtx(INDEX_WARM));
assertEquals(new WarmUnits(2L, 2L), updatedThroughput().indexes().get(INDEX).warm());
}
@Test
void anUnchangedIndexWarmThroughputIsNotSent() throws Exception {
existingTable(table(1, 3, false));
provisioner.provision(existingResource(), props(INDEX_WARM), updateCtx(INDEX_WARM));
verify(tableService, never()).updateThroughput(anyString(), any(), anyString());
}
@Test
void aWarmThroughputWithNoPreviousOneCountsAsChanged() throws Exception {
existingTable(table(1, 2, false));
provisioner.provision(existingResource(), props(UNCHANGED_WARM), updateCtx(UNDECLARED));
assertEquals(new WarmUnits(1L, 1L), updatedThroughput().table().warm());
}
@Test
void updateThatTheApiRefusesKeepsTheSnapshotForTheRollback() throws Exception {
existingTable(table(1, 2, false));
when(tableService.updateThroughput(anyString(), any(), anyString()))
.thenThrow(new AwsException("ValidationException", "decreasing WarmThroughput is not supported", 400));
StackResource r = existingResource();
assertThrows(AwsException.class, () -> provisioner.provision(r, props(CAPACITY_AND_WARM), updateCtx(WARM)));
assertTrue(provisioner.retainsFailedUpdateState(r));
}
@Test
void rollbackPutsThePreviousCapacityBack() throws Exception {
existingTable(table(1, 2, false));
StackResource r = existingResource();
provisioner.provision(r, props(RAISED), updateCtx(PROVISIONED));
when(dynamoDb.describeTable(TABLE_NAME, REGION)).thenReturn(table(3, 1, false));
assertTrue(provisioner.rollbackUpdate(r));
ArgumentCaptor<ThroughputChange> change = ArgumentCaptor.forClass(ThroughputChange.class);
verify(tableService, times(2)).updateThroughput(eq(TABLE_NAME), change.capture(),
eq(REGION));
ThroughputChange restore = change.getAllValues().get(1);
assertEquals(new CapacityUnits(1, 1), restore.table().capacity());
assertNull(restore.table().warm());
assertEquals(new CapacityUnits(2, 2), restore.indexes().get(INDEX).capacity());
assertFalse(r.getAttributes().containsKey(CfnRollback.DYNAMODB_TABLE_UPDATE_SNAPSHOT_ATTR));
}
@Test
void rollbackOfASnapshotWithoutCapacityLeavesItAlone() {
when(dynamoDb.describeTable(TABLE_NAME, REGION)).thenReturn(table(3, 1, false));
StackResource r = existingResource();
r.getAttributes().put(CfnRollback.DYNAMODB_TABLE_UPDATE_SNAPSHOT_ATTR, "{\"accountId\":\"000000000000\","
+ "\"region\":\"us-east-1\",\"tableName\":\"orders\",\"tags\":{},\"streamEnabled\":false,"
+ "\"streamViewType\":null,\"ttlEnabled\":false,\"ttlAttributeName\":null}");
assertTrue(provisioner.rollbackUpdate(r));
verify(tableService, never()).updateThroughput(anyString(), any(), anyString());
}
}
@@ -92,6 +92,19 @@ public final class RecordingDynamoDbBackend implements DynamoDbItemAccess, Dynam
return record("createTable", scope);
}
@Override
public TableDefinition createTable(Scope scope, String tableName, List<KeySchemaElement> keySchema,
List<AttributeDefinition> attributeDefinitions, boolean onDemand,
ThroughputSpec throughput, List<GlobalSecondaryIndex> globalSecondaryIndexes,
List<LocalSecondaryIndex> localSecondaryIndexes) {
return record("createTable", scope);
}
@Override
public TableDefinition updateThroughput(Scope scope, String tableName, ThroughputChange change) {
return record("updateThroughput", scope);
}
@Override
public TableDefinition createOnDemandTable(Scope scope, String tableName, List<KeySchemaElement> keySchema,
List<AttributeDefinition> attributeDefinitions,