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

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