mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
d427b31e07
commit
f3c21892a6
10 files changed
+1236
-24
No files matched your search
+3
-3
@@ -52,7 +52,7 @@ final class CfnPropertyTypes {
|
||||
private static final Pattern SIGNED_WHOLE_NUMBER = Pattern.compile("[+-]?\\d+");
|
||||
private static final Set<String> TRUE_TEXT = Set.of("true", "True", "TRUE");
|
||||
private static final Set<String> FALSE_TEXT = Set.of("false", "False", "FALSE");
|
||||
private static final String INTEGER_RANGE_HINT = ". This may occur when a numeric value exceeds 32-bit"
|
||||
static final String INTEGER_RANGE_HINT = ". This may occur when a numeric value exceeds 32-bit"
|
||||
+ " integer max (2147483647). Consider using 'number' type or ensure value fits in integer range.";
|
||||
|
||||
private static final class Holder {
|
||||
@@ -605,11 +605,11 @@ final class CfnPropertyTypes {
|
||||
}
|
||||
|
||||
/** The resource handler's model validation failure; {@code violations} ends with its closing parenthesis. */
|
||||
private static AwsException modelValidation(String violations) {
|
||||
static AwsException modelValidation(String violations) {
|
||||
return new AwsException("InvalidRequest", "Model validation failed (" + violations, 400);
|
||||
}
|
||||
|
||||
private static AwsException templateMismatch(String property, String expected, String found) {
|
||||
static AwsException templateMismatch(String property, String expected, String found) {
|
||||
return new AwsException("ValidationError", "Property [" + property + "] expected type: "
|
||||
+ expected + ", found: " + found, 400);
|
||||
}
|
||||
|
||||
+232
-10
@@ -13,17 +13,23 @@ import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.floci.aws.services.cloudformation.model.StackResource;
|
||||
import io.floci.aws.services.dynamodb.DynamoDbFacade;
|
||||
import io.floci.aws.services.dynamodb.backend.DynamoDbOperations.Scope;
|
||||
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.TimeToLive;
|
||||
import io.floci.aws.services.dynamodb.backend.DynamoDbTableAccess.WarmUnits;
|
||||
import io.floci.aws.services.dynamodb.model.AttributeDefinition;
|
||||
import io.floci.aws.services.dynamodb.model.GlobalSecondaryIndex;
|
||||
import io.floci.aws.services.dynamodb.model.KeySchemaElement;
|
||||
import io.floci.aws.services.dynamodb.model.KinesisStreamingDestination;
|
||||
import io.floci.aws.services.dynamodb.model.LocalSecondaryIndex;
|
||||
import io.floci.aws.services.dynamodb.model.ProvisionedThroughput;
|
||||
import io.floci.aws.services.dynamodb.model.TableDefinition;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -63,6 +69,8 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {
|
||||
private static final Logger LOG = Logger.getLogger(DynamoDbCfnProvisioner.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final TimeToLive TIME_TO_LIVE_OFF = new TimeToLive(false, null);
|
||||
private static final ThroughputSpec NO_THROUGHPUT = new ThroughputSpec(null, null);
|
||||
private static final String PAY_PER_REQUEST = "PAY_PER_REQUEST";
|
||||
|
||||
private static final String REPLICA_TABLE_NAME_ATTR = "TableName";
|
||||
private static final String REPLICA_REGION_ATTR = "__FlociDynamoDbReplicaRegion";
|
||||
@@ -173,6 +181,11 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {
|
||||
? List.of(declaredKinesisDestination(kinesisSpec, engine))
|
||||
: List.of();
|
||||
|
||||
// GlobalTable and the replica resource carry their own throughput settings, which are not read here.
|
||||
boolean plainTable = TABLE.equals(r.getResourceType());
|
||||
ThroughputSpec tableThroughput = plainTable ? declaredThroughput(props, "#", ctx) : NO_THROUGHPUT;
|
||||
Map<String, ThroughputSpec> indexThroughput = new LinkedHashMap<>();
|
||||
|
||||
List<KeySchemaElement> keySchema = new ArrayList<>();
|
||||
List<AttributeDefinition> attrDefs = new ArrayList<>();
|
||||
List<GlobalSecondaryIndex> gsis = new ArrayList<>();
|
||||
@@ -194,6 +207,7 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
if (props != null && props.has("GlobalSecondaryIndexes")) {
|
||||
int indexPosition = 0;
|
||||
for (JsonNode gsiNode : props.get("GlobalSecondaryIndexes")) {
|
||||
String indexName = engine.resolve(gsiNode.get("IndexName"));
|
||||
List<KeySchemaElement> gsiKeySchema = new ArrayList<>();
|
||||
@@ -216,7 +230,22 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
}
|
||||
}
|
||||
gsis.add(new GlobalSecondaryIndex(indexName, gsiKeySchema, null, projectionType, nonKeyAttributes));
|
||||
GlobalSecondaryIndex gsi = new GlobalSecondaryIndex(indexName, gsiKeySchema, null, projectionType,
|
||||
nonKeyAttributes);
|
||||
if (plainTable) {
|
||||
ThroughputSpec declared = declaredThroughput(gsiNode, "#/GlobalSecondaryIndexes/" + indexPosition, ctx);
|
||||
if (declared.capacity() != null) {
|
||||
gsi.setProvisionedThroughput(new ProvisionedThroughput(
|
||||
declared.capacity().readCapacityUnits(), declared.capacity().writeCapacityUnits()));
|
||||
}
|
||||
if (declared.warm() != null) {
|
||||
gsi.setWarmReadUnitsPerSecond(declared.warm().readUnitsPerSecond());
|
||||
gsi.setWarmWriteUnitsPerSecond(declared.warm().writeUnitsPerSecond());
|
||||
}
|
||||
indexThroughput.put(indexName, declared);
|
||||
}
|
||||
gsis.add(gsi);
|
||||
indexPosition++;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,13 +275,26 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
Scope scope = new Scope(ctx.accountId(), region);
|
||||
boolean onDemand = "PAY_PER_REQUEST".equals(ctx.resolveOptional(props, "BillingMode"));
|
||||
boolean onDemand = PAY_PER_REQUEST.equals(ctx.resolveOptional(props, "BillingMode"));
|
||||
boolean declaresCapacity = tableThroughput.capacity() != null
|
||||
|| indexThroughput.values().stream().anyMatch(spec -> spec.capacity() != null);
|
||||
if (onDemand && declaresCapacity) {
|
||||
throw new AwsException("InvalidRequest",
|
||||
"Property ProvisionedThroughput can't be used with PAY_PER_REQUEST BillingMode.", 400);
|
||||
}
|
||||
boolean throughputDeclared = isDeclared(tableThroughput) || indexThroughput.values().stream()
|
||||
.anyMatch(DynamoDbCfnProvisioner::isDeclared);
|
||||
TableDefinition table;
|
||||
boolean created = false;
|
||||
try {
|
||||
table = onDemand
|
||||
? dynamoDb.tables().createOnDemandTable(scope, tableName, keySchema, attrDefs, gsis, lsis)
|
||||
: dynamoDb.tables().createTable(scope, tableName, keySchema, attrDefs, null, null, gsis, lsis);
|
||||
if (throughputDeclared) {
|
||||
table = dynamoDb.tables().createTable(scope, tableName, keySchema, attrDefs, onDemand,
|
||||
tableThroughput, gsis, lsis);
|
||||
} else {
|
||||
table = onDemand
|
||||
? dynamoDb.tables().createOnDemandTable(scope, tableName, keySchema, attrDefs, gsis, lsis)
|
||||
: dynamoDb.tables().createTable(scope, tableName, keySchema, attrDefs, null, null, gsis, lsis);
|
||||
}
|
||||
created = true;
|
||||
} catch (AwsException e) {
|
||||
if (!"ResourceInUseException".equals(e.getErrorCode())) {
|
||||
@@ -280,6 +322,15 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {
|
||||
reconcileTags(scope, table.getTableArn(), currentTags,
|
||||
parseCfnTags(props != null ? props.get("Tags") : null, engine));
|
||||
|
||||
if (inPlaceUpdate && plainTable) {
|
||||
JsonNode priorProperties = ctx.isUpdate() ? ctx.priorProperties() : null;
|
||||
Map<String, ThroughputSpec> changedIndexes = new LinkedHashMap<>();
|
||||
indexThroughput.forEach((indexName, spec) -> changedIndexes.put(indexName,
|
||||
withChangedWarm(spec, priorIndex(priorProperties, indexName, ctx), ctx)));
|
||||
table = reconcileThroughput(scope, tableName, table,
|
||||
withChangedWarm(tableThroughput, priorProperties, ctx), changedIndexes);
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -339,6 +390,151 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the {@code ProvisionedThroughput} and {@code WarmThroughput} of a table or an index. Each
|
||||
* object needs its members, as CloudFormation requires: both capacity units, and at least one
|
||||
* warm member, so an empty {@code WarmThroughput} object fails.
|
||||
*/
|
||||
private static ThroughputSpec declaredThroughput(JsonNode owner, String pointer, ProvisionContext ctx) {
|
||||
CloudFormationTemplateEngine engine = ctx.engine();
|
||||
CapacityUnits capacity = null;
|
||||
JsonNode provisioned = owner == null ? null : engine.resolveNode(owner.get("ProvisionedThroughput"));
|
||||
if (provisioned != null && !provisioned.isNull()) {
|
||||
CfnPropertyTypes.requireType("ProvisionedThroughput", provisioned, JsonNodeType.OBJECT);
|
||||
String capacityPointer = pointer + "/ProvisionedThroughput";
|
||||
capacity = new CapacityUnits(requiredUnits(provisioned, "ReadCapacityUnits", capacityPointer, ctx),
|
||||
requiredUnits(provisioned, "WriteCapacityUnits", capacityPointer, ctx));
|
||||
}
|
||||
WarmUnits warm = null;
|
||||
JsonNode warmNode = owner == null ? null : engine.resolveNode(owner.get("WarmThroughput"));
|
||||
if (warmNode != null && !warmNode.isNull()) {
|
||||
CfnPropertyTypes.requireType("WarmThroughput", warmNode, JsonNodeType.OBJECT);
|
||||
String warmPointer = pointer + "/WarmThroughput";
|
||||
Long read = optionalUnits(warmNode, "ReadUnitsPerSecond", warmPointer, ctx);
|
||||
Long write = optionalUnits(warmNode, "WriteUnitsPerSecond", warmPointer, ctx);
|
||||
if (read == null && write == null) {
|
||||
throw requiredProperty("ReadUnitsPerSecond");
|
||||
}
|
||||
warm = new WarmUnits(read, write);
|
||||
}
|
||||
return new ThroughputSpec(capacity, warm);
|
||||
}
|
||||
|
||||
private static long requiredUnits(JsonNode owner, String member, String pointer, ProvisionContext ctx) {
|
||||
Long units = optionalUnits(owner, member, pointer, ctx);
|
||||
if (units == null) {
|
||||
throw requiredProperty(member);
|
||||
}
|
||||
return units;
|
||||
}
|
||||
|
||||
private static AwsException requiredProperty(String member) {
|
||||
return new AwsException("InvalidRequest", "Required property [" + member + "] not found", 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* CloudFormation sends WarmThroughput in an UpdateTable only when the template's value changed
|
||||
* from the previous template, so a value the template kept is dropped here even when the table
|
||||
* has since grown past it.
|
||||
*/
|
||||
private static ThroughputSpec withChangedWarm(ThroughputSpec desired, JsonNode priorOwner,
|
||||
ProvisionContext ctx) {
|
||||
if (desired.warm() == null) {
|
||||
return desired;
|
||||
}
|
||||
JsonNode prior = priorOwner == null ? null : ctx.priorEngine().resolveNode(priorOwner.get("WarmThroughput"));
|
||||
if (prior == null || !prior.isObject() || !sameUnits(desired.warm().readUnitsPerSecond(),
|
||||
prior.get("ReadUnitsPerSecond")) || !sameUnits(desired.warm().writeUnitsPerSecond(),
|
||||
prior.get("WriteUnitsPerSecond"))) {
|
||||
return desired;
|
||||
}
|
||||
return new ThroughputSpec(desired.capacity(), null);
|
||||
}
|
||||
|
||||
private static boolean sameUnits(Long desired, JsonNode prior) {
|
||||
boolean priorDeclared = prior != null && !prior.isNull();
|
||||
return desired == null ? !priorDeclared : priorDeclared && prior.asLong() == desired;
|
||||
}
|
||||
|
||||
private static JsonNode priorIndex(JsonNode priorProperties, String indexName, ProvisionContext ctx) {
|
||||
JsonNode indexes = priorProperties == null ? null
|
||||
: ctx.priorEngine().resolveNode(priorProperties.get("GlobalSecondaryIndexes"));
|
||||
if (indexes == null || !indexes.isArray()) {
|
||||
return null;
|
||||
}
|
||||
for (JsonNode index : indexes) {
|
||||
if (indexName.equals(ctx.priorEngine().resolve(index.get("IndexName")))) {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Long optionalUnits(JsonNode owner, String member, String pointer, ProvisionContext ctx) {
|
||||
JsonNode declared = owner.get(member);
|
||||
if (declared != null && declared.isArray()) {
|
||||
throw CfnPropertyTypes.templateMismatch(member, "Integer", "JSONArray");
|
||||
}
|
||||
BigInteger units = ctx.resolveOptionalBigInteger(owner, member);
|
||||
if (units != null && units.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {
|
||||
throw CfnPropertyTypes.modelValidation(pointer + "/" + member
|
||||
+ ": expected type: Integer, found: String" + CfnPropertyTypes.INTEGER_RANGE_HINT + ")");
|
||||
}
|
||||
return units == null ? null : units.longValue();
|
||||
}
|
||||
|
||||
private static boolean isDeclared(ThroughputSpec spec) {
|
||||
return spec.capacity() != null || spec.warm() != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the capacity and warm throughput of the table and of its existing indexes that differ
|
||||
* from what the template declares, in one UpdateTable. A declared warm value equal to the current
|
||||
* one is not sent, and a lower one is left for the API to refuse. An on-demand table has no
|
||||
* capacity to change.
|
||||
*/
|
||||
private TableDefinition reconcileThroughput(Scope scope, String tableName, TableDefinition table,
|
||||
ThroughputSpec tableDesired,
|
||||
Map<String, ThroughputSpec> indexesDesired) {
|
||||
boolean provisioned = !PAY_PER_REQUEST.equals(table.getBillingMode());
|
||||
ThroughputSpec tableChange = changedThroughput(tableDesired, table.getProvisionedThroughput(),
|
||||
table.getWarmReadUnitsPerSecond(), table.getWarmWriteUnitsPerSecond(), provisioned);
|
||||
Map<String, ThroughputSpec> indexChanges = new LinkedHashMap<>();
|
||||
for (GlobalSecondaryIndex gsi : table.getGlobalSecondaryIndexes()) {
|
||||
ThroughputSpec desired = indexesDesired.get(gsi.getIndexName());
|
||||
if (desired == null) {
|
||||
continue;
|
||||
}
|
||||
ThroughputSpec change = changedThroughput(desired, gsi.getProvisionedThroughput(),
|
||||
table.gsiWarmReadUnits(gsi), table.gsiWarmWriteUnits(gsi), provisioned);
|
||||
if (change != null) {
|
||||
indexChanges.put(gsi.getIndexName(), change);
|
||||
}
|
||||
}
|
||||
if (tableChange == null && indexChanges.isEmpty()) {
|
||||
return table;
|
||||
}
|
||||
return dynamoDb.tables().updateThroughput(scope, tableName,
|
||||
new ThroughputChange(tableChange != null ? tableChange : NO_THROUGHPUT, indexChanges));
|
||||
}
|
||||
|
||||
private static ThroughputSpec changedThroughput(ThroughputSpec desired, ProvisionedThroughput current,
|
||||
long currentWarmRead, long currentWarmWrite,
|
||||
boolean provisioned) {
|
||||
CapacityUnits capacity = desired.capacity();
|
||||
if (!provisioned || capacity == null || current != null
|
||||
&& capacity.readCapacityUnits() == current.getReadCapacityUnits()
|
||||
&& capacity.writeCapacityUnits() == current.getWriteCapacityUnits()) {
|
||||
capacity = null;
|
||||
}
|
||||
WarmUnits warm = desired.warm();
|
||||
if (warm != null && (warm.readUnitsPerSecond() == null || warm.readUnitsPerSecond() == currentWarmRead)
|
||||
&& (warm.writeUnitsPerSecond() == null || warm.writeUnitsPerSecond() == currentWarmWrite)) {
|
||||
warm = null;
|
||||
}
|
||||
return capacity == null && warm == null ? null : new ThroughputSpec(capacity, warm);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the table a failed provision created. A delete that fails on create leaves the table
|
||||
* owned by the resource, so the stack's create rollback retries it. On a replacing update the
|
||||
@@ -550,9 +746,10 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the tags, stream setting, TTL setting and active Kinesis streaming destinations the table
|
||||
* has before an in-place update changes them, with the account and region that address it, so
|
||||
* {@link #rollbackUpdate} can put all four back.
|
||||
* Keeps the tags, stream setting, TTL setting, active Kinesis streaming destinations and the
|
||||
* capacity of the table and its indexes the table has before an in-place update changes them, with
|
||||
* the account and region that address it, so {@link #rollbackUpdate} can put them back. Warm
|
||||
* throughput is not kept, as it cannot be lowered.
|
||||
*/
|
||||
private static void snapshotBeforeUpdate(StackResource r, Scope scope, String tableName, TableDefinition table,
|
||||
Map<String, String> tags, TimeToLive ttl, boolean kinesisManaged) {
|
||||
@@ -566,6 +763,13 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {
|
||||
snapshot.put("streamViewType", table.getStreamViewType());
|
||||
snapshot.put("ttlEnabled", ttl.enabled());
|
||||
snapshot.put("ttlAttributeName", ttl.attributeName());
|
||||
if (!PAY_PER_REQUEST.equals(table.getBillingMode()) && table.getProvisionedThroughput() != null) {
|
||||
snapshot.set("tableCapacity", capacityNode(table.getProvisionedThroughput()));
|
||||
ObjectNode indexCapacities = snapshot.putObject("indexCapacities");
|
||||
for (GlobalSecondaryIndex gsi : table.getGlobalSecondaryIndexes()) {
|
||||
indexCapacities.set(gsi.getIndexName(), capacityNode(gsi.getProvisionedThroughput()));
|
||||
}
|
||||
}
|
||||
if (kinesisManaged) {
|
||||
ArrayNode destinations = snapshot.putArray("kinesisDestinations");
|
||||
for (KinesisDestinationSpec destination : activeKinesisDestinations(table)) {
|
||||
@@ -577,6 +781,16 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {
|
||||
r.getAttributes().put(CfnRollback.DYNAMODB_TABLE_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
|
||||
}
|
||||
|
||||
private static ObjectNode capacityNode(ProvisionedThroughput throughput) {
|
||||
return MAPPER.createObjectNode()
|
||||
.put("read", throughput.getReadCapacityUnits())
|
||||
.put("write", throughput.getWriteCapacityUnits());
|
||||
}
|
||||
|
||||
private static CapacityUnits capacityUnits(JsonNode node) {
|
||||
return new CapacityUnits(node.path("read").asLong(), node.path("write").asLong());
|
||||
}
|
||||
|
||||
/**
|
||||
* An in-place update that failed after its snapshot may already have changed the table, so the
|
||||
* engine keeps this attempt for {@link #rollbackUpdate} instead of putting the previous resource
|
||||
@@ -614,8 +828,8 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts back the tags, stream setting, TTL setting and Kinesis streaming destinations an in-place
|
||||
* table update changed. All four go back or none is claimed: restoring one alone would report a
|
||||
* Puts back the tags, capacity, stream setting, TTL setting and Kinesis streaming destinations an
|
||||
* in-place table update changed. All of them go back or none is claimed: restoring one alone would report a
|
||||
* rollback while the others stayed changed. A snapshot without destinations leaves them as they
|
||||
* are. Only an in-place {@code AWS::DynamoDB::Table} update takes the snapshot; a replacing update is
|
||||
* undone by its recorded replacement and a global table reports that rollback is not implemented. The
|
||||
@@ -644,6 +858,14 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {
|
||||
reconcileTags(scope, table.getTableArn(),
|
||||
dynamoDb.tables().listTagsOfResource(scope, table.getTableArn()), tags);
|
||||
|
||||
if (snapshot.has("tableCapacity")) {
|
||||
Map<String, ThroughputSpec> priorIndexes = new LinkedHashMap<>();
|
||||
snapshot.path("indexCapacities").properties().forEach(index -> priorIndexes.put(index.getKey(),
|
||||
new ThroughputSpec(capacityUnits(index.getValue()), null)));
|
||||
table = reconcileThroughput(scope, tableName, table,
|
||||
new ThroughputSpec(capacityUnits(snapshot.get("tableCapacity")), null), priorIndexes);
|
||||
}
|
||||
|
||||
if (snapshot.path("streamEnabled").asBoolean()) {
|
||||
table = dynamoDb.tables().enableStream(scope, tableName, snapshot.path("streamViewType").textValue());
|
||||
} else if (table.isStreamEnabled()) {
|
||||
|
||||
@@ -3,6 +3,10 @@ package io.floci.aws.services.dynamodb;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.SmithyValidationErrors;
|
||||
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.model.AttributeDefinition;
|
||||
import io.floci.aws.services.dynamodb.model.GlobalSecondaryIndex;
|
||||
import io.floci.aws.services.dynamodb.model.KeySchemaElement;
|
||||
@@ -408,6 +412,37 @@ public class NativeDynamoDbTableService {
|
||||
return new AwsException("ValidationException", "Invalid Request: " + message, 400);
|
||||
}
|
||||
|
||||
/** The CreateTable a template's declared throughput asks for, with the checks of the API. */
|
||||
public TableDefinition createTable(String tableName, List<KeySchemaElement> keySchema,
|
||||
List<AttributeDefinition> attributeDefinitions, boolean onDemand,
|
||||
ThroughputSpec throughput, List<GlobalSecondaryIndex> globalSecondaryIndexes,
|
||||
List<LocalSecondaryIndex> localSecondaryIndexes, String region) {
|
||||
TableSettings settings = new TableSettings(onDemand ? "PAY_PER_REQUEST" : null, null, null, null, null,
|
||||
null, null, null, null);
|
||||
return createTable(new CreateTableRequest(tableName, keySchema, attributeDefinitions,
|
||||
throughput(throughput.capacity()), globalSecondaryIndexes, localSecondaryIndexes, List.of(),
|
||||
Map.of(), settings, warm(throughput.warm())), "ACTIVE", region);
|
||||
}
|
||||
|
||||
/** The one UpdateTable a template's declared throughput asks for, with the checks of the API. */
|
||||
public TableDefinition updateThroughput(String tableName, ThroughputChange change, String region) {
|
||||
List<GsiThroughputUpdate> indexUpdates = new ArrayList<>();
|
||||
change.indexes().forEach((indexName, spec) -> indexUpdates.add(new GsiThroughputUpdate(indexName,
|
||||
throughput(spec.capacity()), null, warm(spec.warm()))));
|
||||
TableSettings settings = new TableSettings(null, null, null, null, null, null, null, null, null);
|
||||
return updateTable(new UpdateTableRequest(tableName, throughput(change.table().capacity()), List.of(),
|
||||
List.of(), List.of(), indexUpdates, List.of(), List.of(), List.of(), List.of(), List.of(), settings,
|
||||
warm(change.table().warm())), region);
|
||||
}
|
||||
|
||||
private static Throughput throughput(CapacityUnits capacity) {
|
||||
return capacity == null ? null : new Throughput(capacity.readCapacityUnits(), capacity.writeCapacityUnits());
|
||||
}
|
||||
|
||||
private static WarmThroughput warm(WarmUnits warm) {
|
||||
return warm == null ? null : new WarmThroughput(warm.readUnitsPerSecond(), warm.writeUnitsPerSecond());
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the table, applies the request's settings and replica changes to it and persists
|
||||
* the result.
|
||||
|
||||
@@ -381,23 +381,49 @@ public class DynamoDbLocalBackend implements DynamoDbBackend {
|
||||
List<AttributeDefinition> attributeDefinitions, Long readCapacity,
|
||||
Long writeCapacity, List<GlobalSecondaryIndex> globalSecondaryIndexes,
|
||||
List<LocalSecondaryIndex> localSecondaryIndexes) {
|
||||
CapacityUnits capacity = readCapacity != null && writeCapacity != null
|
||||
? new CapacityUnits(readCapacity, writeCapacity) : null;
|
||||
return createLocalTable(scope, tableName, keySchema, attributeDefinitions, capacity, null,
|
||||
globalSecondaryIndexes, localSecondaryIndexes);
|
||||
}
|
||||
|
||||
@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 createLocalTable(scope, tableName, keySchema, attributeDefinitions,
|
||||
onDemand ? null : throughput.capacity(), throughput.warm(), globalSecondaryIndexes,
|
||||
localSecondaryIndexes);
|
||||
}
|
||||
|
||||
private TableDefinition createLocalTable(Scope scope, String tableName, List<KeySchemaElement> keySchema,
|
||||
List<AttributeDefinition> attributeDefinitions, CapacityUnits capacity,
|
||||
WarmUnits warm, List<GlobalSecondaryIndex> globalSecondaryIndexes,
|
||||
List<LocalSecondaryIndex> localSecondaryIndexes) {
|
||||
ObjectNode body = body(tableName, "KeySchema", keySchema, "AttributeDefinitions", attributeDefinitions);
|
||||
ObjectNode throughput = null;
|
||||
if (readCapacity != null && writeCapacity != null) {
|
||||
throughput = aws.createObjectNode()
|
||||
.put("ReadCapacityUnits", readCapacity)
|
||||
.put("WriteCapacityUnits", writeCapacity);
|
||||
body.put("BillingMode", "PROVISIONED").set("ProvisionedThroughput", throughput);
|
||||
if (capacity != null) {
|
||||
body.put("BillingMode", "PROVISIONED").set("ProvisionedThroughput", capacity(capacity));
|
||||
} else {
|
||||
body.put("BillingMode", "PAY_PER_REQUEST");
|
||||
}
|
||||
if (warm != null) {
|
||||
body.set("WarmThroughput", warm(warm));
|
||||
}
|
||||
if (globalSecondaryIndexes != null && !globalSecondaryIndexes.isEmpty()) {
|
||||
ArrayNode indexes = body.putArray("GlobalSecondaryIndexes");
|
||||
for (GlobalSecondaryIndex gsi : globalSecondaryIndexes) {
|
||||
ObjectNode index = index(indexes, gsi.getIndexName(), gsi.getKeySchema(), gsi.getProjectionType(),
|
||||
gsi.getNonKeyAttributes());
|
||||
if (throughput != null) {
|
||||
index.set("ProvisionedThroughput", throughput.deepCopy());
|
||||
if (capacity != null) {
|
||||
long read = gsi.getProvisionedThroughput().getReadCapacityUnits();
|
||||
long write = gsi.getProvisionedThroughput().getWriteCapacityUnits();
|
||||
index.set("ProvisionedThroughput",
|
||||
read > 0 && write > 0 ? capacity(new CapacityUnits(read, write)) : capacity(capacity));
|
||||
}
|
||||
if (gsi.getWarmReadUnitsPerSecond() != null || gsi.getWarmWriteUnitsPerSecond() != null) {
|
||||
index.set("WarmThroughput",
|
||||
warm(new WarmUnits(gsi.getWarmReadUnitsPerSecond(), gsi.getWarmWriteUnitsPerSecond())));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -411,6 +437,47 @@ public class DynamoDbLocalBackend implements DynamoDbBackend {
|
||||
return table(call(scope, "CreateTable", body).path("TableDescription"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableDefinition updateThroughput(Scope scope, String tableName, ThroughputChange change) {
|
||||
ObjectNode body = body(tableName);
|
||||
if (change.table().capacity() != null) {
|
||||
body.set("ProvisionedThroughput", capacity(change.table().capacity()));
|
||||
}
|
||||
if (change.table().warm() != null) {
|
||||
body.set("WarmThroughput", warm(change.table().warm()));
|
||||
}
|
||||
if (!change.indexes().isEmpty()) {
|
||||
ArrayNode updates = body.putArray("GlobalSecondaryIndexUpdates");
|
||||
change.indexes().forEach((indexName, spec) -> {
|
||||
ObjectNode update = updates.addObject().putObject("Update").put("IndexName", indexName);
|
||||
if (spec.capacity() != null) {
|
||||
update.set("ProvisionedThroughput", capacity(spec.capacity()));
|
||||
}
|
||||
if (spec.warm() != null) {
|
||||
update.set("WarmThroughput", warm(spec.warm()));
|
||||
}
|
||||
});
|
||||
}
|
||||
return table(call(scope, "UpdateTable", body).path("TableDescription"));
|
||||
}
|
||||
|
||||
private ObjectNode capacity(CapacityUnits capacity) {
|
||||
return aws.createObjectNode()
|
||||
.put("ReadCapacityUnits", capacity.readCapacityUnits())
|
||||
.put("WriteCapacityUnits", capacity.writeCapacityUnits());
|
||||
}
|
||||
|
||||
private ObjectNode warm(WarmUnits warm) {
|
||||
ObjectNode node = aws.createObjectNode();
|
||||
if (warm.readUnitsPerSecond() != null) {
|
||||
node.put("ReadUnitsPerSecond", warm.readUnitsPerSecond());
|
||||
}
|
||||
if (warm.writeUnitsPerSecond() != null) {
|
||||
node.put("WriteUnitsPerSecond", warm.writeUnitsPerSecond());
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableDefinition createOnDemandTable(Scope scope, String tableName, List<KeySchemaElement> keySchema,
|
||||
List<AttributeDefinition> attributeDefinitions,
|
||||
|
||||
@@ -19,11 +19,39 @@ public interface DynamoDbTableAccess {
|
||||
record TimeToLive(boolean enabled, String attributeName) {
|
||||
}
|
||||
|
||||
/** The provisioned capacity of a table or an index. */
|
||||
record CapacityUnits(long readCapacityUnits, long writeCapacityUnits) {
|
||||
}
|
||||
|
||||
/** A warm throughput a table or an index should have. A null member is left as it is. */
|
||||
record WarmUnits(Long readUnitsPerSecond, Long writeUnitsPerSecond) {
|
||||
}
|
||||
|
||||
/** What a template declares for one table or index. A null member is not declared. */
|
||||
record ThroughputSpec(CapacityUnits capacity, WarmUnits warm) {
|
||||
}
|
||||
|
||||
/** The throughput to apply to a table and to some of its indexes, by index name. */
|
||||
record ThroughputChange(ThroughputSpec table, Map<String, ThroughputSpec> indexes) {
|
||||
}
|
||||
|
||||
TableDefinition createTable(Scope scope, String tableName, List<KeySchemaElement> keySchema,
|
||||
List<AttributeDefinition> attributeDefinitions, Long readCapacity,
|
||||
Long writeCapacity, List<GlobalSecondaryIndex> globalSecondaryIndexes,
|
||||
List<LocalSecondaryIndex> localSecondaryIndexes);
|
||||
|
||||
/**
|
||||
* Creates a table with the declared throughput. An index takes its own capacity and warm
|
||||
* throughput from its {@link GlobalSecondaryIndex}.
|
||||
*/
|
||||
TableDefinition createTable(Scope scope, String tableName, List<KeySchemaElement> keySchema,
|
||||
List<AttributeDefinition> attributeDefinitions, boolean onDemand,
|
||||
ThroughputSpec throughput, List<GlobalSecondaryIndex> globalSecondaryIndexes,
|
||||
List<LocalSecondaryIndex> localSecondaryIndexes);
|
||||
|
||||
/** One UpdateTable that changes the capacity and warm throughput of the table and of the named indexes. */
|
||||
TableDefinition updateThroughput(Scope scope, String tableName, ThroughputChange change);
|
||||
|
||||
TableDefinition createOnDemandTable(Scope scope, String tableName, List<KeySchemaElement> keySchema,
|
||||
List<AttributeDefinition> attributeDefinitions,
|
||||
List<GlobalSecondaryIndex> globalSecondaryIndexes,
|
||||
|
||||
@@ -171,6 +171,22 @@ public class NativeDynamoDbBackend implements DynamoDbBackend {
|
||||
scope.region()));
|
||||
}
|
||||
|
||||
@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 RequestScopes.callAs(scope.accountId(), () -> tableService.createTable(tableName, keySchema,
|
||||
attributeDefinitions, onDemand, throughput, globalSecondaryIndexes, localSecondaryIndexes,
|
||||
scope.region()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableDefinition updateThroughput(Scope scope, String tableName, ThroughputChange change) {
|
||||
return RequestScopes.callAs(scope.accountId(),
|
||||
() -> tableService.updateThroughput(tableName, change, scope.region()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableDefinition createOnDemandTable(Scope scope, String tableName, List<KeySchemaElement> keySchema,
|
||||
List<AttributeDefinition> attributeDefinitions,
|
||||
|
||||
+308
@@ -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();
|
||||
}
|
||||
}
|
||||
+526
@@ -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,
|
||||
|
||||
@@ -162,7 +162,6 @@ AWS::DynamoDB::GlobalTable ReadProvisionedThroughputSettings accepted and ignore
|
||||
AWS::DynamoDB::GlobalTable SSESpecification accepted and ignored
|
||||
AWS::DynamoDB::GlobalTable TableType accepted and ignored
|
||||
AWS::DynamoDB::GlobalTable VectorIndexes accepted and ignored
|
||||
AWS::DynamoDB::GlobalTable WarmThroughput accepted and ignored
|
||||
AWS::DynamoDB::GlobalTable WriteOnDemandThroughputSettings accepted and ignored
|
||||
AWS::DynamoDB::GlobalTable WriteProvisionedThroughputSettings accepted and ignored
|
||||
AWS::DynamoDB::Table ContributorInsightsSpecification accepted and ignored
|
||||
@@ -170,12 +169,10 @@ AWS::DynamoDB::Table DeletionProtectionEnabled accepted and ignored
|
||||
AWS::DynamoDB::Table ImportSourceSpecification accepted and ignored
|
||||
AWS::DynamoDB::Table OnDemandThroughput accepted and ignored
|
||||
AWS::DynamoDB::Table PointInTimeRecoverySpecification accepted and ignored
|
||||
AWS::DynamoDB::Table ProvisionedThroughput accepted and ignored
|
||||
AWS::DynamoDB::Table ResourcePolicy accepted and ignored
|
||||
AWS::DynamoDB::Table SSESpecification accepted and ignored
|
||||
AWS::DynamoDB::Table TableClass accepted and ignored
|
||||
AWS::DynamoDB::Table VectorIndexes accepted and ignored
|
||||
AWS::DynamoDB::Table WarmThroughput accepted and ignored
|
||||
AWS::EC2::EIP Address accepted and ignored
|
||||
AWS::EC2::EIP Domain accepted and ignored
|
||||
AWS::EC2::EIP InstanceId accepted and ignored
|
||||
|
||||
|
Reference in new issue
Block a user