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
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-22 09:13:53 -04:00
1 parent e295f9ed12
commit a966242daf
11 files changed
+513 -15

No files matched your search

@@ -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 |
+11
View File
@@ -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 |
@@ -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();
@@ -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<String, JsonNode>[] entries = new Map.Entry[n];
int i = 0;
for (Map.Entry<String, JsonNode> 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<String, JsonNode> swap = entries[j];
entries[j] = entries[k];
entries[k] = swap;
}
Map<String, JsonNode> map = new LinkedHashMap<>((int) (n / 0.75f) + 1);
for (Map.Entry<String, JsonNode> entry : entries) {
map.put(entry.getKey(), shuffleValue(entry.getValue()));
}
return new ObjectNode(FACTORY, map);
}
private static ObjectNode wrap(String key, JsonNode value) {
Map<String, JsonNode> 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;
}
}
@@ -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> T withShuffledFailureItem(Supplier<T> 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<JsonNode> 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<JsonNode> 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<JsonNode> 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);
}
+1
View File
@@ -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
@@ -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<String> names = new ArrayList<>();
node.fieldNames().forEachRemaining(names::add);
return String.join(",", names);
}
}
@@ -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<String> orders(Supplier<JsonNode> itemSource) {
Set<String> seen = new HashSet<>();
for (int i = 0; i < CALLS; i++) {
seen.add(topAndMapOrder(itemSource.get()));
}
return seen;
}
private static void assertShuffled(Set<String> seen) {
assertTrue(seen.size() > 1, "expected more than one order but saw " + seen);
Set<String> mapOrders = new HashSet<>();
Set<String> 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<String> 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<String> 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)));
}
}
@@ -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<String> 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<String> 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<String> 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<String> top, Set<String> 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);
}
}
@@ -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);
}
+1
View File
@@ -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