diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbKeyHash.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbKeyHash.java index 985a42fcd5..f1f80bdd1d 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbKeyHash.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbKeyHash.java @@ -11,9 +11,11 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Comparator; +import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; +import java.util.function.ToIntFunction; /** The hash DynamoDB places and orders keys by: MD5 over "Outliers" and the bytes of the key values. */ final class DynamoDbKeyHash { @@ -41,6 +43,24 @@ final class DynamoDbKeyHash { Arrays::compareUnsigned); } + /** DynamoDB gives an on-demand table and its indexes 4 partitions, and a table provisioned at 1 unit 1. */ + static int partitionCount(TableDefinition table) { + return "PAY_PER_REQUEST".equals(table.getBillingMode()) ? 4 : 1; + } + + /** + * Finds the partition of an item, each partition holding an equal range of the hash. A key value + * is hashed once, as a scan meets the same partition key again and again. + */ + static ToIntFunction partitionLocator(List keyNames, int partitions) { + if (partitions == 1) { + return item -> 0; + } + Map, Integer> known = new HashMap<>(); + return item -> known.computeIfAbsent(Arrays.asList(keyNames.stream().map(item::get).toArray(JsonNode[]::new)), + ignored -> (of(item, keyNames)[0] & 0xFF) * partitions / 256); + } + static byte[] of(JsonNode item, List keyNames) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bytes.writeBytes(SALT); diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLHandler.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLHandler.java index 04ce840578..b003c460b4 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLHandler.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLHandler.java @@ -149,9 +149,7 @@ class DynamoDbPartiQLHandler { private static DynamoDbWriteCapacity.Cost readCapacity(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath, Page page, boolean consistentRead) { - double units = page.readBytes().stream() - .mapToDouble(bytes -> NativeDynamoDbJsonHandler.readCapacityUnits(bytes, consistentRead)) - .sum(); + double units = NativeDynamoDbJsonHandler.readCapacityUnits(page.readBytes(), consistentRead); if (!accessPath.isIndex()) { return new DynamoDbWriteCapacity.Cost(units, Map.of(), Map.of()); } @@ -243,8 +241,7 @@ class DynamoDbPartiQLHandler { List matching = partialProjection ? matchingIndexView(result.items(), scanFilters, accessPath, table) : result.items(); - return new Page(matching, result.lastEvaluatedKey(), List.of(result.scannedBytes()), - result.scannedItems()); + return new Page(matching, result.lastEvaluatedKey(), result.readBytes(), result.scannedItems()); } if (accessPath.kind() == DynamoDbAccessPath.Kind.TABLE && skName == null && skCond == null && filterConds.isEmpty()) { @@ -362,14 +359,14 @@ class DynamoDbPartiQLHandler { private Page readOrdered(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath, Routing routing, JsonNode after, Integer limit, String region) { List rows = new ArrayList<>(); - long scannedBytes = 0; + List readBytes = new ArrayList<>(); List scannedItems = new ArrayList<>(); JsonNode lastKey = null; do { JsonNode from = lastKey; Page page = readPage(stmt, table, accessPath, routing, () -> from, null, region); rows.addAll(page.items()); - scannedBytes += page.readBytes().stream().mapToLong(Long::longValue).sum(); + readBytes.addAll(page.readBytes()); scannedItems.addAll(page.scannedItems()); lastKey = page.lastEvaluatedKey(); } while (lastKey != null); @@ -384,7 +381,7 @@ class DynamoDbPartiQLHandler { } int end = limit == null ? rows.size() : start + Math.min(rows.size() - start, limit); JsonNode resumeAfter = start < end && end < rows.size() ? orderingKey(rows.get(end - 1), accessPath, table) : null; - return new Page(new ArrayList<>(rows.subList(start, end)), resumeAfter, List.of(scannedBytes), scannedItems); + return new Page(new ArrayList<>(rows.subList(start, end)), resumeAfter, readBytes, scannedItems); } private static void requireOrderByShape(Stmt.Select stmt, DynamoDbAccessPath accessPath, 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 14f67ed8d9..a00597ef57 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java @@ -80,6 +80,7 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TreeMap; +import java.util.TreeSet; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; @@ -89,7 +90,9 @@ import java.util.concurrent.Executor; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; import java.util.function.Function; +import java.util.function.Predicate; import java.util.function.Supplier; +import java.util.function.ToIntFunction; import java.util.stream.Collectors; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; @@ -1768,9 +1771,14 @@ public class DynamoDbService { TableDefinition table = requireActiveTable(storageKey); DynamoDbAccessPath accessPath = DynamoDbAccessPath.resolve(table, indexName); + int partitions = DynamoDbKeyHash.partitionCount(table); + boolean segmented = segment != null && totalSegments != null && totalSegments > 1; ConcurrentSkipListMap items = itemsByTable.get(scopedItemsKey(storageKey)); - if (items == null) return new ScanResult(List.of(), 0, 0, null, List.of()); + if (items == null) { + return new ScanResult(List.of(), 0, segmented ? List.of(0L) : Collections.nCopies(partitions, 0L), + null, List.of()); + } // ConcurrentSkipListMap keeps items sorted by base item key — no sort needed. // Use tailMap for O(log n) pagination instead of O(n) linear search. @@ -1787,6 +1795,13 @@ public class DynamoDbService { lekPkName = accessPath.partitionKeyName(); lekSkName = accessPath.sortKeyName(); } + String indexPkName = lekPkName; + String indexSkName = lekSkName; + Predicate inIndex = item -> !indexScan || (hasNonNullAttribute(item, indexPkName) + && (indexSkName == null || hasNonNullAttribute(item, indexSkName))); + ToIntFunction partitionOf = DynamoDbKeyHash.partitionLocator( + accessPath.isGlobalSecondaryIndex() ? accessPath.partitionKeyNames() : List.of(pkName), partitions); + Map bytesByPartition = new TreeMap<>(); Collection source = exclusiveStartKey != null ? items.tailMap(buildItemKeyFromNode(exclusiveStartKey, pkName, skName), false).values() @@ -1807,11 +1822,10 @@ public class DynamoDbService { // itself, and base-table items missing any index key attribute do not // exist in the index — they are never read, never counted, and can // never anchor a cursor. - if (indexScan && !(hasNonNullAttribute(item, lekPkName) - && (lekSkName == null || hasNonNullAttribute(item, lekSkName)))) { + if (!inIndex.test(item)) { continue; } - if (segment != null && totalSegments != null && totalSegments > 1) { + if (segmented) { JsonNode pkAttr = item.get(lekPkName); if (computeSegment(pkAttr, totalSegments) != segment) { continue; @@ -1832,7 +1846,11 @@ public class DynamoDbService { break; } accSize += sz; - billedBytes += billedReadSize(item, accessPath, table, sz); + long billed = billedReadSize(item, accessPath, table, sz); + billedBytes += billed; + if (!segmented) { + bytesByPartition.merge(partitionOf.applyAsInt(item), billed, Long::sum); + } totalScanned++; scannedItems.add(item); lastScanned = item; @@ -1858,7 +1876,38 @@ public class DynamoDbService { LOG.tracev("Scan on {0}: returned={1} scanned={2}", canonicalTableName, results.size(), totalScanned); - return new ScanResult(results, totalScanned, billedBytes, lastEvaluatedKey, scannedItems); + List readBytes = segmented ? List.of(billedBytes) + : partitionReads(items.values(), inIndex, partitionOf, partitions, bytesByPartition, + lastEvaluatedKey == null, totalScanned == 0 ? exclusiveStartKey : null); + return new ScanResult(results, totalScanned, readBytes, lastEvaluatedKey, scannedItems); + } + + // DynamoDB charges a scan page for each partition it reads, at least one 4 KB block each. The + // page that ends the scan also reads each partition that holds nothing, and when it finds no + // item left it still reads the partition it resumed in. + private static List partitionReads(Collection allItems, Predicate inIndex, + ToIntFunction partitionOf, int partitions, + Map bytesByPartition, boolean endsScan, + JsonNode resumedFrom) { + Set read = new TreeSet<>(bytesByPartition.keySet()); + if (endsScan) { + Set holding = new HashSet<>(); + for (Iterator each = allItems.iterator(); each.hasNext() && holding.size() < partitions; ) { + JsonNode item = each.next(); + if (inIndex.test(item)) { + holding.add(partitionOf.applyAsInt(item)); + } + } + for (int partition = 0; partition < partitions; partition++) { + if (!holding.contains(partition)) { + read.add(partition); + } + } + if (resumedFrom != null) { + read.add(partitionOf.applyAsInt(resumedFrom)); + } + } + return read.stream().map(partition -> bytesByPartition.getOrDefault(partition, 0L)).toList(); } // A read served by a KEYS_ONLY or INCLUDE index is sized on the projection the @@ -5227,9 +5276,10 @@ public class DynamoDbService { public record TransactGetResult(List items, Map capacity) {} - // scannedBytes carries the pre-filter size of the read items: DynamoDB bills a - // Query or Scan on what it read, not on what survived the filter or projection. - public record ScanResult(List items, int scannedCount, long scannedBytes, JsonNode lastEvaluatedKey, + // scannedBytes and readBytes carry the pre-filter size of the read items: DynamoDB bills a + // Query or Scan on what it read, not on what survived the filter or projection. A Scan + // charges each partition it reads on its own. + public record ScanResult(List items, int scannedCount, List readBytes, JsonNode lastEvaluatedKey, List scannedItems) {} public record QueryResult(List items, int scannedCount, long scannedBytes, JsonNode lastEvaluatedKey, List scannedItems) {} 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 c98fba4765..d6df857297 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java +++ b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java @@ -1634,7 +1634,7 @@ public class NativeDynamoDbJsonHandler { response.set("LastEvaluatedKey", result.lastEvaluatedKey()); } addConsumedCapacity(response, request, tableName, - readCapacityUnits(result.scannedBytes(), request.path("ConsistentRead").asBoolean(false)), scanAccessPath); + readCapacityUnits(result.readBytes(), request.path("ConsistentRead").asBoolean(false)), scanAccessPath); return Response.ok(response).build(); } @@ -3729,6 +3729,11 @@ public class NativeDynamoDbJsonHandler { return consistentRead ? units * 2 : units; } + /** Each read DynamoDB charges on its own, such as each partition a scan page reads. */ + static double readCapacityUnits(List reads, boolean consistentRead) { + return reads.stream().mapToDouble(bytes -> readCapacityUnits(bytes, consistentRead)).sum(); + } + /** * Write-side ConsumedCapacity with the per-index arms DynamoDB reports under * INDEXES. oldItem and newItem are the stored images around the write; the new diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLConsumedCapacityIntegrationTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLConsumedCapacityIntegrationTest.java index 4e478448bf..a52ed9901f 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLConsumedCapacityIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLConsumedCapacityIntegrationTest.java @@ -176,7 +176,7 @@ class DynamoDbPartiQLConsumedCapacityIntegrationTest { } """) .body("ConsumedCapacity.Table.CapacityUnits", equalTo(1.5f)) - .body("ConsumedCapacity.LocalSecondaryIndexes.'lsi-keys'.CapacityUnits", equalTo(0.5f)); + .body("ConsumedCapacity.LocalSecondaryIndexes.'lsi-keys'.CapacityUnits", equalTo(2.0f)); send("ExecuteStatement", """ { "Statement": "SELECT lsiSk FROM \\"PartiQLCapacityLsiTable\\".\\"lsi-keys\\"", diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbScanReadCapacityIntegrationTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbScanReadCapacityIntegrationTest.java new file mode 100644 index 0000000000..bb0687b16b --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbScanReadCapacityIntegrationTest.java @@ -0,0 +1,166 @@ +package io.floci.aws.services.dynamodb; + +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.BillingMode; +import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; +import software.amazon.awssdk.services.dynamodb.model.ExecuteStatementResponse; +import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex; +import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; +import software.amazon.awssdk.services.dynamodb.model.KeyType; +import software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex; +import software.amazon.awssdk.services.dynamodb.model.Projection; +import software.amazon.awssdk.services.dynamodb.model.ProjectionType; +import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; +import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; +import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; +import software.amazon.awssdk.services.dynamodb.model.ScanRequest; +import software.amazon.awssdk.services.dynamodb.model.ScanResponse; +import software.amazon.awssdk.services.dynamodb.model.Select; + +import java.util.Map; +import java.util.UUID; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +class DynamoDbScanReadCapacityIntegrationTest { + + @Test + void scanOfAnOnDemandTableReadsFourPartitions() { + try (DynamoDbClient client = client()) { + String empty = createTable(client, true, false); + String tiny = createTable(client, true, true); + for (String sk : new String[] {"row-1", "row-2", "row-3"}) { + client.putItem(r -> r.tableName(tiny).item(Map.of("pk", text("k"), "sk", text(sk), "g", text("g")))); + } + + assertEquals(2.0, scanUnits(client, empty, r -> { })); + assertEquals(4.0, scanUnits(client, empty, r -> r.consistentRead(true))); + assertEquals(2.0, scanUnits(client, tiny, r -> { })); + assertEquals(4.0, scanUnits(client, tiny, r -> r.consistentRead(true))); + assertEquals(2.0, scanUnits(client, tiny, r -> r.select(Select.COUNT))); + assertEquals(2.0, scanUnits(client, tiny, r -> r.filterExpression("sk = :v") + .expressionAttributeValues(Map.of(":v", text("nope"))))); + assertEquals(2.0, scanUnits(client, tiny, r -> r.indexName("gix"))); + assertEquals(2.0, scanUnits(client, tiny, r -> r.indexName("lix"))); + assertEquals(4.0, scanUnits(client, tiny, r -> r.indexName("lix").consistentRead(true))); + assertEquals(3.5, scanUnits(client, tiny, r -> r.limit(1))); + assertEquals(2.5, scanUnits(client, tiny, r -> r.limit(2))); + assertEquals(2.0, statementUnits(client, "SELECT * FROM \"" + tiny + "\"", false)); + assertEquals(4.0, statementUnits(client, "SELECT * FROM \"" + tiny + "\"", true)); + assertEquals(2.0, statementUnits(client, "SELECT * FROM \"" + tiny + "\".\"gix\"", false)); + assertEquals(2.0, statementUnits(client, "SELECT * FROM \"" + tiny + "\" WHERE x = 1", false)); + assertEquals(2.0, statementUnits(client, "SELECT * FROM \"" + empty + "\"", false)); + } + } + + @Test + void scanChargesEachPartitionItsOwnBlocks() { + try (DynamoDbClient client = client()) { + String big = createTable(client, true, false); + for (String sk : new String[] {"b1", "b2", "b3"}) { + client.putItem(r -> r.tableName(big).item(Map.of("pk", text("k"), "sk", text(sk), + "pad", text("x".repeat(3500))))); + } + String many = createTable(client, true, false); + for (int i = 0; i < 12; i++) { + String pk = "m" + i; + client.putItem(r -> r.tableName(many).item(Map.of("pk", text(pk), "sk", text("x"), + "pad", text("y".repeat(1000))))); + } + + assertEquals(3.0, scanUnits(client, big, r -> { })); + assertEquals(6.0, scanUnits(client, big, r -> r.consistentRead(true))); + assertEquals(2.5, scanUnits(client, many, r -> { })); + assertEquals(5.0, scanUnits(client, many, r -> r.consistentRead(true))); + assertEquals(3.0, statementUnits(client, "SELECT * FROM \"" + big + "\"", false)); + assertEquals(2.5, statementUnits(client, "SELECT * FROM \"" + many + "\"", false)); + String severalKeys = "SELECT * FROM \"" + many + "\" WHERE pk IN ['m0', 'm1']"; + assertEquals(statementUnits(client, severalKeys, false), + statementUnits(client, severalKeys + " ORDER BY pk", false)); + } + } + + @Test + void scanOfAProvisionedTableReadsOnePartition() { + try (DynamoDbClient client = client()) { + String table = createTable(client, false, false); + for (String sk : new String[] {"row-1", "row-2", "row-3"}) { + client.putItem(r -> r.tableName(table).item(Map.of("pk", text("k"), "sk", text(sk)))); + } + + assertEquals(0.5, scanUnits(client, table, r -> { })); + assertEquals(1.0, scanUnits(client, table, r -> r.consistentRead(true))); + assertEquals(0.5, statementUnits(client, "SELECT * FROM \"" + table + "\"", false)); + } + } + + private static DynamoDbClient client() { + return AwsTestClients.create(DynamoDbClient.builder(), "test", Region.US_EAST_1); + } + + private static String createTable(DynamoDbClient client, boolean onDemand, boolean indexes) { + String table = "scan-capacity-" + UUID.randomUUID(); + CreateTableRequest.Builder request = CreateTableRequest.builder().tableName(table) + .keySchema(element("pk", KeyType.HASH), element("sk", KeyType.RANGE)); + if (onDemand) { + request.billingMode(BillingMode.PAY_PER_REQUEST); + } else { + request.provisionedThroughput(ProvisionedThroughput.builder() + .readCapacityUnits(1L).writeCapacityUnits(1L).build()); + } + if (indexes) { + Projection all = Projection.builder().projectionType(ProjectionType.ALL).build(); + request.attributeDefinitions(definition("pk"), definition("sk"), definition("g")) + .globalSecondaryIndexes(GlobalSecondaryIndex.builder().indexName("gix") + .keySchema(element("g", KeyType.HASH)).projection(all).build()) + .localSecondaryIndexes(LocalSecondaryIndex.builder().indexName("lix") + .keySchema(element("pk", KeyType.HASH), element("g", KeyType.RANGE)) + .projection(all).build()); + } else { + request.attributeDefinitions(definition("pk"), definition("sk")); + } + client.createTable(request.build()); + return table; + } + + private static double scanUnits(DynamoDbClient client, String table, Consumer options) { + double units = 0; + Map cursor = null; + do { + ScanRequest.Builder request = ScanRequest.builder().tableName(table) + .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL).exclusiveStartKey(cursor); + options.accept(request); + ScanResponse response = client.scan(request.build()); + units += response.consumedCapacity().capacityUnits(); + cursor = response.hasLastEvaluatedKey() && !response.lastEvaluatedKey().isEmpty() + ? response.lastEvaluatedKey() : null; + } while (cursor != null); + return units; + } + + private static double statementUnits(DynamoDbClient client, String statement, boolean consistentRead) { + ExecuteStatementResponse response = client.executeStatement(r -> r.statement(statement) + .consistentRead(consistentRead).returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)); + return response.consumedCapacity().capacityUnits(); + } + + private static AttributeDefinition definition(String name) { + return AttributeDefinition.builder().attributeName(name).attributeType(ScalarAttributeType.S).build(); + } + + private static KeySchemaElement element(String name, KeyType type) { + return KeySchemaElement.builder().attributeName(name).keyType(type).build(); + } + + private static AttributeValue text(String value) { + return AttributeValue.builder().s(value).build(); + } +} diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbServiceTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbServiceTest.java index 95490f0933..646691c770 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbServiceTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbServiceTest.java @@ -1185,6 +1185,21 @@ class DynamoDbServiceTest { assertEquals(2, result.items().size()); } + @Test + void scanOfAReloadedTableWithoutItemsReadsLikeAnEmptyTable() { + String region = "eu-west-1"; + InMemoryStorage tables = new InMemoryStorage<>(); + new DynamoDbService(tables).createTable("Users", List.of(new KeySchemaElement("userId", "HASH")), + List.of(new AttributeDefinition("userId", "S")), null, null, List.of(), List.of(), List.of(), + "PAY_PER_REQUEST", region); + DynamoDbService reloaded = new DynamoDbService(tables); + + assertEquals(List.of(0L, 0L, 0L, 0L), + reloaded.scan("Users", null, null, null, null, null, null, region).readBytes()); + assertEquals(List.of(0L), + reloaded.scan("Users", null, null, null, null, null, null, null, 0, 4, region).readBytes()); + } + @Test void operationsOnNonExistentTableThrow() { String region = "eu-west-1";