fix(dynamodb): enforce the 400KB item limit on every update surface (#3991)

* fix(dynamodb): enforce the 400KB item limit on every update surface

* docs(dynamodb): correct the update size exception javadoc
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-09-20 10:08:50 -04:00
1 parent 748f71c943
commit 3958be1d0e
6 files changed
+460 -23

No files matched your search

@@ -5,6 +5,10 @@ import io.github.hectorvent.floci.core.common.AwsException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* Calculates DynamoDB item size and enforces the 400KB limit.
@@ -13,6 +17,15 @@ final class DynamoDbItemSize {
static final int MAX_ITEM_SIZE = 400 * 1024; // 400 KB = 409,600 bytes
static final String UPDATE_EXCEEDED = "Item size to update has exceeded the maximum allowed size";
// UpdateItem measures what the statement writes, name and value, not the item it stores,
// and charges these on top. Every other surface measures 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 = 2;
private static final int LIST_INDEX_COST = 1;
private DynamoDbItemSize() {}
/**
@@ -26,6 +39,69 @@ final class DynamoDbItemSize {
}
}
static boolean updatedItemWithinLimit(JsonNode item) {
return calculateItemSize(item) <= MAX_ITEM_SIZE;
}
static boolean updateItemWithinLimit(JsonNode item, Set<String> writtenAttributes, int actionCost) {
int total = 0;
int written = 0;
Iterator<Map.Entry<String, JsonNode>> fields = item.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> entry = fields.next();
int size = utf8Length(entry.getKey()) + attributeValueSize(entry.getValue());
total += size;
if (writtenAttributes.contains(entry.getKey())) {
written += size;
}
}
return total <= MAX_ITEM_SIZE && written + actionCost <= MAX_ITEM_SIZE;
}
static int updateExpressionCost(String expression) {
int cost = UPDATE_COST;
String remaining = expression.trim().replaceAll("\\s+", " ");
while (!remaining.isEmpty()) {
String keyword = remaining.substring(0, Math.max(remaining.indexOf(' '), 0)).toUpperCase(Locale.ROOT);
String body = remaining.substring(keyword.length()).trim();
int nextClause = DynamoDbService.findNextClauseKeyword(body);
String actions = nextClause < 0 ? body : body.substring(0, nextClause);
remaining = nextClause < 0 ? "" : body.substring(nextClause);
while (!actions.isBlank()) {
int comma = DynamoDbService.findNextComma(actions);
cost += actionCost(keyword, comma < 0 ? actions : actions.substring(0, comma));
actions = comma < 0 ? "" : actions.substring(comma + 1);
}
}
return cost;
}
static int attributeUpdatesCost(JsonNode attributeUpdates) {
int cost = UPDATE_COST;
if (attributeUpdates == null || !attributeUpdates.isObject()) {
return cost;
}
for (JsonNode update : attributeUpdates) {
cost += "DELETE".equals(update.path("Action").asText("PUT"))
? REMOVE_OR_DELETE_COST : SET_OR_ADD_COST;
}
return cost;
}
private static int actionCost(String clause, String action) {
return switch (clause) {
case "SET" -> SET_OR_ADD_COST + (writesListElement(action) ? LIST_INDEX_COST : 0);
case "ADD" -> SET_OR_ADD_COST;
default -> REMOVE_OR_DELETE_COST;
};
}
private static boolean writesListElement(String action) {
int bracket = action.indexOf('[');
int assignment = action.indexOf('=');
return bracket >= 0 && (assignment < 0 || bracket < assignment);
}
static int calculateItemSize(JsonNode item) {
if (item == null || !item.isObject()) return 0;
int total = 0;
@@ -504,7 +504,8 @@ class DynamoDbPartiQLHandler {
DynamoDbService.UpdateResult result = service.updateItem(stmt.table(), key, null, ue,
ean.isEmpty() ? null : ean.toNode(mapper),
eav.isEmpty() ? null : eav.toNode(mapper), returnValues, ce, region, "NONE");
eav.isEmpty() ? null : eav.toNode(mapper), returnValues, ce, region, "NONE",
UpdateSizeRule.FINISHED_ITEM);
return itemsResponse(returnedAttributes(stmt.returning(), result));
}
@@ -781,20 +781,20 @@ public class DynamoDbService implements ResourceProvider {
JsonNode expressionAttrNames, JsonNode expressionAttrValues,
String returnValues, String conditionExpression, String region,
String returnValuesOnConditionCheckFailure) {
return updateItemInternal(tableName, key, attributeUpdates, updateExpression,
expressionAttrNames, expressionAttrValues, returnValues,
conditionExpression, region, returnValuesOnConditionCheckFailure, true);
return updateItem(tableName, key, attributeUpdates, updateExpression, expressionAttrNames,
expressionAttrValues, returnValues, conditionExpression, region,
returnValuesOnConditionCheckFailure, UpdateSizeRule.UPDATE_ITEM);
}
private UpdateResult updateItemInternal(String tableName, JsonNode key, JsonNode attributeUpdates,
String updateExpression,
JsonNode expressionAttrNames, JsonNode expressionAttrValues,
String returnValues, String conditionExpression, String region,
String returnValuesOnConditionCheckFailure,
boolean shouldPersist) {
UpdateResult updateItem(String tableName, JsonNode key, JsonNode attributeUpdates,
String updateExpression,
JsonNode expressionAttrNames, JsonNode expressionAttrValues,
String returnValues, String conditionExpression, String region,
String returnValuesOnConditionCheckFailure,
UpdateSizeRule sizeRule) {
return updateItemInternal(tableName, key, attributeUpdates, updateExpression,
expressionAttrNames, expressionAttrValues, returnValues,
conditionExpression, region, returnValuesOnConditionCheckFailure, shouldPersist, null);
conditionExpression, region, returnValuesOnConditionCheckFailure, true, sizeRule);
}
private UpdateResult updateItemInternal(String tableName, JsonNode key, JsonNode attributeUpdates,
@@ -803,11 +803,11 @@ public class DynamoDbService implements ResourceProvider {
String returnValues, String conditionExpression, String region,
String returnValuesOnConditionCheckFailure,
boolean shouldPersist,
Consumer<Runnable> deferredStreamEvents) {
UpdateSizeRule sizeRule) {
return updateItemInternal(tableName, key, attributeUpdates, updateExpression,
expressionAttrNames, expressionAttrValues, returnValues,
conditionExpression, region, returnValuesOnConditionCheckFailure, shouldPersist,
deferredStreamEvents, null);
conditionExpression, region, returnValuesOnConditionCheckFailure, shouldPersist, null,
sizeRule);
}
private UpdateResult updateItemInternal(String tableName, JsonNode key, JsonNode attributeUpdates,
@@ -817,7 +817,22 @@ public class DynamoDbService implements ResourceProvider {
String returnValuesOnConditionCheckFailure,
boolean shouldPersist,
Consumer<Runnable> deferredStreamEvents,
Map<String, ConcurrentSkipListMap<String, JsonNode>> stagedItems) {
UpdateSizeRule sizeRule) {
return updateItemInternal(tableName, key, attributeUpdates, updateExpression,
expressionAttrNames, expressionAttrValues, returnValues,
conditionExpression, region, returnValuesOnConditionCheckFailure, shouldPersist,
deferredStreamEvents, null, sizeRule);
}
private UpdateResult updateItemInternal(String tableName, JsonNode key, JsonNode attributeUpdates,
String updateExpression,
JsonNode expressionAttrNames, JsonNode expressionAttrValues,
String returnValues, String conditionExpression, String region,
String returnValuesOnConditionCheckFailure,
boolean shouldPersist,
Consumer<Runnable> deferredStreamEvents,
Map<String, ConcurrentSkipListMap<String, JsonNode>> stagedItems,
UpdateSizeRule sizeRule) {
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
var table = requireActiveTable(storageKey, canonicalTableName);
@@ -928,6 +943,16 @@ public class DynamoDbService implements ResourceProvider {
// AWS validates index key values against the item the update produces.
validateIndexKeyTypes(table, item, true);
if (sizeRule == UpdateSizeRule.UPDATE_ITEM) {
requireUpdateItemWithinSizeLimit(item,
writtenAttributes(touchedPaths, updateExpression, expressionAttrNames),
updateExpression != null
? DynamoDbItemSize.updateExpressionCost(updateExpression)
: DynamoDbItemSize.attributeUpdatesCost(attributeUpdates));
} else {
requireUpdatedItemWithinSizeLimit(item);
}
items.put(itemKey, item);
if (shouldPersist) {
persistItems(storageKey);
@@ -953,9 +978,9 @@ public class DynamoDbService implements ResourceProvider {
streamEvent.run();
}
var touched = new ArrayList<TouchedPath>();
for (var path : touchedPaths) {
var tokens = updateExpression != null ? parsePath(path, expressionAttrNames) : List.<Object>of(path);
List<TouchedPath> touched = new ArrayList<>();
for (String path : touchedPaths) {
List<Object> tokens = pathTokens(path, updateExpression, expressionAttrNames);
touched.add(new TouchedPath(tokens,
existing == null ? null : valueAtTokens(existing, tokens), valueAtTokens(item, tokens)));
}
@@ -963,6 +988,22 @@ public class DynamoDbService implements ResourceProvider {
});
}
private List<Object> pathTokens(String path, String updateExpression, JsonNode expressionAttrNames) {
return updateExpression != null ? parsePath(path, expressionAttrNames) : List.<Object>of(path);
}
private Set<String> writtenAttributes(List<String> touchedPaths, String updateExpression,
JsonNode expressionAttrNames) {
Set<String> names = new LinkedHashSet<>();
for (String path : touchedPaths) {
List<Object> tokens = pathTokens(path, updateExpression, expressionAttrNames);
if (!tokens.isEmpty() && tokens.get(0) instanceof String name) {
names.add(name);
}
}
return names;
}
public QueryResult query(String tableName, JsonNode keyConditions,
JsonNode expressionAttrValues, String keyConditionExpression,
String filterExpression, Integer limit, String region) {
@@ -1468,7 +1509,8 @@ public class DynamoDbService implements ResourceProvider {
for (int i = 0; i < transactItems.size(); i++) {
try {
validateTransactItem(transactItems.get(i), region, staged);
} catch (KeySchemaMismatchException | ItemNestingExceededException e) {
} catch (KeySchemaMismatchException | ItemNestingExceededException
| UpdatedItemTooLargeException e) {
throw cancelledByMember(transactItems.size(), i, e.getMessage());
}
}
@@ -1495,7 +1537,8 @@ public class DynamoDbService implements ResourceProvider {
upd.has("UpdateExpression") ? upd.get("UpdateExpression").asText() : null,
upd.has("ExpressionAttributeNames") ? upd.get("ExpressionAttributeNames") : null,
upd.has("ExpressionAttributeValues") ? upd.get("ExpressionAttributeValues") : null,
"NONE", null, region, "NONE", false, pendingStreamEvents::add, staged);
"NONE", null, region, "NONE", false, pendingStreamEvents::add, staged,
UpdateSizeRule.FINISHED_ITEM);
affectedStorageKeys.add(storageKey);
}
}
@@ -1754,6 +1797,20 @@ public class DynamoDbService implements ResourceProvider {
validateKeyNotModified(table, key, item);
requireItemNestingWithinLimit(item);
validateIndexKeyTypes(table, item, true);
requireUpdatedItemWithinSizeLimit(item);
}
}
private static void requireUpdatedItemWithinSizeLimit(JsonNode item) {
if (!DynamoDbItemSize.updatedItemWithinLimit(item)) {
throw new UpdatedItemTooLargeException();
}
}
private static void requireUpdateItemWithinSizeLimit(JsonNode item, Set<String> writtenAttributes,
int actionCost) {
if (!DynamoDbItemSize.updateItemWithinLimit(item, writtenAttributes, actionCost)) {
throw new UpdatedItemTooLargeException();
}
}
@@ -3085,7 +3142,7 @@ public class DynamoDbService implements ResourceProvider {
}
}
private int findNextComma(String s) {
static int findNextComma(String s) {
// Find next comma that is not inside a function call
int depth = 0;
for (int i = 0; i < s.length(); i++) {
@@ -3097,7 +3154,7 @@ public class DynamoDbService implements ResourceProvider {
return -1;
}
private int findNextClauseKeyword(String s) {
static int findNextClauseKeyword(String s) {
// Find the start of the next clause keyword (SET, REMOVE, ADD, DELETE)
String upper = s.toUpperCase();
int[] positions = {
@@ -3115,7 +3172,7 @@ public class DynamoDbService implements ResourceProvider {
return min;
}
private int indexOfKeyword(String upper, String keyword) {
private static int indexOfKeyword(String upper, String keyword) {
// Find the next occurrence of keyword at a word boundary (start of string
// or preceded by whitespace). Loop past non-boundary hits so attribute
// names that contain a keyword as a substring (e.g. "oldSET" before a
@@ -0,0 +1,8 @@
package io.github.hectorvent.floci.services.dynamodb;
/** How a surface measures an update against the 400KB item limit. */
enum UpdateSizeRule {
UPDATE_ITEM,
FINISHED_ITEM
}
@@ -0,0 +1,11 @@
package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.core.common.AwsException;
/** An update over 400KB. A transact member carrying one cancels instead of failing up front. */
public class UpdatedItemTooLargeException extends AwsException {
public UpdatedItemTooLargeException() {
super("ValidationException", DynamoDbItemSize.UPDATE_EXCEEDED, 400);
}
}