diff --git a/docs/services/dynamodb.md b/docs/services/dynamodb.md index 7ff6053336..4443ab5ea4 100644 --- a/docs/services/dynamodb.md +++ b/docs/services/dynamodb.md @@ -219,6 +219,10 @@ Floci does the same on the `ReturnValues` of `PutItem`, `UpdateItem` and `Delete `TransactWriteItems` cancellation reason. Each map is shuffled on its own. Lists and sets keep their order. `GetItem`, `Query`, `Scan`, `BatchGetItem`, PartiQL and Streams return the same order on every call, as on AWS. +As on AWS, a map written through `PutItem`, `BatchWriteItem`, `TransactWriteItems` or the values of `UpdateItem` +is stored with its keys sorted by code point. A PartiQL literal keeps the order it is written in. An update sorts +each map on its document path again and leaves the other maps as they are. A value copied from another attribute +keeps the order of that attribute. Set `FLOCI_SERVICES_DYNAMODB_RANDOMIZE_ATTRIBUTE_ORDER=false` to turn the shuffle off. The setting works with the native backend only. With the `local` backend, responses keep the order DynamoDB Local returns. ## Time to Live diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbMapOrder.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbMapOrder.java new file mode 100644 index 0000000000..136758f45f --- /dev/null +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbMapOrder.java @@ -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 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 names = names(map); + List sorted = DynamoDbSetOrder.byCodePoint(names); + if (sorted.equals(names)) { + return; + } + Map fields = LinkedHashMap.newLinkedHashMap(names.size()); + for (Map.Entry entry : map.properties()) { + fields.put(entry.getKey(), entry.getValue()); + } + map.removeAll(); + for (String name : sorted) { + map.set(name, fields.get(name)); + } + } + + private static List names(ObjectNode node) { + List 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 entry : node.properties()) { + if ("M".equals(entry.getKey()) || holdsMap(entry.getValue())) { + return true; + } + } + return false; + } + + private static ObjectNode copyFields(ObjectNode node, boolean sortKeys) { + List names = names(node); + Map 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; + } +} 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 f5b1df93c4..3a3172aae6 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java @@ -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 maps) { + for (ObjectNode map : maps) { + DynamoDbMapOrder.sortKeys(map); + } + } + + private void setValueAtPath(ObjectNode item, String path, JsonNode source, JsonNode exprAttrNames) { List 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 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 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"); diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbSetOrder.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbSetOrder.java index 55f95d7325..171bb59aee 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbSetOrder.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbSetOrder.java @@ -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(JsonNode member, K key) {} + private record Named(String name, byte[] key) {} + private record Order(Function key, Comparator compare) {} private static final Order 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 byCodePoint(Collection strings) { + List 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 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()) { 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 838df1733c..6c2b048583 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java +++ b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java @@ -858,9 +858,9 @@ public class NativeDynamoDbJsonHandler { Consumer 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 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> withSortedPutItems(Map> items) { + Map> sorted = new LinkedHashMap<>(); + for (Map.Entry> entry : items.entrySet()) { + List 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 withSortedMaps(List transactItems) { + List 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 TRANSACT_WRITE_OPS = List.of("ConditionCheck", "Put", "Delete", "Update"); diff --git a/src/main/java/io/floci/aws/services/dynamodb/backend/NativeDynamoDbBackend.java b/src/main/java/io/floci/aws/services/dynamodb/backend/NativeDynamoDbBackend.java index 2d9961b23c..c34101b30b 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/backend/NativeDynamoDbBackend.java +++ b/src/main/java/io/floci/aws/services/dynamodb/backend/NativeDynamoDbBackend.java @@ -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)) { diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbMapKeyOrderIntegrationTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbMapKeyOrderIntegrationTest.java new file mode 100644 index 0000000000..4121bb50af --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbMapKeyOrderIntegrationTest.java @@ -0,0 +1,300 @@ +package io.floci.aws.services.dynamodb; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.UncheckedIOException; + +import static io.floci.aws.services.dynamodb.DynamoDbAttributeOrderFixture.call; +import static io.floci.aws.services.dynamodb.DynamoDbAttributeOrderFixture.createTable; +import static io.floci.aws.services.dynamodb.DynamoDbAttributeOrderFixture.deleteTable; +import static io.floci.aws.services.dynamodb.DynamoDbAttributeOrderFixture.order; +import static io.floci.aws.testing.DynamoDbRequests.ddb; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +class DynamoDbMapKeyOrderIntegrationTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String ZBK = "{\"M\":{\"z\":{\"N\":\"1\"},\"b\":{\"N\":\"2\"},\"k\":{\"N\":\"3\"}}}"; + private static final String UNSORTED_ITEM = "{'pk':'k','m':{'z':1,'k':{'z':1,'b':2,'a':3},'j':{'z':1,'b':2,'a':3}}," + + "'l':[{'z':1,'b':2},{'z':1,'b':2}],'b':{'z':1,'b':2},'n':1}"; + + private String table; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void createTestTable() { + table = createTable("map-key-order"); + } + + @AfterEach + void deleteTestTable() { + deleteTable(table); + } + + private JsonNode stored() { + byte[] body = ddb("GetItem", "{\"TableName\":\"" + table + "\",\"ConsistentRead\":true," + + "\"Key\":{\"pk\":{\"S\":\"k\"}}}").extract().asByteArray(); + try { + return MAPPER.readTree(body).get("Item"); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static String mapOrder(JsonNode node) { + return order(node.get("M")); + } + + private void put(String item) { + call("PutItem", asciiJson("{\"TableName\":\"" + table + "\",\"Item\":" + item + "}")); + } + + // The test client sends a String body as ISO-8859-1. + private static String asciiJson(String json) { + StringBuilder ascii = new StringBuilder(); + json.chars().forEach(c -> { + if (c < 128) { + ascii.append((char) c); + } else { + ascii.append(String.format("\\u%04x", c)); + } + }); + return ascii.toString(); + } + + private void update(String expression, String values) { + String valuesMember = values == null ? "" : ",\"ExpressionAttributeValues\":" + values; + call("UpdateItem", "{\"TableName\":\"" + table + "\",\"Key\":{\"pk\":{\"S\":\"k\"}}," + + "\"UpdateExpression\":\"" + expression + "\"" + valuesMember + "}"); + } + + private void partiQL(String statement) { + ObjectNode body = MAPPER.createObjectNode(); + body.put("Statement", statement.replace("$T", "\"" + table + "\"")); + call("ExecuteStatement", body.toString()); + } + + private void insertUnsorted() { + partiQL("INSERT INTO $T VALUE " + UNSORTED_ITEM); + } + + @Test + void putItemStoresNestedMapsInCodePointOrder() { + put("{\"pk\":{\"S\":\"k\"},\"m\":{\"M\":{\"z\":" + ZBK + ",\"b\":{\"L\":[" + ZBK + "]},\"k\":" + ZBK + "}}}"); + + JsonNode m = stored().get("m"); + assertEquals("b,k,z", mapOrder(m)); + assertEquals("b,k,z", mapOrder(m.get("M").get("z"))); + assertEquals("b,k,z", mapOrder(m.get("M").get("b").get("L").get(0))); + } + + @Test + void putItemOrdersKeysByCodePointNotByUtf16Unit() { + put("{\"pk\":{\"S\":\"k\"},\"m\":{\"M\":{\"😀\":{\"S\":\"x\"},\"₩\":{\"S\":\"x\"}," + + "\"é\":{\"S\":\"x\"},\"aa\":{\"S\":\"x\"},\"a b\":{\"S\":\"x\"},\"a\":{\"S\":\"x\"}," + + "\"_\":{\"S\":\"x\"},\"B\":{\"S\":\"x\"},\"A\":{\"S\":\"x\"},\"1\":{\"S\":\"x\"}}}}"); + + assertEquals("1,A,B,_,a,a b,aa,é,₩,😀", mapOrder(stored().get("m"))); + } + + @Test + void batchWriteItemStoresMapsInCodePointOrder() { + call("BatchWriteItem", "{\"RequestItems\":{\"" + table + "\":[{\"PutRequest\":{\"Item\":" + + "{\"pk\":{\"S\":\"k\"},\"m\":" + ZBK + "}}}]}}"); + + assertEquals("b,k,z", mapOrder(stored().get("m"))); + } + + @Test + void transactWriteItemsPutStoresMapsInCodePointOrder() { + call("TransactWriteItems", "{\"TransactItems\":[{\"Put\":{\"TableName\":\"" + table + "\",\"Item\":" + + "{\"pk\":{\"S\":\"k\"},\"m\":" + ZBK + "}}}]}"); + + assertEquals("b,k,z", mapOrder(stored().get("m"))); + } + + @Test + void transactWriteItemsUpdateStoresMapsInCodePointOrder() { + put("{\"pk\":{\"S\":\"k\"}}"); + call("TransactWriteItems", "{\"TransactItems\":[{\"Update\":{\"TableName\":\"" + table + "\"," + + "\"Key\":{\"pk\":{\"S\":\"k\"}},\"UpdateExpression\":\"SET a = :v\"," + + "\"ExpressionAttributeValues\":{\":v\":" + ZBK + "}}}]}"); + + assertEquals("b,k,z", mapOrder(stored().get("a"))); + } + + @Test + void updateItemSetStoresMapsInCodePointOrder() { + put("{\"pk\":{\"S\":\"k\"},\"m\":{\"M\":{}}}"); + update("SET a = :v, m.x = :v", "{\":v\":" + ZBK + "}"); + + JsonNode item = stored(); + assertEquals("b,k,z", mapOrder(item.get("a"))); + assertEquals("b,k,z", mapOrder(item.get("m").get("M").get("x"))); + } + + @Test + void attributeUpdatesPutStoresMapsInCodePointOrder() { + put("{\"pk\":{\"S\":\"k\"}}"); + call("UpdateItem", "{\"TableName\":\"" + table + "\",\"Key\":{\"pk\":{\"S\":\"k\"}}," + + "\"AttributeUpdates\":{\"a\":{\"Action\":\"PUT\",\"Value\":" + ZBK + "}}}"); + + assertEquals("b,k,z", mapOrder(stored().get("a"))); + } + + @Test + void listAppendStoresMapsInCodePointOrder() { + put("{\"pk\":{\"S\":\"k\"},\"l\":{\"L\":[]}}"); + update("SET l = list_append(l, :v)", "{\":v\":{\"L\":[" + ZBK + "]}}"); + + assertEquals("b,k,z", mapOrder(stored().get("l").get("L").get(0))); + } + + @Test + void ifNotExistsStoresMapsInCodePointOrder() { + put("{\"pk\":{\"S\":\"k\"}}"); + update("SET a = if_not_exists(a, :v)", "{\":v\":" + ZBK + "}"); + + assertEquals("b,k,z", mapOrder(stored().get("a"))); + } + + @Test + void partiQLInsertKeepsTheWrittenOrder() { + partiQL("INSERT INTO $T VALUE {'pk':'k','m':{'z':1,'b':{'z':1,'k':2,'b':3},'k':3}}"); + + JsonNode m = stored().get("m"); + assertEquals("z,b,k", mapOrder(m)); + assertEquals("z,k,b", mapOrder(m.get("M").get("b"))); + } + + @Test + void batchExecuteStatementInsertKeepsTheWrittenOrder() { + ObjectNode statement = MAPPER.createObjectNode(); + statement.put("Statement", "INSERT INTO \"" + table + "\" VALUE {'pk':'k','m':{'z':1,'b':2,'k':3}}"); + call("BatchExecuteStatement", "{\"Statements\":[" + statement + "]}"); + + assertEquals("z,b,k", mapOrder(stored().get("m"))); + } + + @Test + void executeTransactionInsertKeepsTheWrittenOrder() { + ObjectNode statement = MAPPER.createObjectNode(); + statement.put("Statement", "INSERT INTO \"" + table + "\" VALUE {'pk':'k','m':{'z':1,'b':2,'k':3}}"); + call("ExecuteTransaction", "{\"TransactStatements\":[" + statement + "]}"); + + assertEquals("z,b,k", mapOrder(stored().get("m"))); + } + + @Test + void partiQLUpdateSetKeepsTheWrittenOrderOfTheLiteral() { + partiQL("INSERT INTO $T VALUE {'pk':'k'}"); + partiQL("UPDATE $T SET m = {'z':1,'b':2,'k':3} WHERE pk = 'k'"); + + assertEquals("z,b,k", mapOrder(stored().get("m"))); + } + + @Test + void partiQLUpdateSetOfNestedKeyKeepsTheLiteralAndSortsTheMap() { + insertUnsorted(); + partiQL("UPDATE $T SET m.x = {'q':1,'d':2,'a':3} WHERE pk = 'k'"); + + JsonNode m = stored().get("m"); + assertEquals("j,k,x,z", mapOrder(m)); + assertEquals("q,d,a", mapOrder(m.get("M").get("x"))); + } + + @Test + void partiQLRemoveSortsTheMap() { + insertUnsorted(); + partiQL("UPDATE $T REMOVE m.q WHERE pk = 'k'"); + + assertEquals("j,k,z", mapOrder(stored().get("m"))); + } + + @Test + void setOnAMapKeySortsItAndLeavesNestedMapsAlone() { + insertUnsorted(); + update("SET m.x = :v", "{\":v\":{\"N\":\"1\"}}"); + + JsonNode m = stored().get("m"); + assertEquals("j,k,x,z", mapOrder(m)); + assertEquals("z,b,a", mapOrder(m.get("M").get("k"))); + } + + @Test + void setBelowANestedMapSortsEveryMapOnThePath() { + insertUnsorted(); + update("SET m.k.w = :v", "{\":v\":{\"N\":\"1\"}}"); + + JsonNode m = stored().get("m"); + assertEquals("j,k,z", mapOrder(m)); + assertEquals("a,b,w,z", mapOrder(m.get("M").get("k"))); + assertEquals("z,b,a", mapOrder(m.get("M").get("j"))); + } + + @Test + void setBelowAListElementSortsOnlyThatElement() { + insertUnsorted(); + update("SET l[0].e = :v", "{\":v\":{\"N\":\"1\"}}"); + + JsonNode list = stored().get("l").get("L"); + assertEquals("b,e,z", mapOrder(list.get(0))); + assertEquals("z,b", mapOrder(list.get(1))); + } + + @Test + void copyFromAPathKeepsTheSourceOrder() { + insertUnsorted(); + update("SET a = b", null); + + JsonNode item = stored(); + assertEquals("z,b", mapOrder(item.get("a"))); + } + + @Test + void laterPathThroughACopyDoesNotReorderTheSource() { + insertUnsorted(); + update("SET a = b, c = b", null); + update("SET a.e = :v", "{\":v\":{\"N\":\"1\"}}"); + + JsonNode item = stored(); + assertEquals("b,e,z", mapOrder(item.get("a"))); + assertEquals("z,b", mapOrder(item.get("b"))); + assertEquals("z,b", mapOrder(item.get("c"))); + } + + @Test + void copyOfANestedMapKeepsItsOrderWhileTheMapIsSorted() { + insertUnsorted(); + update("SET m.k = m.j", null); + + JsonNode m = stored().get("m"); + assertEquals("j,k,z", mapOrder(m)); + assertEquals("z,b,a", mapOrder(m.get("M").get("k"))); + } + + @Test + void updateThatTouchesNoMapLeavesEveryMapAsItWas() { + insertUnsorted(); + update("ADD n :one", "{\":one\":{\"N\":\"1\"}}"); + + JsonNode item = stored(); + assertEquals("z,k,j", mapOrder(item.get("m"))); + assertEquals("z,b,a", mapOrder(item.get("m").get("M").get("k"))); + assertEquals("z,b", mapOrder(item.get("b"))); + } +} diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbMapOrderTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbMapOrderTest.java new file mode 100644 index 0000000000..5064024c29 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbMapOrderTest.java @@ -0,0 +1,136 @@ +package io.floci.aws.services.dynamodb; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.jupiter.api.Test; + +import static io.floci.aws.services.dynamodb.DynamoDbAttributeOrderFixture.order; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +class DynamoDbMapOrderTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static JsonNode json(String text) throws Exception { + return MAPPER.readTree(text); + } + + @Test + void keysSortByCodePointNotByUtf16Unit() throws Exception { + JsonNode item = json(""" + {"m":{"M":{"😀":{"S":"x"},"₩":{"S":"x"},"é":{"S":"x"},"aa":{"S":"x"}, + "a b":{"S":"x"},"a":{"S":"x"},"_":{"S":"x"},"B":{"S":"x"},"A":{"S":"x"},"1":{"S":"x"}}}}"""); + + JsonNode sorted = DynamoDbMapOrder.sortedItem(item); + + assertEquals("1,A,B,_,a,a b,aa,é,₩,😀", order(sorted.get("m").get("M"))); + } + + @Test + void mapInsideListInsideMapIsSorted() throws Exception { + JsonNode item = json(""" + {"m":{"M":{"z":{"S":"1"},"l":{"L":[{"M":{"z":{"S":"1"},"b":{"S":"2"}}},{"S":"s"}]},"b":{"S":"2"}}}}"""); + + JsonNode sorted = DynamoDbMapOrder.sortedItem(item); + + JsonNode m = sorted.get("m").get("M"); + assertEquals("b,l,z", order(m)); + assertEquals("b,z", order(m.get("l").get("L").get(0).get("M"))); + } + + @Test + void topLevelOrderIsKept() throws Exception { + JsonNode item = json("{\"z\":{\"S\":\"1\"},\"a\":{\"S\":\"2\"},\"m\":{\"M\":{\"y\":{\"S\":\"1\"},\"x\":{\"S\":\"2\"}}}}"); + + JsonNode sorted = DynamoDbMapOrder.sortedItem(item); + + assertEquals("z,a,m", order(sorted)); + assertEquals("x,y", order(sorted.get("m").get("M"))); + } + + @Test + void inputIsNotChanged() throws Exception { + JsonNode item = json("{\"m\":{\"M\":{\"y\":{\"S\":\"1\"},\"x\":{\"S\":\"2\"}}}}"); + + DynamoDbMapOrder.sortedItem(item); + + assertEquals("y,x", order(item.get("m").get("M"))); + } + + @Test + void itemWithoutMapIsReturnedAsIs() throws Exception { + JsonNode item = json("{\"b\":{\"S\":\"1\"},\"a\":{\"L\":[{\"N\":\"1\"}]}}"); + + assertSame(item, DynamoDbMapOrder.sortedItem(item)); + } + + @Test + void setsAreNotChanged() throws Exception { + JsonNode item = json("{\"m\":{\"M\":{\"b\":{\"SS\":[\"z\",\"a\"]},\"a\":{\"NS\":[\"2\",\"1\"]}}}}"); + + JsonNode sorted = DynamoDbMapOrder.sortedItem(item); + + JsonNode m = sorted.get("m").get("M"); + assertEquals("a,b", order(m)); + assertEquals("[\"z\",\"a\"]", m.get("b").get("SS").toString()); + assertEquals("[\"2\",\"1\"]", m.get("a").get("NS").toString()); + } + + @Test + void valueIsSortedAtAnyDepth() throws Exception { + JsonNode values = json("{\":v\":{\"L\":[{\"M\":{\"z\":{\"S\":\"1\"},\"a\":{\"M\":{\"y\":{\"S\":\"1\"}," + + "\"x\":{\"S\":\"2\"}}}}}]}}"); + + JsonNode sorted = DynamoDbMapOrder.sortedItem(values); + + JsonNode map = sorted.get(":v").get("L").get(0).get("M"); + assertEquals("a,z", order(map)); + assertEquals("x,y", order(map.get("a").get("M"))); + } + + @Test + void attributeUpdatesSortEachValue() throws Exception { + JsonNode updates = json(""" + {"m":{"Action":"PUT","Value":{"M":{"z":{"S":"1"},"b":{"S":"2"}}}},"n":{"Action":"ADD","Value":{"N":"1"}}}"""); + + JsonNode sorted = DynamoDbMapOrder.sortedAttributeUpdates(updates); + + assertEquals("b,z", order(sorted.get("m").get("Value").get("M"))); + assertEquals("PUT", sorted.get("m").get("Action").asText()); + assertEquals("z,b", order(updates.get("m").get("Value").get("M"))); + } + + @Test + void sortKeysReordersOneMapInPlace() throws Exception { + ObjectNode map = (ObjectNode) json("{\"z\":{\"M\":{\"y\":{\"S\":\"1\"},\"x\":{\"S\":\"2\"}}},\"a\":{\"S\":\"1\"}}"); + JsonNode nested = map.get("z"); + + DynamoDbMapOrder.sortKeys(map); + + assertEquals("a,z", order(map)); + assertSame(nested, map.get("z")); + assertEquals("y,x", order(map.get("z").get("M"))); + } + + @Test + void withSortedMemberSortsTheMemberAndKeepsTheRest() throws Exception { + JsonNode request = json(""" + {"Put":{"Item":{"m":{"M":{"z":{"S":"1"},"b":{"S":"2"}}}},"TableName":"t"},"Other":1}"""); + + JsonNode result = DynamoDbMapOrder.withSortedMember(request, "Put", "Item"); + + assertEquals("b,z", order(result.get("Put").get("Item").get("m").get("M"))); + assertEquals("t", result.get("Put").get("TableName").asText()); + assertEquals(1, result.get("Other").asInt()); + assertEquals("z,b", order(request.get("Put").get("Item").get("m").get("M"))); + } + + @Test + void withSortedMemberReturnsTheRequestWhenTheOperationIsAbsent() throws Exception { + JsonNode request = json("{\"Delete\":{\"Key\":{\"id\":{\"S\":\"k\"}}}}"); + + assertSame(request, DynamoDbMapOrder.withSortedMember(request, "Put", "Item")); + } +} diff --git a/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbNativeBackendTest.java b/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbNativeBackendTest.java index 077e917153..7a2fb0244d 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbNativeBackendTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbNativeBackendTest.java @@ -184,6 +184,33 @@ class DynamoDbNativeBackendTest { assertEquals(json("{\"id\":{\"S\":\"k\"},\"n\":{\"N\":\"5\"}}"), backend.getItem(SCOPE, TABLE, key)); } + @Test + void typedWritesStoreMapKeysInCodePointOrder() throws Exception { + backend.createTable(SCOPE, TABLE, List.of(new KeySchemaElement("id", "HASH")), + List.of(new AttributeDefinition("id", "S")), 5L, 5L, List.of(), List.of()); + JsonNode key = json("{\"id\":{\"S\":\"k\"}}"); + + backend.putItem(SCOPE, TABLE, + json("{\"id\":{\"S\":\"k\"},\"m\":{\"M\":{\"z\":{\"S\":\"1\"},\"b\":{\"S\":\"2\"}}}}"), + null, null, null); + assertEquals("b,z", keys(backend.getItem(SCOPE, TABLE, key).get("m").get("M"))); + + backend.updateItem(SCOPE, TABLE, key, null, "SET p = :p", null, + json("{\":p\":{\"M\":{\"z\":{\"S\":\"1\"},\"b\":{\"S\":\"2\"}}}}"), "NONE", null); + assertEquals("b,z", keys(backend.getItem(SCOPE, TABLE, key).get("p").get("M"))); + + backend.updateItem(SCOPE, TABLE, key, + json("{\"q\":{\"Action\":\"PUT\",\"Value\":{\"M\":{\"z\":{\"S\":\"1\"},\"b\":{\"S\":\"2\"}}}}}"), + null, null, null, "NONE", null); + assertEquals("b,z", keys(backend.getItem(SCOPE, TABLE, key).get("q").get("M"))); + } + + private static String keys(JsonNode node) { + List names = new ArrayList<>(); + node.fieldNames().forEachRemaining(names::add); + return String.join(",", names); + } + @Test void storedTagsAreTheTablesForItAndItsIndexesInTheArnsAccountAndRegionAndTaggingPutsANewMap() throws Exception { call(Api.DYNAMODB, "CreateTable", json("""