From d37698ea715f5bbcbda560e9e906f4b3e77c4d7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?TATSUNO=20=E2=80=9CTaz=E2=80=9D=20Yasuhiro?= Date: Fri, 20 Nov 2026 11:12:08 +0900 Subject: [PATCH] feat(dynamodb): store WarmThroughput from CreateTable and UpdateTable (#9069) * feat(dynamodb): store WarmThroughput from CreateTable and UpdateTable --- docs/services/dynamodb.md | 2 + .../dynamodb/NativeDynamoDbJsonHandler.java | 101 +++++- .../dynamodb/NativeDynamoDbTableService.java | 134 ++++++- .../dynamodb/model/GlobalSecondaryIndex.java | 9 + .../dynamodb/model/TableDefinition.java | 16 + .../NativeDynamoDbJsonHandlerTest.java | 334 ++++++++++++++++++ .../NativeDynamoDbTableServiceTest.java | 10 +- 7 files changed, 584 insertions(+), 22 deletions(-) diff --git a/docs/services/dynamodb.md b/docs/services/dynamodb.md index 48774bcb7f..4cbb30f5c6 100644 --- a/docs/services/dynamodb.md +++ b/docs/services/dynamodb.md @@ -76,6 +76,8 @@ operations keep their existing resource builders, including batch, transaction a | `DescribeImport` | Get import status and metadata | | `ListImports` | List imports, optionally filtered by table ARN | +`CreateTable` and `UpdateTable` store the `WarmThroughput` of a table and of its global secondary indexes, and DescribeTable reports it. Pre-warming finishes at once, so DescribeTable always shows `ACTIVE`. + ## Legacy 2011-12-05 clients The JSON 1.0 target `DynamoDB_20111205` supports `DescribeTable`, `Query` and diff --git a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java index d6df857297..91351a1203 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java +++ b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java @@ -18,6 +18,7 @@ import io.floci.aws.services.dynamodb.NativeDynamoDbTableService.RestoreOverride import io.floci.aws.services.dynamodb.NativeDynamoDbTableService.TableSettings; import io.floci.aws.services.dynamodb.NativeDynamoDbTableService.Throughput; import io.floci.aws.services.dynamodb.NativeDynamoDbTableService.UpdateTableRequest; +import io.floci.aws.services.dynamodb.NativeDynamoDbTableService.WarmThroughput; import io.floci.aws.services.dynamodb.model.AttributeDefinition; import io.floci.aws.services.dynamodb.model.ConditionalCheckFailedException; import io.floci.aws.services.dynamodb.model.ContributorInsights; @@ -83,9 +84,6 @@ public class NativeDynamoDbJsonHandler { List.of("OLD_IMAGE", "KEYS_ONLY", "NEW_AND_OLD_IMAGES", "NEW_IMAGE"); private static final List ATTRIBUTE_TYPES = List.of("B", "N", "S"); private static final List PROJECTION_TYPES = List.of("ALL", "INCLUDE", "KEYS_ONLY"); - // The warm throughput a new on-demand table or index starts with. - private static final long ON_DEMAND_WARM_READ_UNITS = 12000; - private static final long ON_DEMAND_WARM_WRITE_UNITS = 4000; private final DynamoDbService dynamoDbService; private final NativeDynamoDbTableService tableService; @@ -199,7 +197,14 @@ public class NativeDynamoDbJsonHandler { TableDefinition table = createTableFromSpec(request, "", region, "ACTIVE"); ObjectNode tableNode = tableToNode(table); - tableNode.remove("WarmThroughput"); + reportRequestedWarmThroughput(tableNode, request); + JsonNode requestedGsis = request.path("GlobalSecondaryIndexes"); + if (tableNode.has("GlobalSecondaryIndexes")) { + int position = 0; + for (JsonNode gsiNode : tableNode.get("GlobalSecondaryIndexes")) { + reportRequestedWarmThroughput((ObjectNode) gsiNode, requestedGsis.path(position++)); + } + } ObjectNode response = objectMapper.createObjectNode(); response.set("TableDescription", tableNode); return Response.ok(response).build(); @@ -271,6 +276,9 @@ public class NativeDynamoDbJsonHandler { gsi.setOnDemandMaxWriteRequestUnits(gsiOnDemand.get("MaxWriteRequestUnits").asInt()); } } + if (memberPrefix.isEmpty()) { + setWarmThroughput(gsi, parseWarmThroughput(gsiNode.path("WarmThroughput"))); + } gsis.add(gsi); } } @@ -321,7 +329,9 @@ public class NativeDynamoDbJsonHandler { } return tableService.createTable(new CreateTableRequest(tableName, keySchema, attrDefs, - throughput, gsis, lsis, vectorIndexes, tags, parseTableSettings(request)), initialStatus, region); + throughput, gsis, lsis, vectorIndexes, tags, parseTableSettings(request), + memberPrefix.isEmpty() ? parseWarmThroughput(request.path("WarmThroughput")) : null), + initialStatus, region); } /** @@ -2020,6 +2030,7 @@ public class NativeDynamoDbJsonHandler { newGsi.setOnDemandMaxWriteRequestUnits(newGsiOnDemand.get("MaxWriteRequestUnits").asInt()); } } + setWarmThroughput(newGsi, parseWarmThroughput(createNode.path("WarmThroughput"))); gsiCreates.add(newGsi); } JsonNode deleteNode = update.path("Delete"); @@ -2034,7 +2045,8 @@ public class NativeDynamoDbJsonHandler { requireIndexName(updateNode, "globalSecondaryIndexUpdates." + updatePosition + ".member.update"), gsiPt.isObject() ? parseThroughput(gsiPt) : null, - parseOnDemandThroughput(updateNode.path("OnDemandThroughput")))); + parseOnDemandThroughput(updateNode.path("OnDemandThroughput")), + parseWarmThroughput(updateNode.path("WarmThroughput")))); } } } @@ -2065,6 +2077,11 @@ public class NativeDynamoDbJsonHandler { "Cannot delete and update the same index: " + indexName, 400); } if (currentTable.findGsi(indexName).isEmpty()) { + if (gsiUpdate.warmThroughput() != null && gsiUpdate.provisionedThroughput() == null + && gsiUpdate.onDemandThroughput() == null) { + // AWS answers a warm-only update of a missing index with InternalFailure. + throw new AwsException("InternalFailure", null, 500); + } throw DynamoDbService.missingGsi(indexName, currentTable.getTableName()); } } @@ -2104,10 +2121,13 @@ public class NativeDynamoDbJsonHandler { TableDefinition table = tableService.updateTable(new UpdateTableRequest(tableName, throughput, newAttrDefs, gsiCreates, gsiDeletes, gsiThroughputUpdates, vectorCreates, vectorDeletes, - addRegions, removeRegions, updateRegions, parseTableSettings(request)), region); + addRegions, removeRegions, updateRegions, parseTableSettings(request), + parseWarmThroughput(request.path("WarmThroughput"))), region); + ObjectNode tableNode = tableToNode(table); + markWarmThroughputUpdating(tableNode, request); ObjectNode response = objectMapper.createObjectNode(); - response.set("TableDescription", tableToNode(table)); + response.set("TableDescription", tableNode); return Response.ok(response).build(); } @@ -4085,17 +4105,72 @@ public class NativeDynamoDbJsonHandler { return node; } + /** + * CreateTable describes a table or index's warm throughput only when the request gave one, and + * then only the members it gave, still UPDATING. + */ + private void reportRequestedWarmThroughput(ObjectNode described, JsonNode requested) { + described.remove("WarmThroughput"); + WarmThroughput warm = parseWarmThroughput(requested.path("WarmThroughput")); + if (warm == null || warm.isEmpty()) { + return; + } + ObjectNode reported = described.putObject("WarmThroughput"); + if (warm.readUnitsPerSecond() != null) { + reported.put("ReadUnitsPerSecond", warm.readUnitsPerSecond()); + } + if (warm.writeUnitsPerSecond() != null) { + reported.put("WriteUnitsPerSecond", warm.writeUnitsPerSecond()); + } + reported.put("Status", "UPDATING"); + } + + /** UpdateTable reports UPDATING only for the table and indexes whose request carried a WarmThroughput. */ + private static void markWarmThroughputUpdating(ObjectNode described, JsonNode request) { + if (request.path("WarmThroughput").isObject()) { + ((ObjectNode) described.get("WarmThroughput")).put("Status", "UPDATING"); + } + Set updatedIndexes = new HashSet<>(); + for (JsonNode indexUpdate : request.path("GlobalSecondaryIndexUpdates")) { + for (String action : List.of("Create", "Update")) { + JsonNode node = indexUpdate.path(action); + WarmThroughput warm = parseWarmThroughput(node.path("WarmThroughput")); + if (warm != null && !warm.isEmpty()) { + updatedIndexes.add(node.path("IndexName").asText()); + } + } + } + for (JsonNode gsiNode : described.path("GlobalSecondaryIndexes")) { + if (updatedIndexes.contains(gsiNode.path("IndexName").asText())) { + ((ObjectNode) gsiNode.get("WarmThroughput")).put("Status", "UPDATING"); + } + } + } + + private static WarmThroughput parseWarmThroughput(JsonNode warm) { + if (!warm.isObject()) { + return null; + } + return new WarmThroughput( + warm.hasNonNull("ReadUnitsPerSecond") ? warm.get("ReadUnitsPerSecond").asLong() : null, + warm.hasNonNull("WriteUnitsPerSecond") ? warm.get("WriteUnitsPerSecond").asLong() : null); + } + + private static void setWarmThroughput(GlobalSecondaryIndex gsi, WarmThroughput warm) { + if (warm != null) { + gsi.setWarmReadUnitsPerSecond(warm.readUnitsPerSecond()); + gsi.setWarmWriteUnitsPerSecond(warm.writeUnitsPerSecond()); + } + } + /** * AWS reports a provisioned index's warm throughput as its provisioned capacity, and an on-demand * one's as the values a new on-demand index starts with. An index is ACTIVE as soon as it exists here. */ private ObjectNode gsiWarmThroughput(TableDefinition table, GlobalSecondaryIndex gsi) { - boolean onDemand = "PAY_PER_REQUEST".equals(table.getBillingMode()); ObjectNode warmThroughput = objectMapper.createObjectNode(); - warmThroughput.put("ReadUnitsPerSecond", - onDemand ? ON_DEMAND_WARM_READ_UNITS : gsi.getProvisionedThroughput().getReadCapacityUnits()); - warmThroughput.put("WriteUnitsPerSecond", - onDemand ? ON_DEMAND_WARM_WRITE_UNITS : gsi.getProvisionedThroughput().getWriteCapacityUnits()); + warmThroughput.put("ReadUnitsPerSecond", table.gsiWarmReadUnits(gsi)); + warmThroughput.put("WriteUnitsPerSecond", table.gsiWarmWriteUnits(gsi)); warmThroughput.put("Status", "ACTIVE"); return warmThroughput; } diff --git a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableService.java b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableService.java index 21ae938546..6caba57b8d 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableService.java +++ b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableService.java @@ -40,6 +40,8 @@ public class NativeDynamoDbTableService { private static final String SSE_TYPE_KMS = "KMS"; // The order AWS prints the enum constraint in. static final List SSE_TYPES = List.of("AES256", "KMS"); + private static final String CURRENT_WARM_REASON = + "current WarmThroughput, decreasing WarmThroughput is not supported"; // A null field or throughput record means "not specified in the request". Collections and the // settings record must not be null. @@ -47,8 +49,15 @@ public class NativeDynamoDbTableService { record OnDemandThroughput(Integer maxReadRequestUnits, Integer maxWriteRequestUnits) {} + // Both members null is a request that sent WarmThroughput as an empty object. + record WarmThroughput(Long readUnitsPerSecond, Long writeUnitsPerSecond) { + boolean isEmpty() { + return readUnitsPerSecond == null && writeUnitsPerSecond == null; + } + } + record GsiThroughputUpdate(String indexName, Throughput provisionedThroughput, - OnDemandThroughput onDemandThroughput) {} + OnDemandThroughput onDemandThroughput, WarmThroughput warmThroughput) {} record TableSettings(String billingMode, Boolean deletionProtectionEnabled, String tableClass, OnDemandThroughput onDemandThroughput, @@ -60,7 +69,7 @@ public class NativeDynamoDbTableService { List globalSecondaryIndexes, List localSecondaryIndexes, List vectorIndexes, - Map tags, TableSettings settings) {} + Map tags, TableSettings settings, WarmThroughput warmThroughput) {} record UpdateTableRequest(String tableName, Throughput provisionedThroughput, List attributeDefinitions, @@ -68,7 +77,7 @@ public class NativeDynamoDbTableService { List gsiUpdates, List vectorCreates, List vectorDeletes, List replicaAdds, List replicaRemoves, List replicaUpdates, - TableSettings settings) {} + TableSettings settings, WarmThroughput warmThroughput) {} /** * What one Enable or Disable call applied. The values are the ones the call itself wrote, not a @@ -135,6 +144,8 @@ public class NativeDynamoDbTableService { + "disabled, UpdateViewType should not be specified", 400); } + requireCreateWarmThroughput(request, "PAY_PER_REQUEST".equals(billingMode)); + TableDefinition table = dynamoDbService.createTable(tableName, request.keySchema(), request.attributeDefinitions(), throughput != null ? throughput.readCapacityUnits() : null, @@ -155,6 +166,8 @@ public class NativeDynamoDbTableService { applyOnDemandThroughput(table, settings.onDemandThroughput()); + applyWarmThroughput(table, request.warmThroughput()); + dynamoDbService.putCreationTags(table, request.tags()); if (Boolean.TRUE.equals(settings.streamEnabled())) { @@ -221,7 +234,7 @@ public class NativeDynamoDbTableService { sseEnabled, sseType, kmsMasterKeyId); dynamoDbService.requireRestoreTarget(targetTableName, region); return createTable(new CreateTableRequest(targetTableName, new ArrayList<>(source.getKeySchema()), - new ArrayList<>(attributeDefinitions), throughput, gsis, lsis, vectorIndexes, Map.of(), settings), + new ArrayList<>(attributeDefinitions), throughput, gsis, lsis, vectorIndexes, Map.of(), settings, null), "CREATING", region); } @@ -432,6 +445,8 @@ public class NativeDynamoDbTableService { validateSseType(sseType); } + requireUpdateWarmThroughput(request, region); + Throughput throughput = request.provisionedThroughput(); TableDefinition table = dynamoDbService.updateTable(tableName, throughput != null ? throughput.readCapacityUnits() : null, @@ -451,6 +466,7 @@ public class NativeDynamoDbTableService { gsi.getProvisionedThroughput().setWriteCapacityUnits(gsiThroughput.writeCapacityUnits()); } } + applyWarmThroughput(gsi, update.warmThroughput()); OnDemandThroughput gsiOnDemand = update.onDemandThroughput(); if (gsiOnDemand != null) { if (gsiOnDemand.maxReadRequestUnits() != null) { @@ -473,6 +489,8 @@ public class NativeDynamoDbTableService { applyOnDemandThroughput(table, settings.onDemandThroughput()); + applyWarmThroughput(table, request.warmThroughput()); + if (settings.streamEnabled() != null) { if (settings.streamEnabled()) { enableStream(table, settings.streamViewType(), region); @@ -633,6 +651,114 @@ public class NativeDynamoDbTableService { table.setStreamViewType(viewType); } + private static void requireCreateWarmThroughput(CreateTableRequest request, boolean onDemand) { + Throughput provisioned = request.provisionedThroughput(); + WarmThroughput tableWarm = request.warmThroughput(); + if (tableWarm != null) { + requireCreateWarmThroughput("table", tableWarm.readUnitsPerSecond(), tableWarm.writeUnitsPerSecond(), + onDemand, provisioned != null ? provisioned.readCapacityUnits() : null, + provisioned != null ? provisioned.writeCapacityUnits() : null); + } + for (GlobalSecondaryIndex gsi : request.globalSecondaryIndexes()) { + requireCreateWarmThroughput("index " + gsi.getIndexName(), gsi.getWarmReadUnitsPerSecond(), + gsi.getWarmWriteUnitsPerSecond(), onDemand, gsi.getProvisionedThroughput().getReadCapacityUnits(), + gsi.getProvisionedThroughput().getWriteCapacityUnits()); + } + } + + private static void requireCreateWarmThroughput(String target, Long read, Long write, boolean onDemand, + Long readCapacity, Long writeCapacity) { + if (onDemand) { + String reason = "initial throughput for OnDemand. See: https://docs.aws.amazon.com/amazondynamodb/" + + "latest/developerguide/on-demand-capacity-mode.html#on-demand-capacity-mode-initial"; + requireWarmThroughputAtLeast(target, read, write, TableDefinition.defaultWarmReadUnits("PAY_PER_REQUEST", null), + TableDefinition.defaultWarmWriteUnits("PAY_PER_REQUEST", null), reason, reason); + } else if (readCapacity != null && writeCapacity != null) { + requireWarmThroughputAtLeast(target, read, write, readCapacity, writeCapacity, + "ReadCapacityUnits of ProvisionedThroughput", "WriteCapacityUnits of ProvisionedThroughput"); + } + } + + private void requireUpdateWarmThroughput(UpdateTableRequest request, String region) { + WarmThroughput tableWarm = request.warmThroughput(); + boolean indexWarm = request.gsiUpdates().stream().anyMatch(u -> u.warmThroughput() != null) + || request.gsiCreates().stream().anyMatch(g -> g.getWarmReadUnitsPerSecond() != null + || g.getWarmWriteUnitsPerSecond() != null); + if (tableWarm == null && !indexWarm) { + return; + } + TableDefinition table = dynamoDbService.describeTable(request.tableName(), region); + if (tableWarm != null) { + if (tableWarm.isEmpty()) { + // AWS answers an empty table WarmThroughput with InternalFailure. + throw new AwsException("InternalFailure", null, 500); + } + requireWarmThroughputAtLeast("table", tableWarm.readUnitsPerSecond(), tableWarm.writeUnitsPerSecond(), + table.getWarmReadUnitsPerSecond(), table.getWarmWriteUnitsPerSecond(), + CURRENT_WARM_REASON, CURRENT_WARM_REASON); + } + for (GsiThroughputUpdate update : request.gsiUpdates()) { + WarmThroughput warm = update.warmThroughput(); + if (warm == null) { + continue; + } + if (warm.isEmpty()) { + throw new AwsException("ValidationException", + "One or more parameter values were invalid: WarmThroughput must have at least one of " + + "ReadUnitsPerSecond or WriteUnitsPerSecond specified for index: " + update.indexName(), 400); + } + GlobalSecondaryIndex gsi = table.findGsi(update.indexName()).orElseThrow(); + requireWarmThroughputAtLeast("index " + update.indexName(), warm.readUnitsPerSecond(), + warm.writeUnitsPerSecond(), table.gsiWarmReadUnits(gsi), table.gsiWarmWriteUnits(gsi), + CURRENT_WARM_REASON, CURRENT_WARM_REASON); + } + boolean onDemand = "PAY_PER_REQUEST".equals(table.getBillingMode()); + for (GlobalSecondaryIndex gsi : request.gsiCreates()) { + requireCreateWarmThroughput("index " + gsi.getIndexName(), gsi.getWarmReadUnitsPerSecond(), + gsi.getWarmWriteUnitsPerSecond(), onDemand, gsi.getProvisionedThroughput().getReadCapacityUnits(), + gsi.getProvisionedThroughput().getWriteCapacityUnits()); + } + } + + private static void requireWarmThroughputAtLeast(String target, Long read, Long write, long minimumRead, + long minimumWrite, String readReason, String writeReason) { + if (read != null && read < minimumRead) { + throw lowWarmThroughput("ReadUnitsPerSecond", target, readReason); + } + if (write != null && write < minimumWrite) { + throw lowWarmThroughput("WriteUnitsPerSecond", target, writeReason); + } + } + + private static AwsException lowWarmThroughput(String member, String target, String reason) { + return new AwsException("ValidationException", "One or more parameter values were invalid: Requested " + + member + " for WarmThroughput for " + target + " is lower than " + reason, 400); + } + + private static void applyWarmThroughput(TableDefinition table, WarmThroughput warm) { + if (warm == null) { + return; + } + if (warm.readUnitsPerSecond() != null && table.getWarmReadUnitsPerSecond() < warm.readUnitsPerSecond()) { + table.setWarmReadUnitsPerSecond(warm.readUnitsPerSecond()); + } + if (warm.writeUnitsPerSecond() != null && table.getWarmWriteUnitsPerSecond() < warm.writeUnitsPerSecond()) { + table.setWarmWriteUnitsPerSecond(warm.writeUnitsPerSecond()); + } + } + + private static void applyWarmThroughput(GlobalSecondaryIndex gsi, WarmThroughput warm) { + if (warm == null) { + return; + } + if (warm.readUnitsPerSecond() != null) { + gsi.setWarmReadUnitsPerSecond(warm.readUnitsPerSecond()); + } + if (warm.writeUnitsPerSecond() != null) { + gsi.setWarmWriteUnitsPerSecond(warm.writeUnitsPerSecond()); + } + } + private static void applyOnDemandThroughput(TableDefinition table, OnDemandThroughput onDemand) { if (onDemand == null) { return; diff --git a/src/main/java/io/floci/aws/services/dynamodb/model/GlobalSecondaryIndex.java b/src/main/java/io/floci/aws/services/dynamodb/model/GlobalSecondaryIndex.java index d32fde1faf..7cba449fbb 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/model/GlobalSecondaryIndex.java +++ b/src/main/java/io/floci/aws/services/dynamodb/model/GlobalSecondaryIndex.java @@ -21,6 +21,9 @@ public class GlobalSecondaryIndex { private List nonKeyAttributes; private Integer onDemandMaxReadRequestUnits; private Integer onDemandMaxWriteRequestUnits; + // Null until a request sets the index's warm throughput. + private Long warmReadUnitsPerSecond; + private Long warmWriteUnitsPerSecond; // Null until the first UpdateContributorInsights call on this index. private ContributorInsights contributorInsights; @@ -74,6 +77,12 @@ public class GlobalSecondaryIndex { public Integer getOnDemandMaxWriteRequestUnits() { return onDemandMaxWriteRequestUnits; } public void setOnDemandMaxWriteRequestUnits(Integer v) { this.onDemandMaxWriteRequestUnits = v; } + public Long getWarmReadUnitsPerSecond() { return warmReadUnitsPerSecond; } + public void setWarmReadUnitsPerSecond(Long v) { this.warmReadUnitsPerSecond = v; } + + public Long getWarmWriteUnitsPerSecond() { return warmWriteUnitsPerSecond; } + public void setWarmWriteUnitsPerSecond(Long v) { this.warmWriteUnitsPerSecond = v; } + public ContributorInsights getContributorInsights() { return contributorInsights; } public void setContributorInsights(ContributorInsights contributorInsights) { this.contributorInsights = contributorInsights; diff --git a/src/main/java/io/floci/aws/services/dynamodb/model/TableDefinition.java b/src/main/java/io/floci/aws/services/dynamodb/model/TableDefinition.java index 3f3f904214..310a3b7151 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/model/TableDefinition.java +++ b/src/main/java/io/floci/aws/services/dynamodb/model/TableDefinition.java @@ -126,6 +126,22 @@ public class TableDefinition { return wcu > 0 ? wcu : 5; } + /** The warm read units an index reports: its baseline, or a higher value the index was given. */ + public long gsiWarmReadUnits(GlobalSecondaryIndex gsi) { + long baseline = "PAY_PER_REQUEST".equals(billingMode) + ? defaultWarmReadUnits(billingMode, null) : gsi.getProvisionedThroughput().getReadCapacityUnits(); + Long stored = gsi.getWarmReadUnitsPerSecond(); + return stored != null && stored > baseline ? stored : baseline; + } + + /** The warm write units an index reports: its baseline, or a higher value the index was given. */ + public long gsiWarmWriteUnits(GlobalSecondaryIndex gsi) { + long baseline = "PAY_PER_REQUEST".equals(billingMode) + ? defaultWarmWriteUnits(billingMode, null) : gsi.getProvisionedThroughput().getWriteCapacityUnits(); + Long stored = gsi.getWarmWriteUnitsPerSecond(); + return stored != null && stored > baseline ? stored : baseline; + } + public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } diff --git a/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandlerTest.java b/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandlerTest.java index e417973b16..9ad386744d 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandlerTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandlerTest.java @@ -869,6 +869,340 @@ class NativeDynamoDbJsonHandlerTest { assertEquals("ACTIVE", describedWarmThroughput.get("Status").asText()); } + private static final String ON_DEMAND_REASON = "initial throughput for OnDemand. See: https://docs.aws.amazon.com/" + + "amazondynamodb/latest/developerguide/on-demand-capacity-mode.html#on-demand-capacity-mode-initial"; + private static final String CURRENT_REASON = "current WarmThroughput, decreasing WarmThroughput is not supported"; + + private JsonNode warmTableRequest(String name, boolean onDemand, String tableWarm, String indexWarm) { + String capacity = onDemand ? "\"BillingMode\": \"PAY_PER_REQUEST\"," + : "\"ProvisionedThroughput\": {\"ReadCapacityUnits\": 5, \"WriteCapacityUnits\": 6},"; + String indexCapacity = onDemand ? "" + : "\"ProvisionedThroughput\": {\"ReadCapacityUnits\": 7, \"WriteCapacityUnits\": 8},"; + return json(""" + { + "TableName": "%s", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "g", "AttributeType": "S"} + ], + %s + %s + "GlobalSecondaryIndexes": [{ + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + %s + %s + "Projection": {"ProjectionType": "ALL"} + }] + } + """.formatted(name, capacity, + tableWarm == null ? "" : "\"WarmThroughput\": " + tableWarm + ",", + indexCapacity, indexWarm == null ? "" : "\"WarmThroughput\": " + indexWarm + ",")); + } + + private JsonNode createWarmTable(String name, boolean onDemand, String tableWarm, String indexWarm) + throws Exception { + Response response = handler.handle("CreateTable", warmTableRequest(name, onDemand, tableWarm, indexWarm), + "eu-west-1"); + assertEquals(200, response.getStatus()); + return mapper.convertValue(response.getEntity(), JsonNode.class).get("TableDescription"); + } + + private AwsException warmFailure(String operation, JsonNode request) { + return assertThrows(AwsException.class, () -> handler.handle(operation, request, "eu-west-1")); + } + + private JsonNode updateWarm(String body) throws Exception { + Response response = handler.handle("UpdateTable", json(body), "eu-west-1"); + assertEquals(200, response.getStatus()); + return mapper.convertValue(response.getEntity(), JsonNode.class).get("TableDescription"); + } + + private static void assertWarm(JsonNode warm, long read, long write, String status) { + assertEquals(read, warm.get("ReadUnitsPerSecond").asLong()); + assertEquals(write, warm.get("WriteUnitsPerSecond").asLong()); + assertEquals(status, warm.get("Status").asText()); + } + + @Test + void createTableEchoesRequestedWarmThroughputAsUpdating() throws Exception { + JsonNode description = createWarmTable("warm-create-echo", true, + "{\"ReadUnitsPerSecond\": 15000, \"WriteUnitsPerSecond\": 5000}", + "{\"ReadUnitsPerSecond\": 13000}"); + + assertWarm(description.get("WarmThroughput"), 15000, 5000, "UPDATING"); + JsonNode indexWarm = description.get("GlobalSecondaryIndexes").get(0).get("WarmThroughput"); + assertEquals(2, indexWarm.size()); + assertEquals(13000, indexWarm.get("ReadUnitsPerSecond").asLong()); + assertFalse(indexWarm.has("WriteUnitsPerSecond")); + assertEquals("UPDATING", indexWarm.get("Status").asText()); + assertWarm(warmThroughputOf(describedTable("warm-create-echo")), 15000, 5000, "ACTIVE"); + assertWarm(warmThroughputOf(describedGsi("warm-create-echo", "gsi1")), 13000, 4000, "ACTIVE"); + } + + @Test + void createTableWithOneWarmMemberKeepsTheOtherAtItsBaseline() throws Exception { + JsonNode description = createWarmTable("warm-create-one", true, "{\"ReadUnitsPerSecond\": 12000}", null); + + JsonNode warm = description.get("WarmThroughput"); + assertEquals(2, warm.size()); + assertEquals("UPDATING", warm.get("Status").asText()); + assertWarm(warmThroughputOf(describedTable("warm-create-one")), 12000, 4000, "ACTIVE"); + } + + @Test + void createTableWithoutWarmThroughputOmitsTableAndIndexWarmThroughput() throws Exception { + JsonNode description = createWarmTable("warm-create-none", false, null, null); + + assertFalse(description.has("WarmThroughput")); + assertFalse(description.get("GlobalSecondaryIndexes").get(0).has("WarmThroughput")); + } + + @Test + void createTableIgnoresEmptyWarmThroughput() throws Exception { + JsonNode description = createWarmTable("warm-create-empty", false, "{}", "{}"); + + assertFalse(description.has("WarmThroughput")); + assertFalse(description.get("GlobalSecondaryIndexes").get(0).has("WarmThroughput")); + assertWarm(warmThroughputOf(describedTable("warm-create-empty")), 5, 6, "ACTIVE"); + } + + @Test + void createTableRejectsWarmThroughputBelowOnDemandInitialThroughput() { + AwsException readEx = warmFailure("CreateTable", warmTableRequest("warm-low-od", true, + "{\"ReadUnitsPerSecond\": 11999, \"WriteUnitsPerSecond\": 1}", null)); + assertEquals("ValidationException", readEx.getErrorCode()); + assertEquals(400, readEx.getHttpStatus()); + assertEquals("One or more parameter values were invalid: Requested ReadUnitsPerSecond for WarmThroughput " + + "for table is lower than " + ON_DEMAND_REASON, readEx.getMessage()); + + AwsException writeEx = warmFailure("CreateTable", warmTableRequest("warm-low-od", true, + "{\"WriteUnitsPerSecond\": 0}", null)); + assertEquals("One or more parameter values were invalid: Requested WriteUnitsPerSecond for WarmThroughput " + + "for table is lower than " + ON_DEMAND_REASON, writeEx.getMessage()); + assertThrows(AwsException.class, () -> describedTable("warm-low-od")); + } + + @Test + void createTableRejectsIndexWarmThroughputBelowOnDemandInitialThroughput() { + AwsException ex = warmFailure("CreateTable", warmTableRequest("warm-low-od-index", true, null, + "{\"WriteUnitsPerSecond\": 3999}")); + + assertEquals("One or more parameter values were invalid: Requested WriteUnitsPerSecond for WarmThroughput " + + "for index gsi1 is lower than " + ON_DEMAND_REASON, ex.getMessage()); + assertThrows(AwsException.class, () -> describedTable("warm-low-od-index")); + } + + @Test + void createTableRejectsWarmThroughputBelowProvisionedCapacity() { + AwsException readEx = warmFailure("CreateTable", warmTableRequest("warm-low-prov", false, + "{\"ReadUnitsPerSecond\": 4, \"WriteUnitsPerSecond\": 1}", null)); + assertEquals("One or more parameter values were invalid: Requested ReadUnitsPerSecond for WarmThroughput " + + "for table is lower than ReadCapacityUnits of ProvisionedThroughput", readEx.getMessage()); + + AwsException writeEx = warmFailure("CreateTable", warmTableRequest("warm-low-prov", false, + "{\"ReadUnitsPerSecond\": 5, \"WriteUnitsPerSecond\": 5}", null)); + assertEquals("One or more parameter values were invalid: Requested WriteUnitsPerSecond for WarmThroughput " + + "for table is lower than WriteCapacityUnits of ProvisionedThroughput", writeEx.getMessage()); + + AwsException indexEx = warmFailure("CreateTable", warmTableRequest("warm-low-prov", false, null, + "{\"ReadUnitsPerSecond\": 6}")); + assertEquals("One or more parameter values were invalid: Requested ReadUnitsPerSecond for WarmThroughput " + + "for index gsi1 is lower than ReadCapacityUnits of ProvisionedThroughput", indexEx.getMessage()); + assertThrows(AwsException.class, () -> describedTable("warm-low-prov")); + } + + @Test + void createTableChecksTheTableBeforeItsIndexes() { + AwsException ex = warmFailure("CreateTable", warmTableRequest("warm-order-create", true, + "{\"WriteUnitsPerSecond\": 1}", "{\"ReadUnitsPerSecond\": 1}")); + + assertTrue(ex.getMessage().contains("WriteUnitsPerSecond for WarmThroughput for table")); + } + + @Test + void updateTableRaisesTableWarmThroughputOnOnDemandAndProvisionedTables() throws Exception { + createWarmTable("warm-raise-od", true, null, null); + createWarmTable("warm-raise-prov", false, null, null); + + JsonNode onDemand = updateWarm(""" + {"TableName": "warm-raise-od", "WarmThroughput": {"ReadUnitsPerSecond": 20000}} + """); + JsonNode provisioned = updateWarm(""" + {"TableName": "warm-raise-prov", "WarmThroughput": {"WriteUnitsPerSecond": 50}} + """); + + assertWarm(onDemand.get("WarmThroughput"), 20000, 4000, "UPDATING"); + assertWarm(provisioned.get("WarmThroughput"), 5, 50, "UPDATING"); + assertWarm(warmThroughputOf(describedTable("warm-raise-od")), 20000, 4000, "ACTIVE"); + assertWarm(warmThroughputOf(describedTable("warm-raise-prov")), 5, 50, "ACTIVE"); + } + + @Test + void updateTableMarksOnlyRequestedTargetsAsUpdating() throws Exception { + createWarmTable("warm-flags", true, null, null); + + JsonNode indexOnly = updateWarm(""" + {"TableName": "warm-flags", "GlobalSecondaryIndexUpdates": [ + {"Update": {"IndexName": "gsi1", "WarmThroughput": {"ReadUnitsPerSecond": 13000}}}]} + """); + + assertWarm(indexOnly.get("WarmThroughput"), 12000, 4000, "ACTIVE"); + assertWarm(indexOnly.get("GlobalSecondaryIndexes").get(0).get("WarmThroughput"), 13000, 4000, "UPDATING"); + assertWarm(warmThroughputOf(describedGsi("warm-flags", "gsi1")), 13000, 4000, "ACTIVE"); + + JsonNode tableOnly = updateWarm(""" + {"TableName": "warm-flags", "WarmThroughput": {"WriteUnitsPerSecond": 4001}} + """); + + assertWarm(tableOnly.get("WarmThroughput"), 12000, 4001, "UPDATING"); + assertWarm(tableOnly.get("GlobalSecondaryIndexes").get(0).get("WarmThroughput"), 13000, 4000, "ACTIVE"); + } + + @Test + void updateTableAcceptsWarmThroughputEqualToTheCurrentValue() throws Exception { + createWarmTable("warm-equal", true, null, null); + + JsonNode description = updateWarm(""" + {"TableName": "warm-equal", "WarmThroughput": {"ReadUnitsPerSecond": 12000, "WriteUnitsPerSecond": 4000}} + """); + + assertWarm(description.get("WarmThroughput"), 12000, 4000, "UPDATING"); + } + + @Test + void updateTableRejectsLoweringTableWarmThroughput() throws Exception { + createWarmTable("warm-lower", true, "{\"ReadUnitsPerSecond\": 15000, \"WriteUnitsPerSecond\": 6000}", null); + + AwsException readEx = warmFailure("UpdateTable", json(""" + {"TableName": "warm-lower", "WarmThroughput": {"ReadUnitsPerSecond": 14999}} + """)); + assertEquals("ValidationException", readEx.getErrorCode()); + assertEquals("One or more parameter values were invalid: Requested ReadUnitsPerSecond for WarmThroughput " + + "for table is lower than " + CURRENT_REASON, readEx.getMessage()); + + AwsException writeEx = warmFailure("UpdateTable", json(""" + {"TableName": "warm-lower", "WarmThroughput": {"WriteUnitsPerSecond": 5999}} + """)); + assertEquals("One or more parameter values were invalid: Requested WriteUnitsPerSecond for WarmThroughput " + + "for table is lower than " + CURRENT_REASON, writeEx.getMessage()); + assertWarm(warmThroughputOf(describedTable("warm-lower")), 15000, 6000, "ACTIVE"); + } + + @Test + void updateTableRejectsLoweringIndexWarmThroughputAndChecksTableFirst() throws Exception { + createWarmTable("warm-lower-index", true, null, "{\"ReadUnitsPerSecond\": 14000}"); + + AwsException indexEx = warmFailure("UpdateTable", json(""" + {"TableName": "warm-lower-index", "GlobalSecondaryIndexUpdates": [ + {"Update": {"IndexName": "gsi1", "WarmThroughput": {"ReadUnitsPerSecond": 13999}}}]} + """)); + assertEquals("One or more parameter values were invalid: Requested ReadUnitsPerSecond for WarmThroughput " + + "for index gsi1 is lower than " + CURRENT_REASON, indexEx.getMessage()); + + AwsException orderEx = warmFailure("UpdateTable", json(""" + {"TableName": "warm-lower-index", "WarmThroughput": {"ReadUnitsPerSecond": 1}, + "GlobalSecondaryIndexUpdates": [ + {"Update": {"IndexName": "gsi1", "WarmThroughput": {"ReadUnitsPerSecond": 1}}}]} + """)); + assertTrue(orderEx.getMessage().contains("for table")); + } + + @Test + void updateTableRejectsEmptyTableWarmThroughputWithInternalFailure() throws Exception { + createWarmTable("warm-empty-table", true, null, null); + + AwsException ex = warmFailure("UpdateTable", json(""" + {"TableName": "warm-empty-table", "WarmThroughput": {}} + """)); + + assertEquals("InternalFailure", ex.getErrorCode()); + assertEquals(500, ex.getHttpStatus()); + } + + @Test + void updateTableReportsAMissingTableBeforeAnyWarmThroughputCheck() { + AwsException ex = warmFailure("UpdateTable", json(""" + {"TableName": "warm-no-such-table", "WarmThroughput": {}} + """)); + + assertEquals("ResourceNotFoundException", ex.getErrorCode()); + } + + @Test + void updateTableRejectsEmptyIndexWarmThroughput() throws Exception { + createWarmTable("warm-empty-index", true, null, null); + + AwsException ex = warmFailure("UpdateTable", json(""" + {"TableName": "warm-empty-index", "GlobalSecondaryIndexUpdates": [ + {"Update": {"IndexName": "gsi1", "WarmThroughput": {}}}]} + """)); + + assertEquals("ValidationException", ex.getErrorCode()); + assertEquals("One or more parameter values were invalid: WarmThroughput must have at least one of " + + "ReadUnitsPerSecond or WriteUnitsPerSecond specified for index: gsi1", ex.getMessage()); + } + + @Test + void updateTableRejectsWarmOnlyUpdateOfAMissingIndexWithInternalFailure() throws Exception { + createWarmTable("warm-missing-index", true, null, null); + + AwsException ex = warmFailure("UpdateTable", json(""" + {"TableName": "warm-missing-index", "GlobalSecondaryIndexUpdates": [ + {"Update": {"IndexName": "nope", "WarmThroughput": {"ReadUnitsPerSecond": 13000}}}]} + """)); + assertEquals("InternalFailure", ex.getErrorCode()); + assertEquals(500, ex.getHttpStatus()); + + AwsException other = warmFailure("UpdateTable", json(""" + {"TableName": "warm-missing-index", "GlobalSecondaryIndexUpdates": [ + {"Update": {"IndexName": "nope", "OnDemandThroughput": {"MaxReadRequestUnits": 10}}}]} + """)); + assertEquals("ResourceNotFoundException", other.getErrorCode()); + } + + @Test + void updateTableCreatedIndexFollowsTheCreateTableWarmThroughputRules() throws Exception { + createWarmTable("warm-index-create", true, null, null); + String create = """ + {"TableName": "warm-index-create", + "AttributeDefinitions": [{"AttributeName": "h", "AttributeType": "S"}], + "GlobalSecondaryIndexUpdates": [{"Create": { + "IndexName": "gsi2", + "KeySchema": [{"AttributeName": "h", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"}, + "WarmThroughput": %s}}]} + """; + + AwsException ex = warmFailure("UpdateTable", json(create.formatted("{\"ReadUnitsPerSecond\": 100}"))); + assertEquals("One or more parameter values were invalid: Requested ReadUnitsPerSecond for WarmThroughput " + + "for index gsi2 is lower than " + ON_DEMAND_REASON, ex.getMessage()); + + JsonNode description = updateWarm(create.formatted("{\"ReadUnitsPerSecond\": 12500}")); + JsonNode created = description.get("GlobalSecondaryIndexes").get(1).get("WarmThroughput"); + assertWarm(created, 12500, 4000, "UPDATING"); + assertWarm(description.get("GlobalSecondaryIndexes").get(0).get("WarmThroughput"), 12000, 4000, "ACTIVE"); + assertWarm(warmThroughputOf(describedGsi("warm-index-create", "gsi2")), 12500, 4000, "ACTIVE"); + } + + @Test + void updateTableIgnoresEmptyWarmThroughputOnACreatedIndex() throws Exception { + createWarmTable("warm-index-create-empty", true, null, null); + + JsonNode description = updateWarm(""" + {"TableName": "warm-index-create-empty", + "AttributeDefinitions": [{"AttributeName": "h", "AttributeType": "S"}], + "GlobalSecondaryIndexUpdates": [{"Create": { + "IndexName": "gsi2", + "KeySchema": [{"AttributeName": "h", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"}, + "WarmThroughput": {}}}]} + """); + + assertWarm(description.get("GlobalSecondaryIndexes").get(1).get("WarmThroughput"), 12000, 4000, "ACTIVE"); + } + private JsonNode describedTable(String tableName) throws Exception { Response response = handler.handle("DescribeTable", mapper.createObjectNode().put("TableName", tableName), "eu-west-1"); diff --git a/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableServiceTest.java b/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableServiceTest.java index 2dc120bd47..660e9219e5 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableServiceTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableServiceTest.java @@ -106,7 +106,7 @@ class NativeDynamoDbTableServiceTest { return new CreateTableRequest(TABLE, new ArrayList<>(List.of(new KeySchemaElement("id", "HASH"))), new ArrayList<>(List.of(new AttributeDefinition("id", "S"))), - throughput, List.of(), List.of(), List.of(), Map.of(), settings); + throughput, List.of(), List.of(), List.of(), Map.of(), settings, null); } private static CreateTableRequest createRequestWithGsi(TableSettings settings) { @@ -117,13 +117,13 @@ class NativeDynamoDbTableServiceTest { return new CreateTableRequest(TABLE, new ArrayList<>(List.of(new KeySchemaElement("id", "HASH"))), new ArrayList<>(List.of(new AttributeDefinition("id", "S"), new AttributeDefinition("category", "S"))), - new Throughput(5L, 5L), new ArrayList<>(List.of(gsi)), List.of(), List.of(), Map.of(), settings); + new Throughput(5L, 5L), new ArrayList<>(List.of(gsi)), List.of(), List.of(), Map.of(), settings, null); } private static UpdateTableRequest updateRequest(List gsiUpdates, List replicaUpdates, TableSettings settings) { return new UpdateTableRequest(TABLE, null, List.of(), List.of(), List.of(), gsiUpdates, - List.of(), List.of(), List.of(), List.of(), replicaUpdates, settings); + List.of(), List.of(), List.of(), List.of(), replicaUpdates, settings, null); } private void assertValidationFailure(Executable call, String message) { @@ -190,7 +190,7 @@ class NativeDynamoDbTableServiceTest { CreateTableRequest request = new CreateTableRequest(TABLE, new ArrayList<>(List.of(new KeySchemaElement("id", "HASH"))), new ArrayList<>(List.of(new AttributeDefinition("id", "S"))), - null, List.of(), List.of(), List.of(), tags, settings); + null, List.of(), List.of(), List.of(), tags, settings, null); TableDefinition created = tableService.createTable(request, "ACTIVE", REGION); @@ -253,7 +253,7 @@ class NativeDynamoDbTableServiceTest { TableSettings update = new TableSettings("PAY_PER_REQUEST", true, "STANDARD_INFREQUENT_ACCESS", new OnDemandThroughput(100, 200), true, "NEW_IMAGE", false, null, null); List gsiUpdates = List.of( - new GsiThroughputUpdate(GSI, new Throughput(7L, null), new OnDemandThroughput(30, null))); + new GsiThroughputUpdate(GSI, new Throughput(7L, null), new OnDemandThroughput(30, null), null)); tableService.updateTable(updateRequest(gsiUpdates, List.of(), update), REGION);