diff --git a/docs/services/dynamodb.md b/docs/services/dynamodb.md index 8206ace71b..00131b938c 100644 --- a/docs/services/dynamodb.md +++ b/docs/services/dynamodb.md @@ -26,7 +26,7 @@ including batch, transaction and PartiQL table extraction. | `DeleteTable` | Delete a table | | `DescribeTable` | Get table metadata | | `ListTables` | List all tables | -| `DescribeLimits` | Get the default account and table capacity quotas | +| `DescribeLimits` | Get the default account and table capacity quotas, which `CreateTable` and `UpdateTable` enforce | | `DescribeEndpoints` | Get Floci's own host and port as the endpoint | | `UpdateTable` | Update throughput, indexes, streams | | `PutItem` | Write an item | diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbCapacityQuotas.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbCapacityQuotas.java new file mode 100644 index 0000000000..df0a739616 --- /dev/null +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbCapacityQuotas.java @@ -0,0 +1,159 @@ +package io.floci.aws.services.dynamodb; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.dynamodb.NativeDynamoDbTableService.GsiThroughputUpdate; +import io.floci.aws.services.dynamodb.NativeDynamoDbTableService.Throughput; +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 java.util.List; + +/** + * The provisioned capacity quotas DescribeLimits reports, which CreateTable and UpdateTable + * enforce. On-demand tables are outside them. + */ +final class DynamoDbCapacityQuotas { + + // The default account quotas, the same in every Region measured. + static final long ACCOUNT_MAX_CAPACITY_UNITS = 80_000; + static final long TABLE_MAX_CAPACITY_UNITS = 40_000; + + private static final String READ = "ReadCapacityUnits"; + private static final String WRITE = "WriteCapacityUnits"; + private static final String SEE_GUIDE = + " Refer to the Amazon DynamoDB Developer Guide for current limits and how to request higher limits."; + + private DynamoDbCapacityQuotas() { + } + + /** Capacity units summed over a table and its global secondary indexes. */ + record Capacity(long read, long write) { + + static final Capacity NONE = new Capacity(0, 0); + + static Capacity of(TableDefinition table) { + if ("PAY_PER_REQUEST".equals(table.getBillingMode())) { + return NONE; + } + ProvisionedThroughput throughput = table.getProvisionedThroughput(); + Capacity total = new Capacity(throughput.getReadCapacityUnits(), throughput.getWriteCapacityUnits()); + for (GlobalSecondaryIndex gsi : table.getGlobalSecondaryIndexes()) { + total = total.plus(of(gsi.getProvisionedThroughput())); + } + return total; + } + + private static Capacity of(ProvisionedThroughput throughput) { + return new Capacity(throughput.getReadCapacityUnits(), throughput.getWriteCapacityUnits()); + } + + Capacity plus(Capacity other) { + return new Capacity(read + other.read, write + other.write); + } + } + + /** + * Checks a provisioned table before CreateTable stores it. + * + * @param reserved what the account's other tables in the Region hold + */ + static void requireNewTableWithinQuotas(TableDefinition table, Capacity reserved, String region) { + Capacity requested = Capacity.of(table); + requireWithinAccountQuota(READ, reserved.read(), null, requested.read(), region); + requireWithinAccountQuota(WRITE, reserved.write(), null, requested.write(), region); + ProvisionedThroughput throughput = table.getProvisionedThroughput(); + requireWithinTableQuota(throughput.getReadCapacityUnits(), throughput.getWriteCapacityUnits(), region); + for (GlobalSecondaryIndex gsi : table.getGlobalSecondaryIndexes()) { + requireWithinIndexQuota(gsi.getIndexName(), gsi.getProvisionedThroughput(), region); + } + } + + /** + * Checks the indexes an UpdateTable creates and the table's new total against the account + * quota. The total is checked only when it grows. + * + * @param reserved what the account's tables in the Region hold, this table included + */ + static void requireUpdateWithinQuotas(TableDefinition table, Long read, Long write, + List creates, List deletes, + List updates, Capacity reserved, String region) { + Capacity current = Capacity.of(table); + ProvisionedThroughput tableThroughput = table.getProvisionedThroughput(); + Capacity requested = new Capacity(read != null ? read : tableThroughput.getReadCapacityUnits(), + write != null ? write : tableThroughput.getWriteCapacityUnits()); + for (GlobalSecondaryIndex gsi : table.getGlobalSecondaryIndexes()) { + if (!deletes.contains(gsi.getIndexName())) { + requested = requested.plus(updated(gsi, updates)); + } + } + for (GlobalSecondaryIndex gsi : creates) { + requested = requested.plus(Capacity.of(gsi.getProvisionedThroughput())); + } + if (requested.read() > current.read()) { + requireWithinAccountQuota(READ, reserved.read(), current.read(), requested.read(), region); + } + if (requested.write() > current.write()) { + requireWithinAccountQuota(WRITE, reserved.write(), current.write(), requested.write(), region); + } + for (GlobalSecondaryIndex gsi : creates) { + requireWithinIndexQuota(gsi.getIndexName(), gsi.getProvisionedThroughput(), region); + } + } + + private static Capacity updated(GlobalSecondaryIndex gsi, List updates) { + ProvisionedThroughput throughput = gsi.getProvisionedThroughput(); + long read = throughput.getReadCapacityUnits(); + long write = throughput.getWriteCapacityUnits(); + for (GsiThroughputUpdate update : updates) { + Throughput requested = update.provisionedThroughput(); + if (requested != null && gsi.getIndexName().equals(update.indexName())) { + read = requested.readCapacityUnits() != null ? requested.readCapacityUnits() : read; + write = requested.writeCapacityUnits() != null ? requested.writeCapacityUnits() : write; + } + } + return new Capacity(read, write); + } + + static void requireWithinTableQuota(Long read, Long write, String region) { + requireWithinPerTableMaximum(READ, "table", read, region); + requireWithinPerTableMaximum(WRITE, "table", write, region); + } + + static void requireWithinIndexQuota(String indexName, Long read, Long write, String region) { + requireWithinPerTableMaximum(READ + " for index " + indexName, "index", read, region); + requireWithinPerTableMaximum(WRITE + " for index " + indexName, "index", write, region); + } + + private static void requireWithinIndexQuota(String indexName, ProvisionedThroughput throughput, String region) { + requireWithinIndexQuota(indexName, throughput.getReadCapacityUnits(), throughput.getWriteCapacityUnits(), + region); + } + + // The message names the per table maximum for an index too. + private static void requireWithinPerTableMaximum(String requested, String scope, Long units, String region) { + if (units != null && units > TABLE_MAX_CAPACITY_UNITS) { + throw new AwsException("LimitExceededException", + "The requested " + requested + ", " + units + ", is above the per " + scope + + " maximum for the account in " + region + ". Per table maximum: " + + TABLE_MAX_CAPACITY_UNITS + "." + SEE_GUIDE, 400); + } + } + + /** @param current the table's own total on UpdateTable, null on CreateTable */ + private static void requireWithinAccountQuota(String unit, long reserved, Long current, long requested, + String region) { + long others = current != null ? reserved - current : reserved; + if (others + requested <= ACCOUNT_MAX_CAPACITY_UNITS) { + return; + } + String currentForTable = current != null + ? " Current " + unit + " provisioned for the table and indexes: " + current + "." + : ""; + throw new AwsException("LimitExceededException", + "This request would have caused the " + unit + " limit to be exceeded for the account in " + + region + ". Current " + unit + " reserved by the account: " + reserved + ". Limit: " + + ACCOUNT_MAX_CAPACITY_UNITS + "." + currentForTable + " Requested: " + requested + "." + + SEE_GUIDE, 400); + } +} diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java index 349f16dbeb..c333a3a59f 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java @@ -24,6 +24,8 @@ import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.dynamodb.DynamoDbCapacityQuotas.Capacity; +import io.floci.aws.services.dynamodb.NativeDynamoDbTableService.GsiThroughputUpdate; import io.floci.aws.services.dynamodb.model.AttributeDefinition; import io.floci.aws.services.dynamodb.model.ConditionalCheckFailedException; import io.floci.aws.services.dynamodb.model.ContributorInsights; @@ -131,6 +133,8 @@ public class DynamoDbService { // relies on ReentrantLock's re-entrancy so the inner put/update/delete calls do // not deadlock after the outer transaction already took each participant's lock. private final ConcurrentHashMap> itemLocks = new ConcurrentHashMap<>(); + // Held from an account quota check until the capacity it allowed is stored. + private final Object capacityLock = new Object(); // ClientRequestToken idempotency for TransactWriteItems. AWS retains tokens for // ~10 minutes; floci uses the same window. The cache entry stores a hash of the // request body so a replay with the same token but different parameters can be @@ -685,7 +689,12 @@ public class DynamoDbService { table.setVectorIndexes(created); } - tableStore.put(storageKey, table); + synchronized (capacityLock) { + if (!"PAY_PER_REQUEST".equals(billingMode)) { + DynamoDbCapacityQuotas.requireNewTableWithinQuotas(table, reservedCapacity(region), region); + } + tableStore.put(storageKey, table); + } itemsByTable.put(scopedItemsKey(storageKey), new ConcurrentSkipListMap<>()); LOG.infov("Created table: {0} in region {1}", tableName, region); return table; @@ -1041,6 +1050,19 @@ public class DynamoDbService { } } + Object capacityLock() { + return capacityLock; + } + + private Capacity reservedCapacity(String region) { + String prefix = region + "::"; + Capacity reserved = Capacity.NONE; + for (TableDefinition table : tableStore.scan(k -> k.startsWith(prefix))) { + reserved = reserved.plus(Capacity.of(table)); + } + return reserved; + } + public List listTables(String region) { String prefix = region + "::"; return tableStore.scan(k -> k.startsWith(prefix)).stream() @@ -2506,6 +2528,17 @@ public class DynamoDbService { List newAttrDefs, List vectorCreates, List vectorDeletes, String billingMode, String region) { + return updateTable(tableName, readCapacity, writeCapacity, gsiCreates, gsiDeletes, List.of(), + newAttrDefs, vectorCreates, vectorDeletes, billingMode, region); + } + + /** @param gsiUpdates the index throughput changes, which the caller applies after this returns */ + public TableDefinition updateTable(String tableName, Long readCapacity, Long writeCapacity, + List gsiCreates, List gsiDeletes, + List gsiUpdates, + List newAttrDefs, + List vectorCreates, List vectorDeletes, + String billingMode, String region) { String canonicalTableName = canonicalTableName(region, tableName); String storageKey = regionKey(region, canonicalTableName); TableDefinition table = tableStore.get(storageKey) @@ -2521,6 +2554,7 @@ public class DynamoDbService { throw new AwsException("ValidationException", "The parameter 'ProvisionedThroughput.WriteCapacityUnits' must be greater than 0", 400); } + DynamoDbCapacityQuotas.requireWithinTableQuota(readCapacity, writeCapacity, region); if (readCapacity != null && writeCapacity != null && "PROVISIONED".equals(table.getBillingMode()) && readCapacity.equals(table.getProvisionedThroughput().getReadCapacityUnits()) @@ -2566,9 +2600,13 @@ public class DynamoDbService { if (newAttrDefs != null) { knownAttrDefs.addAll(newAttrDefs); } + String newBillingMode = billingMode != null ? billingMode : table.getBillingMode(); validateVectorIndexUpdates(table, vectorIndexCreates, vectorIndexDeletes, - gsiCreates.size() + gsiDeletes.size(), knownAttrDefs, - billingMode != null ? billingMode : table.getBillingMode()); + gsiCreates.size() + gsiDeletes.size(), knownAttrDefs, newBillingMode); + if (!"PAY_PER_REQUEST".equals(newBillingMode)) { + DynamoDbCapacityQuotas.requireUpdateWithinQuotas(table, readCapacity, writeCapacity, gsiCreates, + gsiDeletes, gsiUpdates, reservedCapacity(region), region); + } if (readCapacity != null) { table.getProvisionedThroughput().setReadCapacityUnits(readCapacity); 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 89302fcf0d..a1bf4c1d34 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java +++ b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java @@ -172,17 +172,14 @@ public class NativeDynamoDbJsonHandler { }; } - // The default account quotas, the same in every Region measured. - private static final long ACCOUNT_MAX_CAPACITY_UNITS = 80_000; - private static final long TABLE_MAX_CAPACITY_UNITS = 40_000; private static final int ENDPOINT_CACHE_PERIOD_IN_MINUTES = 1440; private Response handleDescribeLimits() { ObjectNode response = objectMapper.createObjectNode(); - response.put("AccountMaxReadCapacityUnits", ACCOUNT_MAX_CAPACITY_UNITS); - response.put("AccountMaxWriteCapacityUnits", ACCOUNT_MAX_CAPACITY_UNITS); - response.put("TableMaxReadCapacityUnits", TABLE_MAX_CAPACITY_UNITS); - response.put("TableMaxWriteCapacityUnits", TABLE_MAX_CAPACITY_UNITS); + response.put("AccountMaxReadCapacityUnits", DynamoDbCapacityQuotas.ACCOUNT_MAX_CAPACITY_UNITS); + response.put("AccountMaxWriteCapacityUnits", DynamoDbCapacityQuotas.ACCOUNT_MAX_CAPACITY_UNITS); + response.put("TableMaxReadCapacityUnits", DynamoDbCapacityQuotas.TABLE_MAX_CAPACITY_UNITS); + response.put("TableMaxWriteCapacityUnits", DynamoDbCapacityQuotas.TABLE_MAX_CAPACITY_UNITS); return Response.ok(response).build(); } @@ -2053,6 +2050,17 @@ public class NativeDynamoDbJsonHandler { if (!gsiThroughputUpdates.isEmpty()) { TableDefinition currentTable = dynamoDbService.describeTable(tableName, region); + if (throughput != null) { + DynamoDbCapacityQuotas.requireWithinTableQuota( + throughput.readCapacityUnits(), throughput.writeCapacityUnits(), region); + } + for (GsiThroughputUpdate gsiUpdate : gsiThroughputUpdates) { + Throughput gsiThroughput = gsiUpdate.provisionedThroughput(); + if (gsiThroughput != null) { + DynamoDbCapacityQuotas.requireWithinIndexQuota(gsiUpdate.indexName(), + gsiThroughput.readCapacityUnits(), gsiThroughput.writeCapacityUnits(), region); + } + } for (GsiThroughputUpdate gsiUpdate : gsiThroughputUpdates) { String indexName = gsiUpdate.indexName(); if (gsiDeletes.contains(indexName)) { 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 098f18de1f..0777a18193 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableService.java +++ b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbTableService.java @@ -404,6 +404,12 @@ public class NativeDynamoDbTableService { * stay with the caller, which runs them while it parses so their error precedence holds. */ TableDefinition updateTable(UpdateTableRequest request, String region) { + synchronized (dynamoDbService.capacityLock()) { + return applyUpdate(request, region); + } + } + + private TableDefinition applyUpdate(UpdateTableRequest request, String region) { String tableName = request.tableName(); TableSettings settings = request.settings(); List addRegions = request.replicaAdds(); @@ -430,7 +436,7 @@ public class NativeDynamoDbTableService { TableDefinition table = dynamoDbService.updateTable(tableName, throughput != null ? throughput.readCapacityUnits() : null, throughput != null ? throughput.writeCapacityUnits() : null, - request.gsiCreates(), request.gsiDeletes(), request.attributeDefinitions(), + request.gsiCreates(), request.gsiDeletes(), request.gsiUpdates(), request.attributeDefinitions(), request.vectorCreates(), request.vectorDeletes(), settings.billingMode(), region); diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbIntegrationTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbIntegrationTest.java index c5e2313864..df4b3db262 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbIntegrationTest.java @@ -894,6 +894,55 @@ class DynamoDbIntegrationTest { .body("TableMaxWriteCapacityUnits", equalTo(40000)); } + @Test + void updateTableRefusesIndexCapacityAboveThePerIndexMaximum() { + given() + .header("X-Amz-Target", "DynamoDB_20120810.CreateTable") + .contentType(DYNAMODB_CONTENT_TYPE) + .body(""" + { + "TableName": "QuotaTable", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "g", "AttributeType": "S"} + ], + "ProvisionedThroughput": {"ReadCapacityUnits": 1, "WriteCapacityUnits": 1}, + "GlobalSecondaryIndexes": [{ + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "KEYS_ONLY"}, + "ProvisionedThroughput": {"ReadCapacityUnits": 1, "WriteCapacityUnits": 1} + }] + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", "DynamoDB_20120810.UpdateTable") + .contentType(DYNAMODB_CONTENT_TYPE) + .body(""" + { + "TableName": "QuotaTable", + "GlobalSecondaryIndexUpdates": [{"Update": { + "IndexName": "gsi1", + "ProvisionedThroughput": {"ReadCapacityUnits": 40001, "WriteCapacityUnits": 1} + }}] + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("LimitExceededException")) + .body("message", equalTo("The requested ReadCapacityUnits for index gsi1, 40001, is above the per index " + + "maximum for the account in us-east-1. Per table maximum: 40000. Refer to the Amazon DynamoDB " + + "Developer Guide for current limits and how to request higher limits.")); + } + @Test void describeEndpointsNamesFloci() { given() 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 1295fe43ca..676fa8c0ed 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandlerTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandlerTest.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.AwsRegions; import io.floci.aws.core.common.SmithyValidationErrors; import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.core.storage.PersistentStorage; @@ -29,6 +30,11 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import static org.junit.jupiter.api.Assertions.*; @@ -715,6 +721,203 @@ class NativeDynamoDbJsonHandlerTest { () -> assertEquals(1, describedIndexes.size())); } + private static final String SEE_GUIDE = + " Refer to the Amazon DynamoDB Developer Guide for current limits and how to request higher limits."; + + private JsonNode quotaTableRequest(String tableName, long read, long write, long gsiRead, long gsiWrite) { + return json(""" + { + "TableName": "%s", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "g", "AttributeType": "S"} + ], + "ProvisionedThroughput": {"ReadCapacityUnits": %d, "WriteCapacityUnits": %d}, + "GlobalSecondaryIndexes": [{ + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "KEYS_ONLY"}, + "ProvisionedThroughput": {"ReadCapacityUnits": %d, "WriteCapacityUnits": %d} + }] + } + """.formatted(tableName, read, write, gsiRead, gsiWrite)); + } + + private JsonNode throughputUpdate(String tableName, long read, long write) { + return json(""" + {"TableName": "%s", "ProvisionedThroughput": {"ReadCapacityUnits": %d, "WriteCapacityUnits": %d}} + """.formatted(tableName, read, write)); + } + + private AwsException expectLimitExceeded(String action, JsonNode request) { + AwsException ex = assertThrows(AwsException.class, () -> handler.handle(action, request, "eu-west-2")); + assertEquals("LimitExceededException", ex.getErrorCode()); + return ex; + } + + @ParameterizedTest + @CsvSource(delimiter = '|', textBlock = """ + 40001 | 1 | 1 | 1 | The requested ReadCapacityUnits, 40001, is above the per table maximum for the account in eu-west-2. Per table maximum: 40000. + 1 | 40001 | 1 | 1 | The requested WriteCapacityUnits, 40001, is above the per table maximum for the account in eu-west-2. Per table maximum: 40000. + 1 | 1 | 40001 | 1 | The requested ReadCapacityUnits for index gsi1, 40001, is above the per index maximum for the account in eu-west-2. Per table maximum: 40000. + 1 | 1 | 1 | 40001 | The requested WriteCapacityUnits for index gsi1, 40001, is above the per index maximum for the account in eu-west-2. Per table maximum: 40000. + 1 | 40001 | 40001 | 1 | The requested WriteCapacityUnits, 40001, is above the per table maximum for the account in eu-west-2. Per table maximum: 40000. + 79984 | 1 | 1 | 1 | The requested ReadCapacityUnits, 79984, is above the per table maximum for the account in eu-west-2. Per table maximum: 40000. + 79985 | 1 | 1 | 1 | This request would have caused the ReadCapacityUnits limit to be exceeded for the account in eu-west-2. Current ReadCapacityUnits reserved by the account: 15. Limit: 80000. Requested: 79986. + 1 | 1 | 79985 | 1 | This request would have caused the ReadCapacityUnits limit to be exceeded for the account in eu-west-2. Current ReadCapacityUnits reserved by the account: 15. Limit: 80000. Requested: 79986. + 40001 | 80001 | 1 | 1 | This request would have caused the WriteCapacityUnits limit to be exceeded for the account in eu-west-2. Current WriteCapacityUnits reserved by the account: 15. Limit: 80000. Requested: 80002. + """) + void createTableRefusesCapacityAboveTheQuotas(long read, long write, long gsiRead, long gsiWrite, String message) throws Exception { + handler.handle("CreateTable", quotaTableRequest("held", 10, 10, 5, 5), "eu-west-2"); + handler.handle("CreateTable", quotaTableRequest("elsewhere", 30000, 30000, 30000, 30000), "us-east-1"); + + AwsException ex = expectLimitExceeded("CreateTable", quotaTableRequest("quota", read, write, gsiRead, gsiWrite)); + + assertEquals(message + SEE_GUIDE, ex.getMessage()); + assertEquals(List.of("held"), service.listTables("eu-west-2")); + } + + @Test + void createTableChecksTheQuotasAfterTheOtherErrors() throws Exception { + handler.handle("CreateTable", quotaTableRequest("held", 10, 10, 5, 5), "eu-west-2"); + ObjectNode unusedAttribute = (ObjectNode) quotaTableRequest("quota", 40001, 1, 1, 1); + ((ArrayNode) unusedAttribute.get("AttributeDefinitions")).addObject() + .put("AttributeName", "unused").put("AttributeType", "S"); + + AwsException taken = assertThrows(AwsException.class, () -> handler.handle("CreateTable", + quotaTableRequest("held", 40001, 1, 1, 1), "eu-west-2")); + AwsException invalid = assertThrows(AwsException.class, + () -> handler.handle("CreateTable", unusedAttribute, "eu-west-2")); + + assertEquals("ResourceInUseException", taken.getErrorCode()); + assertEquals("ValidationException", invalid.getErrorCode()); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """ + {"TableName":"quota","ProvisionedThroughput":{"ReadCapacityUnits":40001,"WriteCapacityUnits":10}} | The requested ReadCapacityUnits, 40001, is above the per table maximum for the account in eu-west-2. Per table maximum: 40000. + {"TableName":"quota","ProvisionedThroughput":{"ReadCapacityUnits":10,"WriteCapacityUnits":40001}} | The requested WriteCapacityUnits, 40001, is above the per table maximum for the account in eu-west-2. Per table maximum: 40000. + {"TableName":"quota","GlobalSecondaryIndexUpdates":[{"Update":{"IndexName":"gsi1","ProvisionedThroughput":{"ReadCapacityUnits":40001,"WriteCapacityUnits":5}}}],"ProvisionedThroughput":{"ReadCapacityUnits":40001,"WriteCapacityUnits":10}} | The requested ReadCapacityUnits, 40001, is above the per table maximum for the account in eu-west-2. Per table maximum: 40000. + {"TableName":"quota","GlobalSecondaryIndexUpdates":[{"Update":{"IndexName":"gsi1","ProvisionedThroughput":{"ReadCapacityUnits":6,"WriteCapacityUnits":5}}},{"Update":{"IndexName":"nope","ProvisionedThroughput":{"ReadCapacityUnits":1,"WriteCapacityUnits":40001}}}]} | The requested WriteCapacityUnits for index nope, 40001, is above the per index maximum for the account in eu-west-2. Per table maximum: 40000. + {"TableName":"quota","AttributeDefinitions":[{"AttributeName":"g","AttributeType":"S"}],"GlobalSecondaryIndexUpdates":[{"Create":{"IndexName":"gsi2","KeySchema":[{"AttributeName":"g","KeyType":"HASH"}],"Projection":{"ProjectionType":"KEYS_ONLY"},"ProvisionedThroughput":{"ReadCapacityUnits":40001,"WriteCapacityUnits":1}}}]} | The requested ReadCapacityUnits for index gsi2, 40001, is above the per index maximum for the account in eu-west-2. Per table maximum: 40000. + {"TableName":"quota","AttributeDefinitions":[{"AttributeName":"g","AttributeType":"S"}],"GlobalSecondaryIndexUpdates":[{"Create":{"IndexName":"gsi2","KeySchema":[{"AttributeName":"g","KeyType":"HASH"}],"Projection":{"ProjectionType":"KEYS_ONLY"},"ProvisionedThroughput":{"ReadCapacityUnits":79971,"WriteCapacityUnits":1}}}]} | This request would have caused the ReadCapacityUnits limit to be exceeded for the account in eu-west-2. Current ReadCapacityUnits reserved by the account: 30. Limit: 80000. Current ReadCapacityUnits provisioned for the table and indexes: 15. Requested: 79986. + """) + void updateTableRefusesCapacityAboveTheQuotas(String request, String message) throws Exception { + handler.handle("CreateTable", quotaTableRequest("held", 10, 10, 5, 5), "eu-west-2"); + handler.handle("CreateTable", quotaTableRequest("quota", 10, 10, 5, 5), "eu-west-2"); + + AwsException ex = expectLimitExceeded("UpdateTable", json(request)); + + assertEquals(message + SEE_GUIDE, ex.getMessage()); + TableDefinition table = service.describeTable("quota", "eu-west-2"); + assertEquals(10, table.getProvisionedThroughput().getReadCapacityUnits()); + assertEquals(1, table.getGlobalSecondaryIndexes().size()); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """ + {"TableName":"quota","ProvisionedThroughput":{"ReadCapacityUnits":39996,"WriteCapacityUnits":10}} | ReadCapacityUnits | 40015 | 15 | 40001 + {"TableName":"quota","ProvisionedThroughput":{"ReadCapacityUnits":10,"WriteCapacityUnits":39996}} | WriteCapacityUnits | 40015 | 15 | 40001 + {"TableName":"quota","GlobalSecondaryIndexUpdates":[{"Update":{"IndexName":"gsi1","ProvisionedThroughput":{"ReadCapacityUnits":39991,"WriteCapacityUnits":5}}}]} | ReadCapacityUnits | 40015 | 15 | 40001 + {"TableName":"quota","AttributeDefinitions":[{"AttributeName":"g","AttributeType":"S"}],"GlobalSecondaryIndexUpdates":[{"Create":{"IndexName":"gsi2","KeySchema":[{"AttributeName":"g","KeyType":"HASH"}],"Projection":{"ProjectionType":"KEYS_ONLY"},"ProvisionedThroughput":{"ReadCapacityUnits":39986,"WriteCapacityUnits":1}}}]} | ReadCapacityUnits | 40015 | 15 | 40001 + {"TableName":"onDemand","BillingMode":"PROVISIONED","ProvisionedThroughput":{"ReadCapacityUnits":39986,"WriteCapacityUnits":1}} | ReadCapacityUnits | 40015 | 0 | 39986 + """) + void updateTableRefusesATotalAboveTheAccountQuota(String request, String unit, long reserved, long current, + long requested) throws Exception { + handler.handle("CreateTable", quotaTableRequest("held", 39990, 39990, 10, 10), "eu-west-2"); + handler.handle("CreateTable", quotaTableRequest("quota", 10, 10, 5, 5), "eu-west-2"); + handler.handle("CreateTable", json(""" + { + "TableName": "onDemand", + "BillingMode": "PAY_PER_REQUEST", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}] + } + """), "eu-west-2"); + + AwsException ex = expectLimitExceeded("UpdateTable", json(request)); + + assertEquals("This request would have caused the " + unit + " limit to be exceeded for the account in " + + "eu-west-2. Current " + unit + " reserved by the account: " + reserved + ". Limit: 80000. Current " + + unit + " provisioned for the table and indexes: " + current + ". Requested: " + requested + "." + + SEE_GUIDE, ex.getMessage()); + } + + @Test + void updateTableAcceptsATotalAtTheAccountQuotaAndAnyDecrease() throws Exception { + handler.handle("CreateTable", quotaTableRequest("held", 39990, 39990, 10, 10), "eu-west-2"); + handler.handle("CreateTable", quotaTableRequest("quota", 10, 10, 5, 5), "eu-west-2"); + + handler.handle("UpdateTable", throughputUpdate("quota", 39995, 10), "eu-west-2"); + handler.handle("UpdateTable", throughputUpdate("quota", 39994, 9), "eu-west-2"); + + assertEquals(39994, service.describeTable("quota", "eu-west-2").getProvisionedThroughput().getReadCapacityUnits()); + } + + @Test + void updateTableChecksTheQuotasAfterTheLookups() throws Exception { + handler.handle("CreateTable", quotaTableRequest("quota", 10, 10, 5, 5), "eu-west-2"); + JsonNode existingIndexCreate = json(""" + { + "TableName": "quota", + "AttributeDefinitions": [{"AttributeName": "g", "AttributeType": "S"}], + "GlobalSecondaryIndexUpdates": [{"Create": { + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "KEYS_ONLY"}, + "ProvisionedThroughput": {"ReadCapacityUnits": 80001, "WriteCapacityUnits": 1} + }}] + } + """); + + AwsException missingTable = assertThrows(AwsException.class, + () -> handler.handle("UpdateTable", throughputUpdate("missing", 40001, 10), "eu-west-2")); + AwsException existingIndex = assertThrows(AwsException.class, + () -> handler.handle("UpdateTable", existingIndexCreate, "eu-west-2")); + + assertEquals("ResourceNotFoundException", missingTable.getErrorCode()); + assertEquals("ValidationException", existingIndex.getErrorCode()); + } + + @Test + void concurrentRequestsCannotPassTheAccountQuotaTogether() throws Exception { + try (ExecutorService pool = Executors.newFixedThreadPool(16)) { + for (String region : AwsRegions.advertised(AwsRegions.DEFAULT_PARTITION)) { + CountDownLatch start = new CountDownLatch(1); + List> results = new ArrayList<>(); + for (int i = 0; i < 8; i++) { + handler.handle("CreateTable", quotaTableRequest("old" + i, 1, 1, 1, 1), region); + JsonNode create = quotaTableRequest("new" + i, 10000, 1, 1, 1); + JsonNode update = throughputUpdate("old" + i, 10000, 1); + results.add(pool.submit(() -> { + start.await(); + return handler.handle("CreateTable", create, region); + })); + results.add(pool.submit(() -> { + start.await(); + return handler.handle("UpdateTable", update, region); + })); + } + start.countDown(); + for (Future result : results) { + try { + result.get(); + } catch (ExecutionException e) { + AwsException refused = assertInstanceOf(AwsException.class, e.getCause()); + assertEquals("LimitExceededException", refused.getErrorCode()); + } + } + + long reserved = 0; + for (String name : service.listTables(region)) { + reserved += DynamoDbCapacityQuotas.Capacity.of(service.describeTable(name, region)).read(); + } + assertTrue(reserved <= DynamoDbCapacityQuotas.ACCOUNT_MAX_CAPACITY_UNITS, region + " " + reserved); + } + } + } + // Request validation for AWS parity: real DynamoDB rejects each of these with a // ValidationException (paritysuite dynamodb-conformance tier1).