diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbItemSize.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbItemSize.java index 77d574d562..9998b7a740 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbItemSize.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbItemSize.java @@ -10,7 +10,6 @@ import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.HashSet; import java.util.Iterator; -import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; @@ -30,19 +29,6 @@ final class DynamoDbItemSize { /** What a vector index reads per vector component, whatever the written decimal text costs. */ static final int VECTOR_COMPONENT_BYTES = 4; - // An UpdateExpression is also measured as a statement: these per action, the target paths - // with a shared prefix counted once, and every operand a SET reads or an ADD writes. - // Every other surface, AttributeUpdates included, measures only the finished item. - private static final int UPDATE_COST = 3; - private static final int SET_OR_ADD_COST = 19; - private static final int REMOVE_OR_DELETE_COST = 1; - private static final int TARGET_CONTAINER_COST = 4; - private static final int OPERAND_PATH_COST = 1; - private static final int OPERAND_PATH_ELEMENT_COST = 14; - private static final int PLUS_COST = 34; - private static final int MINUS_COST = 37; - private static final int LIST_APPEND_COST = 37; - private static final int IF_NOT_EXISTS_COST = 39; private static final int CONTAINER_COST = 3; private static final int MAX_NUMBER_PAIRS = 20; @@ -68,13 +54,15 @@ final class DynamoDbItemSize { } /** - * The size of an UpdateExpression statement, or empty when an action lacks the assignment or the - * value its clause needs, or leaves a parenthesis open. The update parser refuses such a statement. + * The size UpdateItem and TransactWriteItems measure an UpdateExpression statement at, besides the + * finished item: for every SET and ADD action, the UTF-8 bytes of the names in its target path (a + * list index counts 0) plus the size of each :value its operand uses, once per use. Empty when an + * action lacks the assignment or the value its clause needs, or leaves a parenthesis open. The + * update parser refuses such a statement. */ static OptionalInt updateStatementSize(String expression, Function> paths, JsonNode values) { - int size = UPDATE_COST; - PathTree targets = new PathTree(); + int size = 0; String remaining = expression.trim().replaceAll("\\s+", " "); while (!remaining.isEmpty()) { String keyword = remaining.substring(0, Math.max(remaining.indexOf(' '), 0)).toUpperCase(Locale.ROOT); @@ -88,11 +76,11 @@ final class DynamoDbItemSize { if (!readable(keyword, action)) { return OptionalInt.empty(); } - size += actionSize(keyword, action, targets, paths, values); + size += actionSize(keyword, action, paths, values); actions = comma < 0 ? "" : actions.substring(comma + 1); } } - return OptionalInt.of(size + targets.size()); + return OptionalInt.of(size); } private static boolean readable(String clause, String action) { @@ -119,89 +107,61 @@ final class DynamoDbItemSize { return open > 0; } - private static int actionSize(String clause, String action, PathTree targets, + private static int actionSize(String clause, String action, Function> paths, JsonNode values) { return switch (clause) { case "SET" -> { int assignment = action.indexOf('='); - targets.add(paths.apply(action.substring(0, assignment))); - yield SET_OR_ADD_COST + operandSize(action.substring(assignment + 1), paths, values); + yield targetSize(paths.apply(action.substring(0, assignment))) + + operandSize(action.substring(assignment + 1), values); } case "ADD" -> { String[] parts = action.split(" ", 2); - targets.add(paths.apply(parts[0])); - yield SET_OR_ADD_COST + operandSize(parts[1], paths, values); - } - default -> { - targets.add(paths.apply(action.split(" ", 2)[0])); - yield REMOVE_OR_DELETE_COST; + yield targetSize(paths.apply(parts[0])) + operandSize(parts[1], values); } + default -> 0; }; } - private static int operandSize(String operand, Function> paths, JsonNode values) { + private static int targetSize(List path) { + int size = 0; + for (Object element : path) { + if (element instanceof String name) { + size += utf8Length(name); + } + } + return size; + } + + private static int operandSize(String operand, JsonNode values) { String expr = DynamoDbService.stripOuterParens(operand); int operator = DynamoDbService.findArithmeticOperator(expr); if (operator >= 0) { - return (expr.charAt(operator) == '+' ? PLUS_COST : MINUS_COST) - + operandSize(expr.substring(0, operator), paths, values) - + operandSize(expr.substring(operator + 1), paths, values); + return operandSize(expr.substring(0, operator), values) + + operandSize(expr.substring(operator + 1), values); } String lower = expr.toLowerCase(Locale.ROOT); - if (DynamoDbService.startsWithFunctionCall(lower, "list_append")) { - return LIST_APPEND_COST + argumentsSize(expr, paths, values); - } - if (DynamoDbService.startsWithFunctionCall(lower, "if_not_exists")) { - return IF_NOT_EXISTS_COST + argumentsSize(expr, paths, values); + if (DynamoDbService.startsWithFunctionCall(lower, "list_append") + || DynamoDbService.startsWithFunctionCall(lower, "if_not_exists")) { + return argumentsSize(expr, values); } if (expr.startsWith(":")) { return values == null ? 0 : attributeValueSize(values.get(expr)); } - int size = OPERAND_PATH_COST; - for (Object element : paths.apply(expr)) { - size += OPERAND_PATH_ELEMENT_COST + pathElementSize(element); - } - return size; + return 0; } - private static int argumentsSize(String call, Function> paths, JsonNode values) { + private static int argumentsSize(String call, JsonNode values) { String arguments = call.substring(call.indexOf('(') + 1, call.lastIndexOf(')')); int size = 0; while (!arguments.isBlank()) { int comma = DynamoDbService.findNextComma(arguments); - size += operandSize(comma < 0 ? arguments : arguments.substring(0, comma), paths, values); + size += operandSize(comma < 0 ? arguments : arguments.substring(0, comma), values); arguments = comma < 0 ? "" : arguments.substring(comma + 1); } return size; } - // A list index counts its decimal digits. - private static int pathElementSize(Object element) { - return element instanceof Long index ? Long.toString(index).length() : utf8Length((String) element); - } - - private static final class PathTree { - - private final Map children = new LinkedHashMap<>(); - - void add(List path) { - PathTree node = this; - for (Object element : path) { - node = node.children.computeIfAbsent(element, ignored -> new PathTree()); - } - } - - int size() { - int size = 0; - for (Map.Entry child : children.entrySet()) { - PathTree nested = child.getValue(); - size += pathElementSize(child.getKey()) - + (nested.children.isEmpty() ? 0 : TARGET_CONTAINER_COST + nested.size()); - } - return size; - } - } - static int billedItemSize(TableDefinition table, JsonNode item) { return billedItemSize(table, item, calculateItemSize(item)); } 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 3a3172aae6..9bace69105 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java @@ -2406,29 +2406,44 @@ public class DynamoDbService { return new TransactParticipant(storageKey, itemKey, tableName); } - // AWS checks every member's key against the table schema, in order, before it looks for - // duplicate items or evaluates a condition. The first mismatch cancels with that member's - // reason alone. An empty key value still fails the whole request. - void cancelOnKeySchemaMismatch(List transactItems, String region) { + // AWS looks up every member's table first, in order. Then it walks the members in order. + // A Put checks its item size, then its key. Any other member checks its key, then an Update + // checks its statement size. A key mismatch cancels with that member's reason alone. An + // oversized item or statement fails the whole request. All of this runs before the duplicate + // item check and before any condition. An empty key value still fails the whole request. + void validateTransactMemberKeysAndSizes(List transactItems, String region) { + for (JsonNode transactItem : transactItems) { + JsonNode target = transactTarget(transactItem); + if (target != null) { + requireActiveTable(regionKey(region, canonicalTableName(region, target.path("TableName").asText()))); + } + } for (int i = 0; i < transactItems.size(); i++) { try { - validateTransactMemberKey(transactItems.get(i), region); + validateTransactMember(transactItems.get(i), region); } catch (KeySchemaMismatchException e) { throw cancelledByMember(transactItems.size(), i, e.getMessage()); } } } - private void validateTransactMemberKey(JsonNode transactItem, String region) { - boolean isPut = transactItem.has("Put"); - JsonNode target = isPut ? transactItem.get("Put") + private static JsonNode transactTarget(JsonNode transactItem) { + return transactItem.has("Put") ? transactItem.get("Put") : transactItem.has("Update") ? transactItem.get("Update") : transactItem.has("Delete") ? transactItem.get("Delete") : transactItem.get("ConditionCheck"); + } + + private void validateTransactMember(JsonNode transactItem, String region) { + boolean isPut = transactItem.has("Put"); + JsonNode target = transactTarget(transactItem); JsonNode key = target == null ? null : target.get(isPut ? "Item" : "Key"); if (key == null) { return; } + if (isPut) { + DynamoDbItemSize.validateSize(DynamoDbNumberUtils.normalizeNumbersInItem(key)); + } String tableName = canonicalTableName(region, target.path("TableName").asText()); TableDefinition table = requireActiveTable(regionKey(region, tableName)); List keyNames = table.getSortKeyName() == null @@ -2444,6 +2459,11 @@ public class DynamoDbService { buildItemKey(table, key, isPut ? KeySurface.ITEM_BODY : KeySurface.KEY_ARGUMENT); if (isPut) { validateIndexKeyTypes(table, key, false); + } else if (transactItem.has("Update") && target.has("UpdateExpression")) { + JsonNode names = target.get("ExpressionAttributeNames"); + DynamoDbItemSize.updateStatementSize(target.get("UpdateExpression").asText(), + path -> parsePath(path, names), target.get("ExpressionAttributeValues")) + .ifPresent(DynamoDbService::requireUpdateStatementWithinSizeLimit); } } 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 6c2b048583..ec3bfd045c 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java +++ b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java @@ -2956,7 +2956,7 @@ public class NativeDynamoDbJsonHandler { List transactItems = new ArrayList<>(); transactItemsNode.forEach(transactItems::add); try { - dynamoDbService.cancelOnKeySchemaMismatch(transactItems, region); + dynamoDbService.validateTransactMemberKeysAndSizes(transactItems, region); } catch (TransactionCanceledException e) { return transactWriteCanceled(e); } diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbItemSizeServiceTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbItemSizeServiceTest.java index b961a0027b..781c0b0dc6 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbItemSizeServiceTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbItemSizeServiceTest.java @@ -18,7 +18,6 @@ import org.junit.jupiter.params.provider.CsvSource; import java.util.Base64; import java.util.List; -import java.util.function.IntFunction; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -31,20 +30,7 @@ class DynamoDbItemSizeServiceTest { private static final int MAX_ITEM_SIZE = 400 * 1024; private static final String UPDATE_EXCEEDED = "Item size to update has exceeded the maximum allowed size"; - private static final int UPDATE_COST = 3; - private static final int SET_OR_ADD_COST = 19; - private static final int REMOVE_OR_DELETE_COST = 1; - private static final int LIST_INDEX_COST = 1; - private static final int OPERAND_PATH_COST = 1; - private static final int OPERAND_PATH_ELEMENT_COST = 14; - private static final int PLUS_COST = 34; - private static final int MINUS_COST = 37; - private static final int LIST_APPEND_COST = 37; - private static final int IF_NOT_EXISTS_COST = 39; private static final int CONTAINER_COST = 3; - private static final int TARGET_CONTAINER_COST = 4; - // "pk" plus a one-byte value, short enough that the ceiling falls below 400KB. - private static final int SHORT_KEY_BYTES = 3; private DynamoDbService service; private NativeDynamoDbJsonHandler handler; @@ -112,12 +98,114 @@ class DynamoDbItemSizeServiceTest { } @Test - void updateItemSitsBelowTheLimitAtAShortKey() { - int ceiling = MAX_ITEM_SIZE + SHORT_KEY_BYTES - (UPDATE_COST + SET_OR_ADD_COST); + void updateItemAcceptsAFinishedItemOfExactlyTheLimitAtAShortKey() { + update("a", "SET b = :pad", MAX_ITEM_SIZE, 0); + assertEquals(MAX_ITEM_SIZE, storedBytes("a")); + assertRefused(() -> update("b", "SET b = :pad", MAX_ITEM_SIZE + 1, 0)); + } - update("a", "SET b = :pad", ceiling, 0); - assertEquals(ceiling, storedBytes("a")); - assertRefused(() -> update("b", "SET b = :pad", ceiling + 1, 0)); + @Test + void updateItemCountsATargetNameAndEachValueTheOperandUses() { + assertStatementCeiling(withC(), "SET c = if_not_exists(c, :v)", null, null, 1); + } + + @Test + void updateItemCountsEveryNameOfADocumentPath() { + assertStatementCeiling(withC("d", mapValue("leaf", stringValue("x"))), + "SET d.leaf = if_not_exists(d.leaf, :v)", null, null, "d".length() + "leaf".length()); + ObjectNode nested = mapValue("e", mapValue("leaf", stringValue("x"))); + assertStatementCeiling(withC("d", nested), + "SET d.e.leaf = if_not_exists(d.e.leaf, :v)", null, null, "d".length() + "e".length() + "leaf".length()); + } + + @Test + void updateItemCountsAListIndexAsZero() { + ObjectNode list = listValue(); + for (int i = 0; i < 11; i++) { + ((ArrayNode) list.get("L")).add(stringValue("x")); + } + assertStatementCeiling(withC("l", list), "SET l[0] = if_not_exists(l[0], :v)", null, null, "l".length()); + assertStatementCeiling(withC("l", list), "SET l[10] = if_not_exists(l[10], :v)", null, null, "l".length()); + } + + @Test + void updateItemDoesNotMergeTargetPathsThatShareAPrefix() { + ObjectNode map = JsonNodeFactory.instance.objectNode(); + map.putObject("M").set("a", stringValue("x")); + ((ObjectNode) map.get("M")).set("b", stringValue("y")); + assertStatementCeiling(withC("d", map), + "SET d.a = if_not_exists(d.a, :v), d.b = if_not_exists(d.b, :w)", null, + values(":w", stringValue("y")), + "d".length() + "a".length() + "d".length() + "b".length() + "y".length()); + } + + @Test + void updateItemResolvesAliasesInATargetPath() { + assertStatementCeiling(withC("d", mapValue("leafleafle", stringValue("x"))), + "SET #d.#l = if_not_exists(#d.#l, :v)", names("#d", "d", "#l", "leafleafle"), null, + "d".length() + "leafleafle".length()); + } + + @Test + void updateItemCountsTheValueAnAddWritesButNotADelete() { + ObjectNode members = values(":w", stringSetValue("z".repeat(100000))); + ObjectNode seed = withC("s", stringSetValue("q")); + assertStatementCeiling(seed, "SET c = if_not_exists(c, :v) ADD s :w", null, members, 1 + 1 + 100000); + assertStatementCeiling(seed, "SET c = if_not_exists(c, :v) DELETE s :w", null, members, 1); + } + + @Test + void updateItemDoesNotCountARemovePath() { + assertStatementCeiling(withC(), "SET c = if_not_exists(c, :v) REMOVE #r", names("#r", "r".repeat(1000)), + null, 1); + } + + @Test + void updateItemCountsTheNameAndNumberBytesOfAnAdd() { + assertStatementCeiling(withC(), "SET c = if_not_exists(c, :v) ADD #m :w", names("#m", "m".repeat(1000)), + values(":w", numberValue("12345678901234567890")), 1 + 1000 + 11); + } + + @Test + void updateItemCountsEachValueOfAnArithmeticOperand() { + ObjectNode two = values(":one", numberValue("1")); + two.set(":two", numberValue("2")); + assertStatementCeiling(withC(), "SET c = if_not_exists(c, :v), n = :one + :two", null, two, + 1 + 1 + 2 + 2); + assertStatementCeiling(withC("n", numberValue("1")), "SET c = if_not_exists(c, :v), n = n + :two", null, + values(":two", numberValue("2")), 1 + 1 + 2); + assertStatementCeiling(withC(), "SET c = if_not_exists(c, :v), n = if_not_exists(n, :two) + :two", null, + values(":two", numberValue("2")), 1 + 1 + 2 + 2); + } + + @Test + void updateItemCountsEachValueOfAListAppend() { + ObjectNode lists = values(":a", listValue(stringValue("aaaa"))); + lists.set(":b", listValue(stringValue("bbbb"))); + assertStatementCeiling(withC(), "SET c = if_not_exists(c, :v), l = list_append(:a, :b)", null, lists, + 1 + 1 + 8 + 8); + } + + @Test + void updateItemDoesNotCountAnOperandPath() { + assertStatementCeiling(withC("e", stringValue("e".repeat(100000))), "SET c = if_not_exists(c, :v), d = e", + null, null, 1 + 1); + } + + @Test + void updateItemCountsAValueOncePerUse() { + assertStatementCeiling(withC(), "SET c = if_not_exists(c, :v), d = if_not_exists(d, :v)", null, null, + 1 + 1, 2); + } + + @Test + void updateItemDoesNotCountAValueUsedOnlyInTheCondition() { + seed("a", "c", stringValue("x")); + + service.updateItem(TABLE, key("a"), null, "SET b = :s", null, + values(":s", stringValue("y")).set(":v", stringValue("h".repeat(MAX_ITEM_SIZE + 300))), + "NONE", "c <> :v", REGION, "NONE"); + assertEquals("y", service.getItem(TABLE, key("a"), REGION).get("b").get("S").asText()); } @Test @@ -129,87 +217,6 @@ class DynamoDbItemSizeServiceTest { assertRefused(() -> update("K".repeat(100), "SET b = :pad", MAX_ITEM_SIZE + 1, 0)); } - @Test - void updateItemChargesNineteenBytesForASecondSetClause() { - int ceiling = MAX_ITEM_SIZE + SHORT_KEY_BYTES - (UPDATE_COST + SET_OR_ADD_COST * 2); - ObjectNode second = values(":c", stringValue("y")); - - update("a", "SET b = :pad, c = :c", ceiling, 2, second); - assertEquals(ceiling, storedBytes("a")); - assertRefused(() -> update("b", "SET b = :pad, c = :c", ceiling + 1, 2, second)); - } - - @Test - void updateItemChargesNineteenBytesForAnAdd() { - int ceiling = MAX_ITEM_SIZE + SHORT_KEY_BYTES - (UPDATE_COST + SET_OR_ADD_COST * 2); - ObjectNode one = values(":one", numberValue("1")); - int numberBytes = "n".length() + 2; - - update("a", "SET b = :pad ADD n :one", ceiling, numberBytes, one); - assertEquals(ceiling, storedBytes("a")); - assertRefused(() -> update("b", "SET b = :pad ADD n :one", ceiling + 1, numberBytes, one)); - } - - @Test - void updateItemChargesTwoBytesForARemoveAlongsideASet() { - int ceiling = MAX_ITEM_SIZE + SHORT_KEY_BYTES - - (UPDATE_COST + SET_OR_ADD_COST + REMOVE_OR_DELETE_COST + "r".length()); - seed("a", "r", stringValue("z")); - seed("b", "r", stringValue("z")); - - update("a", "SET b = :pad REMOVE r", ceiling, 0); - assertEquals(ceiling, storedBytes("a")); - assertRefused(() -> update("b", "SET b = :pad REMOVE r", ceiling + 1, 0)); - } - - @Test - void updateItemChargesTwoBytesForADeleteAlongsideASet() { - int ceiling = MAX_ITEM_SIZE + SHORT_KEY_BYTES - - (UPDATE_COST + SET_OR_ADD_COST + REMOVE_OR_DELETE_COST + "s".length()); - ObjectNode members = values(":members", stringSetValue("z")); - seed("a", "s", stringSetValue("z")); - seed("b", "s", stringSetValue("z")); - - update("a", "SET b = :pad DELETE s :members", ceiling, 0, members); - assertEquals(ceiling, storedBytes("a")); - assertRefused(() -> update("b", "SET b = :pad DELETE s :members", ceiling + 1, 0, members)); - } - - @Test - void updateItemChargesADocumentPathLikeAPlainSet() { - int ceiling = MAX_ITEM_SIZE + SHORT_KEY_BYTES - (UPDATE_COST + SET_OR_ADD_COST); - int mapBytes = "leaf".length() + 1 + 3; - seed("a", "d", mapValue("leaf", stringValue("x"))); - seed("b", "d", mapValue("leaf", stringValue("x"))); - - update("a", "SET d.leaf = :pad", ceiling, mapBytes); - assertEquals(ceiling, storedBytes("a")); - assertRefused(() -> update("b", "SET d.leaf = :pad", ceiling + 1, mapBytes)); - } - - @Test - void updateItemChargesOneMoreByteThroughAListIndex() { - int ceiling = MAX_ITEM_SIZE + SHORT_KEY_BYTES - - (UPDATE_COST + SET_OR_ADD_COST + LIST_INDEX_COST); - int elementBytes = CONTAINER_COST + 1; - seed("a", "d", listValue(stringValue("x"))); - seed("b", "d", listValue(stringValue("x"))); - - update("a", "SET d[0] = :pad", ceiling, elementBytes); - assertEquals(ceiling, storedBytes("a")); - assertRefused(() -> update("b", "SET d[0] = :pad", ceiling + 1, elementBytes)); - } - - @Test - void updateItemChargesIfNotExistsAndTheOperandsItReads() { - int ceiling = MAX_ITEM_SIZE + SHORT_KEY_BYTES - - (UPDATE_COST + SET_OR_ADD_COST + IF_NOT_EXISTS_COST + operandPath("b")); - - update("a", "SET b = if_not_exists(b, :pad)", ceiling, 0); - assertEquals(ceiling, storedBytes("a")); - assertRefused(() -> update("b", "SET b = if_not_exists(b, :pad)", ceiling + 1, 0)); - } - @ParameterizedTest @CsvSource({ "'SET c = if_not_exists(c, :huge)', attribute_exists(nope)", @@ -263,16 +270,14 @@ class DynamoDbItemSizeServiceTest { } @Test - void updateItemDoesNotChargeForAnAttributeItLeavesAlone() { + void updateItemCountsAnUntouchedAttributeInTheFinishedItem() { int untouchedBytes = 1 + 10; // "u" plus its value - int ceiling = MAX_ITEM_SIZE + SHORT_KEY_BYTES + untouchedBytes - - (UPDATE_COST + SET_OR_ADD_COST); seed("a", "u", stringValue("y".repeat(10))); seed("b", "u", stringValue("y".repeat(10))); - update("a", "SET b = :pad", ceiling, untouchedBytes); - assertEquals(ceiling, storedBytes("a")); - assertRefused(() -> update("b", "SET b = :pad", ceiling + 1, untouchedBytes)); + update("a", "SET b = :pad", MAX_ITEM_SIZE, untouchedBytes); + assertEquals(MAX_ITEM_SIZE, storedBytes("a")); + assertRefused(() -> update("b", "SET b = :pad", MAX_ITEM_SIZE + 1, untouchedBytes)); } @Test @@ -352,121 +357,8 @@ class DynamoDbItemSizeServiceTest { assertEquals(before, service.getItem(TABLE, key("a"), REGION)); } - @Test - void updateItemChargesListAppendAndTheOperandsItReads() { - int fixed = UPDATE_COST + SET_OR_ADD_COST + "l".length() - + LIST_APPEND_COST + operandPath("l") + CONTAINER_COST + 1; - - assertUpdateCeiling(attributes("l", listValue(stringValue("x"))), "SET l = list_append(l, :list)", - pad -> values(":list", listValue(stringValue("x".repeat(pad)))), MAX_ITEM_SIZE - fixed); - } - - @Test - void updateItemChargesIfNotExistsNestedInListAppend() { - int fixed = UPDATE_COST + SET_OR_ADD_COST + "l".length() + LIST_APPEND_COST - + IF_NOT_EXISTS_COST + operandPath("l") + CONTAINER_COST + CONTAINER_COST + 1; - - assertUpdateCeiling(null, "SET l = list_append(if_not_exists(l, :empty), :list)", pad -> { - ObjectNode values = values(":list", listValue(stringValue("x".repeat(pad)))); - values.set(":empty", listValue()); - return values; - }, MAX_ITEM_SIZE - fixed); - } - - @Test - void updateItemChargesTheSourcePathOfACopy() { - int fixed = UPDATE_COST + 2 * SET_OR_ADD_COST + "a".length() + operandPath("b") + "c".length(); - - assertUpdateCeiling(attributes("b", stringValue("y")), "SET a = b, c = :pad", - pad -> values(":pad", stringValue("x".repeat(pad))), MAX_ITEM_SIZE - fixed); - } - - @Test - void updateItemChargesEveryElementOfANestedSourcePath() { - ObjectNode list = listValue(); - for (int i = 0; i < 11; i++) { - ((ArrayNode) list.get("L")).add(stringValue("x")); - } - int fixed = UPDATE_COST + 2 * SET_OR_ADD_COST + "a".length() + operandPath("d", "ee", "10") + "c".length(); - - assertUpdateCeiling(attributes("d", mapValue("ee", list)), "SET a = d.ee[10], c = :pad", - pad -> values(":pad", stringValue("x".repeat(pad))), MAX_ITEM_SIZE - fixed); - } - - @Test - void updateItemChargesPlusAndMinusDifferently() { - int one = 2; - int fixed = UPDATE_COST + 3 * SET_OR_ADD_COST - + "n".length() + PLUS_COST + operandPath("n") + one - + "m".length() + MINUS_COST + operandPath("m") + one - + "c".length(); - ObjectNode seed = attributes("n", numberValue("1")); - seed.set("m", numberValue("1")); - - assertUpdateCeiling(seed, "SET n = n + :one, m = m - :one, c = :pad", pad -> { - ObjectNode values = values(":pad", stringValue("x".repeat(pad))); - values.set(":one", numberValue("1")); - return values; - }, MAX_ITEM_SIZE - fixed); - } - - @Test - void updateItemCountsASharedTargetPrefixOnce() { - int fixed = UPDATE_COST + 2 * SET_OR_ADD_COST - + "d".length() + TARGET_CONTAINER_COST + "a".length() + "b".length() + "e".length(); - - assertUpdateCeiling(attributes("d", JsonNodeFactory.instance.objectNode().set("M", - JsonNodeFactory.instance.objectNode())), "SET d.a = :pad, d.b = :e", pad -> { - ObjectNode values = values(":pad", stringValue("x".repeat(pad))); - values.set(":e", stringValue("e")); - return values; - }, MAX_ITEM_SIZE - fixed); - } - - @Test - void updateItemCountsTheDigitsOfAListIndex() { - ObjectNode list = listValue(); - for (int i = 0; i < 11; i++) { - ((ArrayNode) list.get("L")).add(stringValue("x")); - } - int fixed = UPDATE_COST + SET_OR_ADD_COST + "l".length() + TARGET_CONTAINER_COST + "10".length(); - - assertUpdateCeiling(attributes("l", list), "SET l[10] = :pad", - pad -> values(":pad", stringValue("x".repeat(pad))), MAX_ITEM_SIZE - fixed); - } - - @Test - void updateItemChargesRemoveAndDeleteByTheirPathAlone() { - ObjectNode seed = attributes("rrrrrrrrrr", stringValue("y")); - seed.set("ssssssssss", stringSetValue("y", "z")); - int fixed = UPDATE_COST + 2 * (REMOVE_OR_DELETE_COST + 10) + SET_OR_ADD_COST + "c".length(); - - assertUpdateCeiling(seed, "REMOVE rrrrrrrrrr DELETE ssssssssss :z SET c = :pad", pad -> { - ObjectNode values = values(":pad", stringValue("x".repeat(pad))); - values.set(":z", stringSetValue("z".repeat(100))); - return values; - }, MAX_ITEM_SIZE - fixed); - } - - @Test - void updateItemChargesTheValueAnAddWritesNotTheSetItBuilds() { - int fixed = UPDATE_COST + 2 * SET_OR_ADD_COST + "ss".length() + 1 + "c".length(); - - assertUpdateCeiling(attributes("ss", stringSetValue("yy")), "ADD ss :v SET c = :pad", pad -> { - ObjectNode values = values(":pad", stringValue("x".repeat(pad))); - values.set(":v", stringSetValue("z")); - return values; - }, MAX_ITEM_SIZE - fixed); - } - private void update(String keyValue, String expression, int totalBytes, int otherBytes) { - update(keyValue, expression, totalBytes, otherBytes, JsonNodeFactory.instance.objectNode()); - } - - private void update(String keyValue, String expression, int totalBytes, int otherBytes, - ObjectNode extraValues) { - ObjectNode values = extraValues.deepCopy(); - values.set(":pad", stringValue(padding(keyValue, totalBytes, otherBytes))); + ObjectNode values = values(":pad", stringValue(padding(keyValue, totalBytes, otherBytes))); service.updateItem(TABLE, key(keyValue), null, expression, null, values, "NONE", REGION); } @@ -511,26 +403,47 @@ class DynamoDbItemSizeServiceTest { service.putItem(TABLE, item, REGION); } - private void assertUpdateCeiling(ObjectNode seed, String expression, IntFunction values, - int maxPadding) { - for (String keyValue : List.of("a", "b")) { - if (seed != null) { - ObjectNode item = key(keyValue); - item.setAll(seed.deepCopy()); - service.putItem(TABLE, item, REGION); - } - } - service.updateItem(TABLE, key("a"), null, expression, null, values.apply(maxPadding), "NONE", REGION); - assertRefused(() -> service.updateItem(TABLE, key("b"), null, expression, null, - values.apply(maxPadding + 1), "NONE", REGION)); + private ObjectNode withC() { + return attributes("c", stringValue("x")); } - private static int operandPath(String... elements) { - int size = OPERAND_PATH_COST; - for (String element : elements) { - size += OPERAND_PATH_ELEMENT_COST + element.length(); + private ObjectNode withC(String name, JsonNode value) { + ObjectNode seed = withC(); + seed.set(name, value); + return seed; + } + + private ObjectNode names(String... aliasAndName) { + ObjectNode names = JsonNodeFactory.instance.objectNode(); + for (int i = 0; i < aliasAndName.length; i += 2) { + names.put(aliasAndName[i], aliasAndName[i + 1]); } - return size; + return names; + } + + private void assertStatementCeiling(ObjectNode seed, String expression, ObjectNode names, ObjectNode extra, + int fixedBytes) { + assertStatementCeiling(seed, expression, names, extra, fixedBytes, 1); + } + + private void assertStatementCeiling(ObjectNode seed, String expression, ObjectNode names, ObjectNode extra, + int fixedBytes, int vUses) { + int maxPad = (MAX_ITEM_SIZE - fixedBytes) / vUses; + for (String keyValue : List.of("a", "b")) { + ObjectNode item = key(keyValue); + item.setAll(seed.deepCopy()); + service.putItem(TABLE, item, REGION); + } + service.updateItem(TABLE, key("a"), null, expression, names, statementValues(extra, maxPad), + "NONE", REGION); + assertRefused(() -> service.updateItem(TABLE, key("b"), null, expression, names, + statementValues(extra, maxPad + 1), "NONE", REGION)); + } + + private ObjectNode statementValues(ObjectNode extra, int pad) { + ObjectNode values = extra == null ? JsonNodeFactory.instance.objectNode() : extra.deepCopy(); + values.set(":v", stringValue("x".repeat(pad))); + return values; } private ObjectNode attributes(String name, JsonNode value) { 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 f4042d9b82..f83005a88a 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandlerTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandlerTest.java @@ -4561,6 +4561,150 @@ class NativeDynamoDbJsonHandlerTest { + "cannot contain an empty string value. Key: userId", ex.getMessage()); } + private static final String UPDATE_SIZE_MESSAGE = "Item size to update has exceeded the maximum allowed size"; + private static final String PUT_SIZE_MESSAGE = "Item size has exceeded the maximum allowed size"; + private static final int ITEM_LIMIT = 400 * 1024; + + private ObjectNode transactStatementUpdate(String table, String userId, int valueLength) { + ObjectNode member = transactMember("Update", table, "Key", item("userId", userId)); + ObjectNode update = (ObjectNode) member.get("Update"); + update.put("UpdateExpression", "SET c = if_not_exists(c, :v)"); + update.set("ExpressionAttributeValues", + mapper.createObjectNode().set(":v", attributeValue("S", "v".repeat(valueLength)))); + return member; + } + + private ObjectNode transactOversizedPut(String userId) { + return transactMember("Put", "Users", "Item", item("userId", userId, "b", "b".repeat(ITEM_LIMIT))); + } + + private ObjectNode transactWrongTypeDelete() { + ObjectNode key = mapper.createObjectNode(); + key.set("userId", attributeValue("N", "5")); + return transactMember("Delete", "Users", "Key", key); + } + + private void seedUserWithC(String userId) { + service.putItem("Users", item("userId", userId, "c", "x"), "eu-west-1"); + } + + private void assertTransactWriteRefused(String code, String message, ObjectNode... members) { + ObjectNode request = transactWriteOf(members); + AwsException ex = assertThrows(AwsException.class, + () -> handler.handle("TransactWriteItems", request, "eu-west-1")); + assertEquals(code, ex.getErrorCode()); + assertEquals(message, ex.getMessage()); + } + + @Test + void transactWriteItemsRefusesAnOversizedStatementBeforeAFailingConditionAndLeavesItemsAlone() { + createUsersTable("eu-west-1"); + seedUserWithC("u1"); + ObjectNode check = transactMember("ConditionCheck", "Users", "Key", item("userId", "u9")); + ((ObjectNode) check.get("ConditionCheck")).put("ConditionExpression", "attribute_exists(userId)"); + + assertTransactWriteRefused("ValidationException", UPDATE_SIZE_MESSAGE, + check, transactStatementUpdate("Users", "u1", ITEM_LIMIT)); + assertEquals(item("userId", "u1", "c", "x"), service.getItem("Users", item("userId", "u1"), "eu-west-1")); + } + + @Test + void transactWriteItemsAcceptsAStatementOfExactlyTheLimit() throws Exception { + createUsersTable("eu-west-1"); + seedUserWithC("u1"); + + Response response = handler.handle("TransactWriteItems", + transactWriteOf(transactStatementUpdate("Users", "u1", ITEM_LIMIT - 1)), "eu-west-1"); + + assertEquals(200, response.getStatus()); + } + + @Test + void transactWriteItemsAnswersResourceNotFoundForALaterMissingTableBeforeAnOversizedStatement() { + createUsersTable("eu-west-1"); + seedUserWithC("u1"); + + assertTransactWriteRefused("ResourceNotFoundException", "Requested resource not found", + transactStatementUpdate("Users", "u1", ITEM_LIMIT), transactStatementUpdate("Nope", "u1", 1)); + } + + @Test + void transactWriteItemsAnswersResourceNotFoundForALaterMissingTableBeforeAKeyMismatch() { + createUsersTable("eu-west-1"); + + assertTransactWriteRefused("ResourceNotFoundException", "Requested resource not found", + transactWrongTypeDelete(), transactStatementUpdate("Nope", "u1", 1)); + } + + @Test + void transactWriteItemsCancelsOnAKeyMismatchBeforeALaterOversizedStatement() throws Exception { + createUsersTable("eu-west-1"); + seedUserWithC("u1"); + + Response response = handler.handle("TransactWriteItems", + transactWriteOf(transactWrongTypeDelete(), transactStatementUpdate("Users", "u1", ITEM_LIMIT)), + "eu-west-1"); + + assertEquals(400, response.getStatus()); + JsonNode body = mapper.convertValue(response.getEntity(), JsonNode.class); + assertEquals("Transaction cancelled, please refer cancellation reasons for specific reasons " + + "[ValidationError, None]", body.get("message").asText()); + } + + @Test + void transactWriteItemsRefusesAnOversizedStatementBeforeALaterKeyMismatch() { + createUsersTable("eu-west-1"); + seedUserWithC("u1"); + + assertTransactWriteRefused("ValidationException", UPDATE_SIZE_MESSAGE, + transactStatementUpdate("Users", "u1", ITEM_LIMIT), transactWrongTypeDelete()); + } + + @Test + void transactWriteItemsReportsTheFirstOversizedMemberWhenAPutAndAnUpdateBothOverflow() { + createUsersTable("eu-west-1"); + seedUserWithC("u1"); + + assertTransactWriteRefused("ValidationException", PUT_SIZE_MESSAGE, + transactOversizedPut("u2"), transactStatementUpdate("Users", "u1", ITEM_LIMIT)); + assertTransactWriteRefused("ValidationException", UPDATE_SIZE_MESSAGE, + transactStatementUpdate("Users", "u1", ITEM_LIMIT), transactOversizedPut("u2")); + } + + @Test + void transactWriteItemsRefusesAnOversizedPutBeforeItsFailingCondition() { + createUsersTable("eu-west-1"); + ObjectNode put = transactOversizedPut("u1"); + ((ObjectNode) put.get("Put")).put("ConditionExpression", "attribute_exists(userId)"); + + assertTransactWriteRefused("ValidationException", PUT_SIZE_MESSAGE, put); + } + + @Test + void transactWriteItemsRefusesAnOversizedPutBeforeItsMissingKey() { + createUsersTable("eu-west-1"); + + assertTransactWriteRefused("ValidationException", PUT_SIZE_MESSAGE, + transactMember("Put", "Users", "Item", item("b", "b".repeat(ITEM_LIMIT)))); + } + + @Test + void transactWriteItemsRefusesAnOversizedMemberBeforeTheDuplicateItemCheck() { + createUsersTable("eu-west-1"); + seedUserWithC("u1"); + ObjectNode check = transactMember("ConditionCheck", "Users", "Key", item("userId", "u1")); + ((ObjectNode) check.get("ConditionCheck")).put("ConditionExpression", "attribute_exists(userId)"); + ObjectNode update = transactMember("Update", "Users", "Key", item("userId", "u1")); + ((ObjectNode) update.get("Update")).put("UpdateExpression", "SET c = :v"); + ((ObjectNode) update.get("Update")).set("ExpressionAttributeValues", + mapper.createObjectNode().set(":v", attributeValue("S", "v"))); + + assertTransactWriteRefused("ValidationException", PUT_SIZE_MESSAGE, + transactOversizedPut("u1"), update, check); + assertTransactWriteRefused("ValidationException", UPDATE_SIZE_MESSAGE, + transactStatementUpdate("Users", "u1", ITEM_LIMIT), check); + } + @Test void transactWriteItemsCancelsOnAPutIndexKeyOfTheWrongType() throws Exception { createProvisionedTableWithGsi("Movies", "eu-west-1");