From a966242daf40a4ff68f06be19bc89cf8d5fb9f43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?TATSUNO=20=E2=80=9CTaz=E2=80=9D=20Yasuhiro?= Date: Sun, 22 Nov 2026 22:13:53 +0900 Subject: [PATCH] feat(dynamodb): return attributes and map keys in a random order where AWS does (#9191) * feat(dynamodb): return attributes and map keys in a random order where AWS does * perf(dynamodb): presize the maps of a shuffled item * refactor(dynamodb): read the attribute order setting when the handler is built * docs(dynamodb): say the attribute order setting works with the native backend only * test(dynamodb): share the attribute order test helpers and delete each test table * test(dynamodb): check the attribute order setting in a unit test instead of a test profile * docs(dynamodb): say reads return the same order on every call --- docs/configuration/environment-variables.md | 1 + docs/services/dynamodb.md | 11 ++ .../io/floci/aws/config/EmulatorConfig.java | 10 + .../dynamodb/DynamoDbAttributeOrder.java | 75 ++++++++ .../dynamodb/NativeDynamoDbJsonHandler.java | 49 +++-- src/main/resources/application.yml | 1 + .../DynamoDbAttributeOrderFixture.java | 53 ++++++ ...DynamoDbAttributeOrderIntegrationTest.java | 171 ++++++++++++++++++ .../dynamodb/DynamoDbAttributeOrderTest.java | 153 ++++++++++++++++ .../backend/DynamoDbNativeBackendTest.java | 3 +- src/test/resources/application.yml | 1 + 11 files changed, 513 insertions(+), 15 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrder.java create mode 100644 src/test/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrderFixture.java create mode 100644 src/test/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrderIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrderTest.java diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index b513f5e926..2d359f9dc7 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -299,6 +299,7 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s |---|---|---| | `FLOCI_SERVICES_DYNAMODB_ENABLED` | `true` | Enable the DynamoDB service | | `FLOCI_SERVICES_DYNAMODB_TRANSACTION_CONFLICTS_ENABLED` | `false` | Reject requests that reach the items of a `TransactWriteItems` in flight with `TransactionConflictException` or a `TransactionConflict` cancellation, as AWS does, instead of making them wait. Native backend only. See [DynamoDB](../services/dynamodb.md#transaction-conflicts) | +| `FLOCI_SERVICES_DYNAMODB_RANDOMIZE_ATTRIBUTE_ORDER` | `true` | Return attributes and map keys in a random order on the operations where AWS does. Native backend only. See [DynamoDB](../services/dynamodb.md#attribute-order) | | `FLOCI_SERVICES_DYNAMODB_BACKEND` | `native` | Engine behind the DynamoDB API: `native` or `local` (DynamoDB Local), case-insensitive. Any other value fails startup. See [DynamoDB Local backend](../services/dynamodb.md#dynamodb-local-backend) | | `FLOCI_SERVICES_DYNAMODB_LOCAL_ENDPOINT` | _(none)_ | Base URL of DynamoDB Local, for example `http://dynamodb-local:8000`. Required when the backend is `local`. Must be `http` or `https` with a host. AWS endpoints (hosts under `amazonaws.com`, `amazonaws.com.cn` or `api.aws`) are rejected | | `FLOCI_SERVICES_DYNAMODB_LOCAL_CONNECT_TIMEOUT_SECONDS` | `2` | Seconds to wait for a connection to DynamoDB Local | diff --git a/docs/services/dynamodb.md b/docs/services/dynamodb.md index 07f7db63b6..7ff6053336 100644 --- a/docs/services/dynamodb.md +++ b/docs/services/dynamodb.md @@ -211,6 +211,16 @@ A `BatchWriteItem`, or a write that is not part of a transaction, does not make conflict. The setting works with the native backend only; with the `local` backend Floci does not start. +## Attribute order + +AWS returns the top-level attributes and every map key in a new random order on some operations. +Floci does the same on the `ReturnValues` of `PutItem`, `UpdateItem` and `DeleteItem`, on the +`Item` of a failed condition check, on `TransactGetItems`, and on the `Item` of a +`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. +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 With TTL enabled, a sweep runs every 60 seconds and deletes the items whose TTL attribute holds an @@ -344,6 +354,7 @@ region is rejected. | `FLOCI_SERVICES_DYNAMODB_STREAM_RETENTION_ENABLED` | `false` | Keep stream records, and shards once closed, for 24 hours, as AWS does | | `FLOCI_SERVICES_DYNAMODB_STREAM_MAX_RECORDS` | `1000` | Most records each stream keeps across its shards; the oldest goes first. Must be at least `1` | | `FLOCI_SERVICES_DYNAMODB_TRANSACTION_CONFLICTS_ENABLED` | `false` | Reject requests that reach the items of a `TransactWriteItems` in flight, as AWS does, instead of making them wait. Native backend only. See [Transaction conflicts](#transaction-conflicts) | +| `FLOCI_SERVICES_DYNAMODB_RANDOMIZE_ATTRIBUTE_ORDER` | `true` | Return attributes and map keys in a random order where AWS does. Native backend only. See [Attribute order](#attribute-order) | | `FLOCI_SERVICES_DYNAMODB_BACKEND` | `native` | Engine behind the DynamoDB API: `native` or `local`, case-insensitive. Any other value fails startup. See [DynamoDB Local backend](#dynamodb-local-backend) | | `FLOCI_SERVICES_DYNAMODB_LOCAL_ENDPOINT` | *(none)* | Base URL of DynamoDB Local, for example `http://dynamodb-local:8000`. Required when the backend is `local`. Must be `http` or `https` with a host. AWS endpoints (hosts under `amazonaws.com`, `amazonaws.com.cn` or `api.aws`) are rejected | | `FLOCI_SERVICES_DYNAMODB_LOCAL_CONNECT_TIMEOUT_SECONDS` | `2` | Seconds to wait for a connection to DynamoDB Local | diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 643dd0263b..996c461ce6 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -1742,6 +1742,16 @@ public interface EmulatorConfig { @WithDefault("false") boolean transactionConflictsEnabled(); + /** + * Whether the operations that AWS answers in a new order on each call do the same: the + * ReturnValues of PutItem, UpdateItem and DeleteItem, the Item of a failed condition check, + * TransactGetItems and the Item of a TransactWriteItems cancellation reason. Map keys and + * top-level attributes come back shuffled. False keeps the stored order. The native backend only. + * Env: FLOCI_SERVICES_DYNAMODB_RANDOMIZE_ATTRIBUTE_ORDER + */ + @WithDefault("true") + boolean randomizeAttributeOrder(); + /** The engine behind the DynamoDB API: {@code native} or {@code local}. Env: FLOCI_SERVICES_DYNAMODB_BACKEND. */ @WithDefault("native") String backend(); diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrder.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrder.java new file mode 100644 index 0000000000..02907d3e8e --- /dev/null +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrder.java @@ -0,0 +1,75 @@ +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.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; + +/** + * Some DynamoDB operations return the top-level attributes and every map in a new random order + * on each call. Each map is drawn on its own. Sets and lists keep their order. + */ +final class DynamoDbAttributeOrder { + + private static final JsonNodeFactory FACTORY = JsonNodeFactory.instance; + + private DynamoDbAttributeOrder() { + } + + static JsonNode shuffled(JsonNode item, boolean enabled) { + if (!enabled || item == null || !item.isObject()) { + return item; + } + return shuffleFields((ObjectNode) item); + } + + private static ObjectNode shuffleFields(ObjectNode node) { + int n = node.size(); + @SuppressWarnings("unchecked") + Map.Entry[] entries = new Map.Entry[n]; + int i = 0; + for (Map.Entry entry : node.properties()) { + entries[i++] = entry; + } + ThreadLocalRandom random = ThreadLocalRandom.current(); + for (int j = n - 1; j > 0; j--) { + int k = random.nextInt(j + 1); + Map.Entry swap = entries[j]; + entries[j] = entries[k]; + entries[k] = swap; + } + Map map = new LinkedHashMap<>((int) (n / 0.75f) + 1); + for (Map.Entry entry : entries) { + map.put(entry.getKey(), shuffleValue(entry.getValue())); + } + return new ObjectNode(FACTORY, map); + } + + private static ObjectNode wrap(String key, JsonNode value) { + Map map = new LinkedHashMap<>(2); + map.put(key, value); + return new ObjectNode(FACTORY, map); + } + + private static JsonNode shuffleValue(JsonNode value) { + if (value.isObject() && value.size() == 1) { + JsonNode map = value.get("M"); + if (map != null && map.isObject()) { + return wrap("M", shuffleFields((ObjectNode) map)); + } + JsonNode list = value.get("L"); + if (list != null && list.isArray()) { + ArrayNode copy = FACTORY.arrayNode(list.size()); + for (JsonNode element : list) { + copy.add(shuffleValue(element)); + } + return wrap("L", copy); + } + } + return value; + } +} 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 ab0bc1e50f..838df1733c 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java +++ b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java @@ -89,16 +89,24 @@ public class NativeDynamoDbJsonHandler { private final NativeDynamoDbTableService tableService; private final ObjectMapper objectMapper; private final EmulatorConfig config; + private final boolean randomizeOrder; private final DynamoDbPartiQLHandler partiQLHandler; private final Object importLock = new Object(); @Inject public NativeDynamoDbJsonHandler(DynamoDbService dynamoDbService, NativeDynamoDbTableService tableService, ObjectMapper objectMapper, EmulatorConfig config) { + this(dynamoDbService, tableService, objectMapper, config, + config.services().dynamodb().randomizeAttributeOrder()); + } + + private NativeDynamoDbJsonHandler(DynamoDbService dynamoDbService, NativeDynamoDbTableService tableService, + ObjectMapper objectMapper, EmulatorConfig config, boolean randomizeOrder) { this.dynamoDbService = dynamoDbService; this.tableService = tableService; this.objectMapper = objectMapper; this.config = config; + this.randomizeOrder = randomizeOrder; this.partiQLHandler = new DynamoDbPartiQLHandler(dynamoDbService, objectMapper); } @@ -106,7 +114,18 @@ public class NativeDynamoDbJsonHandler { NativeDynamoDbJsonHandler(DynamoDbService dynamoDbService, DynamoDbStreamService dynamoDbStreamService, KinesisService kinesisService, ObjectMapper objectMapper) { this(dynamoDbService, new NativeDynamoDbTableService(dynamoDbService, dynamoDbStreamService, kinesisService), - objectMapper, null); + objectMapper, null, false); + } + + private T withShuffledFailureItem(Supplier call) { + try { + return call.get(); + } catch (ConditionalCheckFailedException e) { + if (e.getItem() == null || !randomizeOrder) { + throw e; + } + throw new ConditionalCheckFailedException(DynamoDbAttributeOrder.shuffled(e.getItem(), true)); + } } public Response handle(String action, JsonNode request, String region) throws Exception { @@ -839,12 +858,13 @@ public class NativeDynamoDbJsonHandler { Consumer expectedCheck = legacyExpectedCheck(tableName, region, item, false, expected, conditionalOperator, returnValuesOnConditionCheckFailure); - JsonNode previousItem = dynamoDbService.putItem(tableName, item, conditionExpression, - exprAttrNames, exprAttrValues, region, returnValuesOnConditionCheckFailure, expectedCheck); + JsonNode previousItem = withShuffledFailureItem(() -> dynamoDbService.putItem(tableName, item, + conditionExpression, exprAttrNames, exprAttrValues, region, returnValuesOnConditionCheckFailure, + expectedCheck)); ObjectNode response = objectMapper.createObjectNode(); if ("ALL_OLD".equals(returnValues) && previousItem != null) { - response.set("Attributes", previousItem); + response.set("Attributes", DynamoDbAttributeOrder.shuffled(previousItem, randomizeOrder)); } addItemCollectionMetrics(response, request, tableName, item, region); addWriteConsumedCapacity(response, request, tableName, region, previousItem, item); @@ -973,12 +993,13 @@ public class NativeDynamoDbJsonHandler { ? request.get("ConditionalOperator").asText() : "AND"; Consumer expectedCheck = legacyExpectedCheck(tableName, region, key, true, expectedDel, condOpDel, returnValuesOnConditionCheckFailure); - JsonNode oldItem = dynamoDbService.deleteItem(tableName, key, conditionExpression, - exprAttrNames, exprAttrValues, region, returnValuesOnConditionCheckFailure, expectedCheck); + JsonNode oldItem = withShuffledFailureItem(() -> dynamoDbService.deleteItem(tableName, key, + conditionExpression, exprAttrNames, exprAttrValues, region, returnValuesOnConditionCheckFailure, + expectedCheck)); ObjectNode response = objectMapper.createObjectNode(); if ("ALL_OLD" .equals(returnValues) && oldItem != null) { - response.set("Attributes", oldItem); + response.set("Attributes", DynamoDbAttributeOrder.shuffled(oldItem, randomizeOrder)); } addItemCollectionMetrics(response, request, tableName, key, region); addWriteConsumedCapacity(response, request, tableName, region, oldItem, null); @@ -1079,20 +1100,20 @@ public class NativeDynamoDbJsonHandler { Consumer expectedCheck = legacyExpectedCheck(tableName, region, key, true, expectedUpd, conditionalOperatorUpd, returnValuesOnConditionCheckFailure); - DynamoDbService.UpdateResult result = dynamoDbService.updateItem( + DynamoDbService.UpdateResult result = withShuffledFailureItem(() -> dynamoDbService.updateItem( tableName, key, updateData, updateExpression, exprAttrNames, exprAttrValues, - returnValues, conditionExpression, region, returnValuesOnConditionCheckFailure, expectedCheck); + returnValues, conditionExpression, region, returnValuesOnConditionCheckFailure, expectedCheck)); ObjectNode response = objectMapper.createObjectNode(); if ("ALL_NEW" .equals(returnValues) && result.newItem() != null) { - response.set("Attributes", result.newItem()); + response.set("Attributes", DynamoDbAttributeOrder.shuffled(result.newItem(), randomizeOrder)); } else if ("ALL_OLD" .equals(returnValues) && result.oldItem() != null) { - response.set("Attributes", result.oldItem()); + response.set("Attributes", DynamoDbAttributeOrder.shuffled(result.oldItem(), randomizeOrder)); } else if ("UPDATED_NEW".equals(returnValues) || "UPDATED_OLD".equals(returnValues)) { ObjectNode updated = DynamoDbUpdatedAttributes.collect(result.touched(), "UPDATED_NEW".equals(returnValues)); // AWS omits Attributes when no touched path has a value on that side. if (!updated.isEmpty()) { - response.set("Attributes", updated); + response.set("Attributes", DynamoDbAttributeOrder.shuffled(updated, randomizeOrder)); } } addItemCollectionMetrics(response, request, tableName, key, region); @@ -3298,7 +3319,7 @@ public class NativeDynamoDbJsonHandler { r.put("Message", reason.message() != null ? reason.message() : "The conditional request failed"); } if (reason.item() != null) { - r.set("Item", reason.item()); + r.set("Item", DynamoDbAttributeOrder.shuffled(reason.item(), randomizeOrder)); } reasons.add(r); } @@ -3380,7 +3401,7 @@ public class NativeDynamoDbJsonHandler { for (JsonNode item : result.items()) { ObjectNode entry = objectMapper.createObjectNode(); if (item != null) { - entry.set("Item", item); + entry.set("Item", DynamoDbAttributeOrder.shuffled(item, randomizeOrder)); } responsesArray.add(entry); } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index ec01e54ac4..c75cf75a77 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -491,6 +491,7 @@ floci: stream-retention-enabled: false # FLOCI_SERVICES_DYNAMODB_STREAM_RETENTION_ENABLED. 24-hour records and shards. stream-max-records: 1000 # FLOCI_SERVICES_DYNAMODB_STREAM_MAX_RECORDS. Records kept per stream. transaction-conflicts-enabled: false # FLOCI_SERVICES_DYNAMODB_TRANSACTION_CONFLICTS_ENABLED. Busy items cancel overlapping transactions (native engine). + randomize-attribute-order: true # FLOCI_SERVICES_DYNAMODB_RANDOMIZE_ATTRIBUTE_ORDER. Shuffle attributes and map keys where AWS does (native engine). backend: native # FLOCI_SERVICES_DYNAMODB_BACKEND: native or local # local-endpoint: http://dynamodb-local:8000 # FLOCI_SERVICES_DYNAMODB_LOCAL_ENDPOINT local-connect-timeout-seconds: 2 # FLOCI_SERVICES_DYNAMODB_LOCAL_CONNECT_TIMEOUT_SECONDS diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrderFixture.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrderFixture.java new file mode 100644 index 0000000000..cbb90b6f13 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrderFixture.java @@ -0,0 +1,53 @@ +package io.floci.aws.services.dynamodb; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static io.floci.aws.testing.DynamoDbRequests.ddb; + +final class DynamoDbAttributeOrderFixture { + + static final String MAP = """ + {"M":{"k1":{"S":"1"},"k2":{"S":"2"},"k3":{"S":"3"},"k4":{"S":"4"},"k5":{"S":"5"},"k6":{"S":"6"}}}"""; + static final String ITEM = """ + {"pk":{"S":"k"},"a1":{"S":"1"},"a2":{"S":"2"},"a3":{"S":"3"},"a4":{"S":"4"},"a5":{"S":"5"},"m":%s} + """.formatted(MAP); + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private DynamoDbAttributeOrderFixture() { + } + + static String createTable(String prefix) { + String table = prefix + "-" + UUID.randomUUID(); + ddb("CreateTable", """ + {"TableName":"%s","BillingMode":"PAY_PER_REQUEST", + "KeySchema":[{"AttributeName":"pk","KeyType":"HASH"}], + "AttributeDefinitions":[{"AttributeName":"pk","AttributeType":"S"}]} + """.formatted(table)).statusCode(200); + return table; + } + + static void deleteTable(String table) { + ddb("DeleteTable", "{\"TableName\":\"" + table + "\"}").statusCode(200); + } + + static JsonNode call(String action, String body) { + String response = ddb(action, body).extract().asString(); + try { + return MAPPER.readTree(response); + } catch (Exception e) { + throw new IllegalStateException(response, e); + } + } + + static String order(JsonNode node) { + List names = new ArrayList<>(); + node.fieldNames().forEachRemaining(names::add); + return String.join(",", names); + } +} diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrderIntegrationTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrderIntegrationTest.java new file mode 100644 index 0000000000..0d4cfec112 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrderIntegrationTest.java @@ -0,0 +1,171 @@ +package io.floci.aws.services.dynamodb; + +import com.fasterxml.jackson.databind.JsonNode; +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.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Supplier; + +import static io.floci.aws.services.dynamodb.DynamoDbAttributeOrderFixture.ITEM; +import static io.floci.aws.services.dynamodb.DynamoDbAttributeOrderFixture.MAP; +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 org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class DynamoDbAttributeOrderIntegrationTest { + + private static final int CALLS = 30; + + private String table; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void createTestTable() { + table = createTable("attribute-order"); + } + + @AfterEach + void deleteTestTable() { + deleteTable(table); + } + + private void putItem() { + call("PutItem", "{\"TableName\":\"" + table + "\",\"Item\":" + ITEM + "}"); + } + + private static String topAndMapOrder(JsonNode item) { + return order(item) + "|" + order(item.get("m").get("M")); + } + + private static Set orders(Supplier itemSource) { + Set seen = new HashSet<>(); + for (int i = 0; i < CALLS; i++) { + seen.add(topAndMapOrder(itemSource.get())); + } + return seen; + } + + private static void assertShuffled(Set seen) { + assertTrue(seen.size() > 1, "expected more than one order but saw " + seen); + Set mapOrders = new HashSet<>(); + Set topOrders = new HashSet<>(); + for (String s : seen) { + String[] parts = s.split("\\|"); + topOrders.add(parts[0]); + mapOrders.add(parts[1]); + } + assertTrue(topOrders.size() > 1, "top-level order never changed"); + assertTrue(mapOrders.size() > 1, "map key order never changed"); + } + + private static void assertStable(Set seen) { + assertEquals(1, seen.size(), "expected one order but saw " + seen); + } + + @Test + void putItemAllOldShuffles() { + putItem(); + assertShuffled(orders(() -> call("PutItem", "{\"TableName\":\"" + table + "\",\"Item\":" + ITEM + + ",\"ReturnValues\":\"ALL_OLD\"}").get("Attributes"))); + } + + @Test + void updateItemReturnValuesShuffle() { + putItem(); + for (String mode : List.of("ALL_OLD", "ALL_NEW")) { + assertShuffled(orders(() -> call("UpdateItem", "{\"TableName\":\"" + table + + "\",\"Key\":{\"pk\":{\"S\":\"k\"}},\"UpdateExpression\":\"SET a1 = :v\"," + + "\"ExpressionAttributeValues\":{\":v\":{\"S\":\"1\"}},\"ReturnValues\":\"" + mode + "\"}") + .get("Attributes"))); + } + } + + @Test + void updateItemUpdatedValuesShuffleNestedMap() { + putItem(); + for (String mode : List.of("UPDATED_OLD", "UPDATED_NEW")) { + Set seen = new HashSet<>(); + for (int i = 0; i < CALLS; i++) { + JsonNode attributes = call("UpdateItem", "{\"TableName\":\"" + table + + "\",\"Key\":{\"pk\":{\"S\":\"k\"}},\"UpdateExpression\":\"SET m = :v\"," + + "\"ExpressionAttributeValues\":{\":v\":" + MAP + + "},\"ReturnValues\":\"" + mode + "\"}").get("Attributes"); + seen.add(order(attributes.get("m").get("M"))); + } + assertTrue(seen.size() > 1, mode + " saw " + seen); + } + } + + @Test + void deleteItemAllOldShuffles() { + assertShuffled(orders(() -> { + putItem(); + return call("DeleteItem", "{\"TableName\":\"" + table + + "\",\"Key\":{\"pk\":{\"S\":\"k\"}},\"ReturnValues\":\"ALL_OLD\"}").get("Attributes"); + })); + } + + @Test + void failedConditionItemShuffles() { + putItem(); + String conditionFails = ",\"ConditionExpression\":\"attribute_not_exists(pk)\"," + + "\"ReturnValuesOnConditionCheckFailure\":\"ALL_OLD\"}"; + assertShuffled(orders(() -> call("PutItem", "{\"TableName\":\"" + table + "\",\"Item\":" + ITEM + + conditionFails).get("Item"))); + assertShuffled(orders(() -> call("UpdateItem", "{\"TableName\":\"" + table + + "\",\"Key\":{\"pk\":{\"S\":\"k\"}},\"UpdateExpression\":\"SET a1 = :v\"," + + "\"ExpressionAttributeValues\":{\":v\":{\"S\":\"1\"}}" + conditionFails).get("Item"))); + assertShuffled(orders(() -> call("DeleteItem", "{\"TableName\":\"" + table + + "\",\"Key\":{\"pk\":{\"S\":\"k\"}}" + conditionFails).get("Item"))); + } + + @Test + void transactGetItemsShuffles() { + putItem(); + assertShuffled(orders(() -> call("TransactGetItems", "{\"TransactItems\":[{\"Get\":{\"TableName\":\"" + + table + "\",\"Key\":{\"pk\":{\"S\":\"k\"}}}}]}").get("Responses").get(0).get("Item"))); + assertShuffled(orders(() -> call("TransactGetItems", "{\"TransactItems\":[{\"Get\":{\"TableName\":\"" + + table + "\",\"Key\":{\"pk\":{\"S\":\"k\"}},\"ProjectionExpression\":\"pk, a1, m\"}}]}") + .get("Responses").get(0).get("Item"))); + } + + @Test + void transactWriteCancellationItemShuffles() { + putItem(); + assertShuffled(orders(() -> call("TransactWriteItems", "{\"TransactItems\":[{\"ConditionCheck\":" + + "{\"TableName\":\"" + table + "\",\"Key\":{\"pk\":{\"S\":\"k\"}}," + + "\"ConditionExpression\":\"attribute_not_exists(pk)\"," + + "\"ReturnValuesOnConditionCheckFailure\":\"ALL_OLD\"}}]}") + .get("CancellationReasons").get(0).get("Item"))); + } + + @Test + void getItemQueryAndPartiQlSelectKeepOneOrder() { + putItem(); + assertStable(orders(() -> call("GetItem", "{\"TableName\":\"" + table + + "\",\"Key\":{\"pk\":{\"S\":\"k\"}}}").get("Item"))); + assertStable(orders(() -> call("Query", "{\"TableName\":\"" + table + + "\",\"KeyConditionExpression\":\"pk = :p\",\"ExpressionAttributeValues\":{\":p\":{\"S\":\"k\"}}}") + .get("Items").get(0))); + assertStable(orders(() -> call("Scan", "{\"TableName\":\"" + table + "\"}").get("Items").get(0))); + assertStable(orders(() -> call("BatchGetItem", "{\"RequestItems\":{\"" + table + + "\":{\"Keys\":[{\"pk\":{\"S\":\"k\"}}]}}}").get("Responses").get(table).get(0))); + assertStable(orders(() -> call("ExecuteStatement", "{\"Statement\":\"SELECT * FROM \\\"" + table + + "\\\" WHERE pk = 'k'\"}").get("Items").get(0))); + } +} diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrderTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrderTest.java new file mode 100644 index 0000000000..ce5d5c1baa --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbAttributeOrderTest.java @@ -0,0 +1,153 @@ +package io.floci.aws.services.dynamodb; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.dynamodb.model.AttributeDefinition; +import io.floci.aws.services.dynamodb.model.KeySchemaElement; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static io.floci.aws.services.dynamodb.DynamoDbAttributeOrderFixture.ITEM; +import static io.floci.aws.services.dynamodb.DynamoDbAttributeOrderFixture.order; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class DynamoDbAttributeOrderTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String TABLE = "attribute-order"; + private static final String REGION = "us-east-1"; + + private static JsonNode json(String text) throws Exception { + return MAPPER.readTree(text); + } + + @Test + void mapShowsEverySixOrdersOverManyCalls() throws Exception { + JsonNode item = json("{\"m\":{\"M\":{\"a\":{\"S\":\"1\"},\"b\":{\"S\":\"2\"},\"c\":{\"S\":\"3\"}}}}"); + Set orders = new HashSet<>(); + for (int i = 0; i < 500; i++) { + orders.add(order(DynamoDbAttributeOrder.shuffled(item, true).get("m").get("M"))); + } + assertEquals(6, orders.size()); + } + + @Test + void topLevelAttributesShuffle() throws Exception { + JsonNode item = json("{\"a\":{\"S\":\"1\"},\"b\":{\"S\":\"2\"},\"c\":{\"S\":\"3\"}}"); + Set orders = new HashSet<>(); + for (int i = 0; i < 500; i++) { + orders.add(order(DynamoDbAttributeOrder.shuffled(item, true))); + } + assertEquals(6, orders.size()); + } + + @Test + void mapInsideListInsideMapShuffles() throws Exception { + JsonNode item = json("{\"o\":{\"M\":{\"l\":{\"L\":[{\"M\":{\"a\":{\"N\":\"1\"},\"b\":{\"N\":\"2\"}," + + "\"c\":{\"N\":\"3\"}}}]}}}}"); + Set orders = new HashSet<>(); + for (int i = 0; i < 500; i++) { + JsonNode inner = DynamoDbAttributeOrder.shuffled(item, true) + .get("o").get("M").get("l").get("L").get(0).get("M"); + orders.add(order(inner)); + } + assertEquals(6, orders.size()); + } + + @Test + void valuesSetsAndListsKeepTheirOrder() throws Exception { + JsonNode item = json("{\"ss\":{\"SS\":[\"z\",\"a\",\"m\"]},\"ns\":{\"NS\":[\"3\",\"1\"]}," + + "\"l\":{\"L\":[{\"S\":\"q\"},{\"N\":\"5\"},{\"S\":\"b\"}]},\"n\":{\"N\":\"7\"}," + + "\"m\":{\"M\":{\"x\":{\"SS\":[\"y\",\"x\"]}}}}"); + for (int i = 0; i < 50; i++) { + JsonNode shuffled = DynamoDbAttributeOrder.shuffled(item, true); + assertEquals(item.get("ss"), shuffled.get("ss")); + assertEquals(item.get("ns"), shuffled.get("ns")); + assertEquals(item.get("l"), shuffled.get("l")); + assertEquals(item.get("n"), shuffled.get("n")); + assertEquals(item.get("m"), shuffled.get("m")); + assertEquals(item.size(), shuffled.size()); + } + } + + @Test + void inputIsNotChanged() throws Exception { + JsonNode item = json("{\"a\":{\"S\":\"1\"},\"b\":{\"M\":{\"x\":{\"S\":\"1\"},\"y\":{\"S\":\"2\"}}}}"); + String before = item.toString(); + for (int i = 0; i < 50; i++) { + assertNotSame(item, DynamoDbAttributeOrder.shuffled(item, true)); + } + assertEquals(before, item.toString()); + } + + @Test + void disabledReturnsTheSameNode() throws Exception { + JsonNode item = json("{\"a\":{\"S\":\"1\"}}"); + assertSame(item, DynamoDbAttributeOrder.shuffled(item, false)); + } + + @Test + void nullStaysNull() { + assertNull(DynamoDbAttributeOrder.shuffled(null, true)); + } + + @Test + void storedOrderIsKeptWhenTheSettingIsOff() throws Exception { + Orders orders = handlerOrders(false); + assertEquals(1, orders.top().size(), orders.top().toString()); + assertEquals(Set.of("k1,k2,k3,k4,k5,k6"), orders.map()); + } + + @Test + void returnValuesShuffleWhenTheSettingIsOn() throws Exception { + Orders orders = handlerOrders(true); + assertTrue(orders.top().size() > 1, orders.top().toString()); + assertTrue(orders.map().size() > 1, orders.map().toString()); + } + + private record Orders(Set top, Set map) { + } + + private static Orders handlerOrders(boolean randomize) throws Exception { + Orders orders = new Orders(new HashSet<>(), new HashSet<>()); + DynamoDbService service = new DynamoDbService(new InMemoryStorage<>()); + service.createTable(TABLE, List.of(new KeySchemaElement("pk", "HASH")), + List.of(new AttributeDefinition("pk", "S")), 5L, 5L, REGION); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().dynamodb().randomizeAttributeOrder()).thenReturn(randomize); + NativeDynamoDbJsonHandler handler = new NativeDynamoDbJsonHandler(service, + new NativeDynamoDbTableService(service, null, null), MAPPER, config); + JsonNode put = json("{\"TableName\":\"" + TABLE + "\",\"Item\":" + ITEM + + ",\"ReturnValues\":\"ALL_OLD\"}"); + JsonNode transactGet = json("{\"TransactItems\":[{\"Get\":{\"TableName\":\"" + TABLE + + "\",\"Key\":{\"pk\":{\"S\":\"k\"}}}}]}"); + handler.handle("PutItem", put, REGION); + for (int i = 0; i < 20; i++) { + JsonNode attributes = body(handler.handle("PutItem", put, REGION)).get("Attributes"); + orders.top().add(order(attributes)); + orders.map().add(order(attributes.get("m").get("M"))); + JsonNode transacted = body(handler.handle("TransactGetItems", transactGet, REGION)) + .get("Responses").get(0).get("Item"); + orders.top().add(order(transacted)); + orders.map().add(order(transacted.get("m").get("M"))); + } + return orders; + } + + private static JsonNode body(Response response) { + return MAPPER.convertValue(response.getEntity(), JsonNode.class); + } +} 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 56937769e3..077e917153 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 @@ -77,7 +77,8 @@ class DynamoDbNativeBackendTest { DynamoDbService service = new DynamoDbService(storageFactory, new RegionResolver(REGION, ACCOUNT), streams, forwarder, null, mapper, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS)); NativeDynamoDbTableService tables = new NativeDynamoDbTableService(service, streams, mock(KinesisService.class)); - backend = new NativeDynamoDbBackend(new NativeDynamoDbJsonHandler(service, tables, mapper, mock(EmulatorConfig.class)), + backend = new NativeDynamoDbBackend(new NativeDynamoDbJsonHandler(service, tables, mapper, + mock(EmulatorConfig.class, RETURNS_DEEP_STUBS)), new NativeDynamoDbStreamsJsonHandler(streams, service, new RegionResolver(REGION, ACCOUNT), mapper), tables, service, streams, ttl, mapper); } diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 3a36f836a8..487a6ed55e 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -162,6 +162,7 @@ floci: vector-index-allocation-seconds: 0 vector-index-backfill-seconds: 0 latest-restorable-lag-seconds: 0 + randomize-attribute-order: true backend: native sns: enabled: true