mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(dynamodb): store map keys in code point order on plain API writes (#9227)
AWS sorts the keys of every map in a PutItem, BatchWriteItem or TransactWriteItems item and in update values. PartiQL literals keep their written order. An update sorts each map on its document path again. Step Functions dynamodb:putItem and dynamodb:updateItem tasks and IoT dynamoDBv2 rule actions are plain PutItem and UpdateItem calls on AWS, so their maps are stored in code point order too.
This commit is contained in:
1 parent
77c11493e7
commit
4d481ebccb
9 files changed
+705
-16
No files matched your search
@@ -0,0 +1,146 @@
|
||||
package io.floci.aws.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* DynamoDB stores the keys of a map, at any depth, in code point order when the value arrives
|
||||
* through the plain API. PartiQL literals keep the order they are written in. An update puts
|
||||
* the maps on its document path in code point order and leaves the others as they are.
|
||||
*/
|
||||
public final class DynamoDbMapOrder {
|
||||
|
||||
private static final JsonNodeFactory FACTORY = JsonNodeFactory.instance;
|
||||
|
||||
private DynamoDbMapOrder() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a copy of an item, or of a map of attribute values such as ExpressionAttributeValues,
|
||||
* with every nested map sorted. The top-level order is kept. Input holding no map is returned as is.
|
||||
*/
|
||||
public static JsonNode sortedItem(JsonNode item) {
|
||||
if (item == null || !item.isObject() || !holdsMap(item)) {
|
||||
return item;
|
||||
}
|
||||
return copyFields((ObjectNode) item, false);
|
||||
}
|
||||
|
||||
/** Returns a copy of a legacy AttributeUpdates map with every nested map of each Value sorted. */
|
||||
public static JsonNode sortedAttributeUpdates(JsonNode updates) {
|
||||
if (updates == null || !updates.isObject() || !holdsMap(updates)) {
|
||||
return updates;
|
||||
}
|
||||
ObjectNode sorted = FACTORY.objectNode();
|
||||
for (Map.Entry<String, JsonNode> entry : updates.properties()) {
|
||||
JsonNode update = entry.getValue();
|
||||
JsonNode value = update.get("Value");
|
||||
sorted.set(entry.getKey(), value != null && holdsMap(value)
|
||||
? withMember(update, "Value", copyValue(value)) : update);
|
||||
}
|
||||
return sorted;
|
||||
}
|
||||
|
||||
/** Returns a copy of {@code request} whose {@code operation.member} value has every nested map sorted. */
|
||||
static JsonNode withSortedMember(JsonNode request, String operation, String member) {
|
||||
JsonNode op = request.get(operation);
|
||||
if (op == null || !op.isObject()) {
|
||||
return request;
|
||||
}
|
||||
JsonNode value = op.get(member);
|
||||
JsonNode sorted = sortedItem(value);
|
||||
if (sorted == value) {
|
||||
return request;
|
||||
}
|
||||
return withMember(request, operation, withMember(op, member, sorted));
|
||||
}
|
||||
|
||||
/** Returns a shallow copy of {@code node} with {@code name} set to {@code value}. */
|
||||
private static ObjectNode withMember(JsonNode node, String name, JsonNode value) {
|
||||
ObjectNode copy = FACTORY.objectNode();
|
||||
copy.setAll((ObjectNode) node);
|
||||
copy.set(name, value);
|
||||
return copy;
|
||||
}
|
||||
|
||||
/** Puts the keys of one map in code point order, in place. Nested maps are not touched. */
|
||||
static void sortKeys(ObjectNode map) {
|
||||
if (map.size() < 2) {
|
||||
return;
|
||||
}
|
||||
List<String> names = names(map);
|
||||
List<String> sorted = DynamoDbSetOrder.byCodePoint(names);
|
||||
if (sorted.equals(names)) {
|
||||
return;
|
||||
}
|
||||
Map<String, JsonNode> fields = LinkedHashMap.newLinkedHashMap(names.size());
|
||||
for (Map.Entry<String, JsonNode> entry : map.properties()) {
|
||||
fields.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
map.removeAll();
|
||||
for (String name : sorted) {
|
||||
map.set(name, fields.get(name));
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> names(ObjectNode node) {
|
||||
List<String> names = new ArrayList<>(node.size());
|
||||
node.fieldNames().forEachRemaining(names::add);
|
||||
return names;
|
||||
}
|
||||
|
||||
private static boolean holdsMap(JsonNode node) {
|
||||
if (node.isArray()) {
|
||||
for (JsonNode element : node) {
|
||||
if (holdsMap(element)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (!node.isObject()) {
|
||||
return false;
|
||||
}
|
||||
for (Map.Entry<String, JsonNode> entry : node.properties()) {
|
||||
if ("M".equals(entry.getKey()) || holdsMap(entry.getValue())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static ObjectNode copyFields(ObjectNode node, boolean sortKeys) {
|
||||
List<String> names = names(node);
|
||||
Map<String, JsonNode> map = LinkedHashMap.newLinkedHashMap(names.size());
|
||||
for (String name : sortKeys ? DynamoDbSetOrder.byCodePoint(names) : names) {
|
||||
map.put(name, copyValue(node.get(name)));
|
||||
}
|
||||
return new ObjectNode(FACTORY, map);
|
||||
}
|
||||
|
||||
private static JsonNode copyValue(JsonNode value) {
|
||||
if (!value.isObject() || value.size() != 1) {
|
||||
return value;
|
||||
}
|
||||
JsonNode map = value.get("M");
|
||||
if (map != null && map.isObject()) {
|
||||
return FACTORY.objectNode().set("M", copyFields((ObjectNode) map, true));
|
||||
}
|
||||
JsonNode list = value.get("L");
|
||||
if (list != null && list.isArray()) {
|
||||
ArrayNode copy = FACTORY.arrayNode(list.size());
|
||||
for (JsonNode element : list) {
|
||||
copy.add(copyValue(element));
|
||||
}
|
||||
return FACTORY.objectNode().set("L", copy);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -4328,9 +4328,27 @@ public class DynamoDbService {
|
||||
}
|
||||
}
|
||||
|
||||
private void setValueAtPath(ObjectNode item, String path, JsonNode value, JsonNode exprAttrNames) {
|
||||
private static void setAndSort(ObjectNode map, String attr, JsonNode value) {
|
||||
map.set(attr, value);
|
||||
DynamoDbMapOrder.sortKeys(map);
|
||||
}
|
||||
|
||||
private static void removeAndSort(ObjectNode map, String attr) {
|
||||
map.remove(attr);
|
||||
DynamoDbMapOrder.sortKeys(map);
|
||||
}
|
||||
|
||||
private static void sortWalked(List<ObjectNode> maps) {
|
||||
for (ObjectNode map : maps) {
|
||||
DynamoDbMapOrder.sortKeys(map);
|
||||
}
|
||||
}
|
||||
|
||||
private void setValueAtPath(ObjectNode item, String path, JsonNode source, JsonNode exprAttrNames) {
|
||||
List<Object> tokens = parsePath(path, exprAttrNames);
|
||||
if (tokens.isEmpty()) return;
|
||||
// A map sorted later in place must not be shared with another attribute or a request value.
|
||||
JsonNode value = source.deepCopy();
|
||||
|
||||
if (tokens.size() == 1) {
|
||||
if (tokens.get(0) instanceof String attrName) {
|
||||
@@ -4340,6 +4358,7 @@ public class DynamoDbService {
|
||||
}
|
||||
|
||||
JsonNode container = item;
|
||||
List<ObjectNode> walked = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < tokens.size() - 1; i++) {
|
||||
Object tok = tokens.get(i);
|
||||
@@ -4361,7 +4380,8 @@ public class DynamoDbService {
|
||||
"The document path provided in the update expression is invalid for update",
|
||||
400);
|
||||
}
|
||||
((ObjectNode) child.get("M")).set(finalAttr, value);
|
||||
setAndSort((ObjectNode) child.get("M"), finalAttr, value);
|
||||
sortWalked(walked);
|
||||
} else if (nextTok instanceof Long finalIdx) {
|
||||
if (child == null || !child.has("L")) {
|
||||
throw new AwsException(
|
||||
@@ -4371,6 +4391,7 @@ public class DynamoDbService {
|
||||
}
|
||||
|
||||
setOrAppend((ArrayNode) child.get("L"), finalIdx, value);
|
||||
sortWalked(walked);
|
||||
}
|
||||
|
||||
return;
|
||||
@@ -4384,6 +4405,7 @@ public class DynamoDbService {
|
||||
400);
|
||||
}
|
||||
container = child.get("M");
|
||||
walked.add((ObjectNode) container);
|
||||
|
||||
} else if (nextTok instanceof Long) {
|
||||
if (child == null || !child.has("L")) {
|
||||
@@ -4417,7 +4439,8 @@ public class DynamoDbService {
|
||||
400);
|
||||
}
|
||||
|
||||
((ObjectNode) element.get("M")).set(finalAttr, value);
|
||||
setAndSort((ObjectNode) element.get("M"), finalAttr, value);
|
||||
sortWalked(walked);
|
||||
|
||||
} else if (nextTok instanceof Long finalIdx) {
|
||||
if (!element.has("L")) {
|
||||
@@ -4428,6 +4451,7 @@ public class DynamoDbService {
|
||||
}
|
||||
|
||||
setOrAppend((ArrayNode) element.get("L"), finalIdx, value);
|
||||
sortWalked(walked);
|
||||
}
|
||||
|
||||
return;
|
||||
@@ -4442,6 +4466,7 @@ public class DynamoDbService {
|
||||
}
|
||||
|
||||
container = element.get("M");
|
||||
walked.add((ObjectNode) container);
|
||||
|
||||
} else if (nextTok instanceof Long) {
|
||||
if (!element.has("L")) {
|
||||
@@ -4514,6 +4539,7 @@ public class DynamoDbService {
|
||||
}
|
||||
|
||||
JsonNode container = item;
|
||||
List<ObjectNode> walked = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < tokens.size() - 1; i++) {
|
||||
Object tok = tokens.get(i);
|
||||
@@ -4528,7 +4554,8 @@ public class DynamoDbService {
|
||||
if (last) {
|
||||
if (nextTok instanceof String finalAttr) {
|
||||
if (child == null || !child.has("M")) return;
|
||||
((ObjectNode) child.get("M")).remove(finalAttr);
|
||||
removeAndSort((ObjectNode) child.get("M"), finalAttr);
|
||||
sortWalked(walked);
|
||||
} else if (nextTok instanceof Long finalIdx) {
|
||||
if (child == null || !child.has("L")) return;
|
||||
|
||||
@@ -4536,6 +4563,7 @@ public class DynamoDbService {
|
||||
if (finalIdx < lArr.size()) {
|
||||
lArr.remove(finalIdx.intValue());
|
||||
}
|
||||
sortWalked(walked);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -4543,6 +4571,7 @@ public class DynamoDbService {
|
||||
if (nextTok instanceof String) {
|
||||
if (child == null || !child.has("M")) return;
|
||||
container = child.get("M");
|
||||
walked.add((ObjectNode) container);
|
||||
} else if (nextTok instanceof Long) {
|
||||
if (child == null || !child.has("L")) return;
|
||||
container = child.get("L");
|
||||
@@ -4557,7 +4586,8 @@ public class DynamoDbService {
|
||||
if (last) {
|
||||
if (nextTok instanceof String finalAttr) {
|
||||
if (!element.has("M")) return;
|
||||
((ObjectNode) element.get("M")).remove(finalAttr);
|
||||
removeAndSort((ObjectNode) element.get("M"), finalAttr);
|
||||
sortWalked(walked);
|
||||
} else if (nextTok instanceof Long finalIdx) {
|
||||
if (!element.has("L")) return;
|
||||
|
||||
@@ -4565,6 +4595,7 @@ public class DynamoDbService {
|
||||
if (finalIdx < lArr.size()) {
|
||||
lArr.remove(finalIdx.intValue());
|
||||
}
|
||||
sortWalked(walked);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -4572,6 +4603,7 @@ public class DynamoDbService {
|
||||
if (nextTok instanceof String) {
|
||||
if (!element.has("M")) return;
|
||||
container = element.get("M");
|
||||
walked.add((ObjectNode) container);
|
||||
} else if (nextTok instanceof Long) {
|
||||
if (!element.has("L")) return;
|
||||
container = element.get("L");
|
||||
|
||||
@@ -9,6 +9,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -23,6 +24,8 @@ final class DynamoDbSetOrder {
|
||||
|
||||
private record Keyed<K>(JsonNode member, K key) {}
|
||||
|
||||
private record Named(String name, byte[] key) {}
|
||||
|
||||
private record Order<K>(Function<String, K> key, Comparator<K> compare) {}
|
||||
|
||||
private static final Order<BigDecimal> BY_VALUE = new Order<>(DynamoDbSetOrder::numberOf, Comparator.naturalOrder());
|
||||
@@ -31,6 +34,20 @@ final class DynamoDbSetOrder {
|
||||
|
||||
private DynamoDbSetOrder() {}
|
||||
|
||||
/** Orders strings by code point, the order of a string set and of a map's keys. */
|
||||
static List<String> byCodePoint(Collection<String> strings) {
|
||||
List<Named> named = new ArrayList<>(strings.size());
|
||||
for (String string : strings) {
|
||||
named.add(new Named(string, BY_CODE_POINT.key().apply(string)));
|
||||
}
|
||||
named.sort(Comparator.comparing(Named::key, BY_CODE_POINT.compare()));
|
||||
List<String> result = new ArrayList<>(named.size());
|
||||
for (Named entry : named) {
|
||||
result.add(entry.name());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Returns the members in DynamoDB's order, or the input itself when it is not an array. */
|
||||
static JsonNode sorted(String setType, JsonNode members) {
|
||||
if (!members.isArray()) {
|
||||
|
||||
@@ -858,9 +858,9 @@ public class NativeDynamoDbJsonHandler {
|
||||
|
||||
Consumer<JsonNode> expectedCheck = legacyExpectedCheck(tableName, region, item, false, expected,
|
||||
conditionalOperator, returnValuesOnConditionCheckFailure);
|
||||
JsonNode previousItem = withShuffledFailureItem(() -> dynamoDbService.putItem(tableName, item,
|
||||
conditionExpression, exprAttrNames, exprAttrValues, region, returnValuesOnConditionCheckFailure,
|
||||
expectedCheck));
|
||||
JsonNode previousItem = withShuffledFailureItem(() -> dynamoDbService.putItem(tableName,
|
||||
DynamoDbMapOrder.sortedItem(item), conditionExpression, exprAttrNames, exprAttrValues, region,
|
||||
returnValuesOnConditionCheckFailure, expectedCheck));
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
if ("ALL_OLD".equals(returnValues) && previousItem != null) {
|
||||
@@ -1101,8 +1101,9 @@ public class NativeDynamoDbJsonHandler {
|
||||
Consumer<JsonNode> expectedCheck = legacyExpectedCheck(tableName, region, key, true, expectedUpd,
|
||||
conditionalOperatorUpd, returnValuesOnConditionCheckFailure);
|
||||
DynamoDbService.UpdateResult result = withShuffledFailureItem(() -> dynamoDbService.updateItem(
|
||||
tableName, key, updateData, updateExpression, exprAttrNames, exprAttrValues,
|
||||
returnValues, conditionExpression, region, returnValuesOnConditionCheckFailure, expectedCheck));
|
||||
tableName, key, DynamoDbMapOrder.sortedAttributeUpdates(updateData), updateExpression,
|
||||
exprAttrNames, DynamoDbMapOrder.sortedItem(exprAttrValues), returnValues, conditionExpression, region,
|
||||
returnValuesOnConditionCheckFailure, expectedCheck));
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
if ("ALL_NEW" .equals(returnValues) && result.newItem() != null) {
|
||||
@@ -1827,7 +1828,7 @@ public class NativeDynamoDbJsonHandler {
|
||||
}
|
||||
}
|
||||
|
||||
dynamoDbService.batchWriteItem(items, region);
|
||||
dynamoDbService.batchWriteItem(withSortedPutItems(items), region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("UnprocessedItems", objectMapper.createObjectNode());
|
||||
@@ -1842,6 +1843,18 @@ public class NativeDynamoDbJsonHandler {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private static Map<String, List<JsonNode>> withSortedPutItems(Map<String, List<JsonNode>> items) {
|
||||
Map<String, List<JsonNode>> sorted = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, List<JsonNode>> entry : items.entrySet()) {
|
||||
List<JsonNode> writes = new ArrayList<>(entry.getValue().size());
|
||||
for (JsonNode writeReq : entry.getValue()) {
|
||||
writes.add(DynamoDbMapOrder.withSortedMember(writeReq, "PutRequest", "Item"));
|
||||
}
|
||||
sorted.put(entry.getKey(), writes);
|
||||
}
|
||||
return sorted;
|
||||
}
|
||||
|
||||
private Response handleBatchGetItem(JsonNode request, String region) {
|
||||
JsonNode requestItems = request.get("RequestItems");
|
||||
if (requestItems == null || requestItems.isNull() || requestItems.isMissingNode()) {
|
||||
@@ -2977,7 +2990,8 @@ public class NativeDynamoDbJsonHandler {
|
||||
|
||||
try {
|
||||
DynamoDbService.TransactWriteResult result =
|
||||
dynamoDbService.transactWriteItems(transactItems, region, clientRequestToken, request);
|
||||
dynamoDbService.transactWriteItems(withSortedMaps(transactItems), region,
|
||||
clientRequestToken, request);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
addTransactWriteConsumedCapacity(response, request, result);
|
||||
return Response.ok(response).build();
|
||||
@@ -2986,6 +3000,16 @@ public class NativeDynamoDbJsonHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private static List<JsonNode> withSortedMaps(List<JsonNode> transactItems) {
|
||||
List<JsonNode> sorted = new ArrayList<>(transactItems.size());
|
||||
for (JsonNode txItem : transactItems) {
|
||||
sorted.add(DynamoDbMapOrder.withSortedMember(
|
||||
DynamoDbMapOrder.withSortedMember(txItem, "Put", "Item"),
|
||||
"Update", "ExpressionAttributeValues"));
|
||||
}
|
||||
return sorted;
|
||||
}
|
||||
|
||||
// DynamoDB reads an action with more than one operation as the first one in this order.
|
||||
private static final List<String> TRANSACT_WRITE_OPS = List.of("ConditionCheck", "Put", "Delete", "Update");
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.resource.ExplorerResource;
|
||||
import io.floci.aws.services.dynamodb.DynamoDbMapOrder;
|
||||
import io.floci.aws.services.dynamodb.DynamoDbService;
|
||||
import io.floci.aws.services.dynamodb.DynamoDbStreamService;
|
||||
import io.floci.aws.services.dynamodb.DynamoDbTtlService;
|
||||
@@ -118,7 +119,8 @@ public class NativeDynamoDbBackend implements DynamoDbBackend {
|
||||
@Override
|
||||
public void putItem(Scope scope, String tableName, JsonNode item, String conditionExpression,
|
||||
JsonNode expressionAttributeNames, JsonNode expressionAttributeValues) {
|
||||
RequestScopes.runAs(scope.accountId(), () -> dynamoDbService.putItem(tableName, item, conditionExpression,
|
||||
RequestScopes.runAs(scope.accountId(), () -> dynamoDbService.putItem(tableName,
|
||||
DynamoDbMapOrder.sortedItem(item), conditionExpression,
|
||||
expressionAttributeNames, expressionAttributeValues, scope.region(), "NONE"));
|
||||
}
|
||||
|
||||
@@ -139,9 +141,10 @@ public class NativeDynamoDbBackend implements DynamoDbBackend {
|
||||
String updateExpression, JsonNode expressionAttributeNames,
|
||||
JsonNode expressionAttributeValues, String returnValues, String conditionExpression) {
|
||||
DynamoDbService.UpdateResult result = RequestScopes.callAs(scope.accountId(), () ->
|
||||
dynamoDbService.updateItem(tableName, key, attributeUpdates, updateExpression,
|
||||
expressionAttributeNames, expressionAttributeValues, returnValues, conditionExpression,
|
||||
scope.region(), "NONE"));
|
||||
dynamoDbService.updateItem(tableName, key,
|
||||
DynamoDbMapOrder.sortedAttributeUpdates(attributeUpdates), updateExpression,
|
||||
expressionAttributeNames, DynamoDbMapOrder.sortedItem(expressionAttributeValues),
|
||||
returnValues, conditionExpression, scope.region(), "NONE"));
|
||||
if ("ALL_NEW".equals(returnValues)) {
|
||||
return result.newItem();
|
||||
} else if ("ALL_OLD".equals(returnValues)) {
|
||||
|
||||
Reference in new issue
Block a user