mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(dynamodb): measure UpdateExpression size by target names and values (#9237)
DynamoDB no longer charges a fixed cost per UpdateExpression clause. UpdateItem caps the finished item at exactly 409,600 bytes, key included. It also refuses a statement whose SET and ADD actions add up to more than 409,600 bytes. Each action counts the names in its target path and every value its operand uses, once per use. REMOVE, DELETE, operand paths, functions and operators count nothing. TransactWriteItems applies the same statement check to an Update and answers a top-level ValidationException, as it does for an oversized Put. Every member's table is looked up first. Then the members are checked in order. A Put checks its item size, then its key. Other members check their key, then an Update checks its statement size. All of this comes before the duplicate item check and before any condition.
This commit is contained in:
1 parent
272f3f8435
commit
3c4efe43bf
5 files changed
+355
-318
No files matched your search
@@ -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<String, List<Object>> 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<String, List<Object>> 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<String, List<Object>> paths, JsonNode values) {
|
||||
private static int targetSize(List<Object> 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<String, List<Object>> 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<Object, PathTree> children = new LinkedHashMap<>();
|
||||
|
||||
void add(List<Object> path) {
|
||||
PathTree node = this;
|
||||
for (Object element : path) {
|
||||
node = node.children.computeIfAbsent(element, ignored -> new PathTree());
|
||||
}
|
||||
}
|
||||
|
||||
int size() {
|
||||
int size = 0;
|
||||
for (Map.Entry<Object, PathTree> 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));
|
||||
}
|
||||
|
||||
@@ -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<JsonNode> 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<JsonNode> 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<String> 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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2956,7 +2956,7 @@ public class NativeDynamoDbJsonHandler {
|
||||
List<JsonNode> transactItems = new ArrayList<>();
|
||||
transactItemsNode.forEach(transactItems::add);
|
||||
try {
|
||||
dynamoDbService.cancelOnKeySchemaMismatch(transactItems, region);
|
||||
dynamoDbService.validateTransactMemberKeysAndSizes(transactItems, region);
|
||||
} catch (TransactionCanceledException e) {
|
||||
return transactWriteCanceled(e);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user