diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md index 7b78484bb4..8b736eb57c 100644 --- a/docs/configuration/advanced/application-yml.md +++ b/docs/configuration/advanced/application-yml.md @@ -162,6 +162,7 @@ floci: dynamodb: enabled: true + transaction-conflicts-enabled: false # reject requests that reach a transaction's busy items, as AWS does (native only) backend: native # native | local (forward calls to DynamoDB Local) # local-endpoint: http://dynamodb-local:8000 # DynamoDB Local base URL, required when backend is local local-connect-timeout-seconds: 2 # Seconds to wait for a connection to DynamoDB Local diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 80b95d7e81..1d3861750f 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -297,6 +297,7 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s | Variable | Default | Description | |---|---|---| | `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_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 1bca6bae3d..07f7db63b6 100644 --- a/docs/services/dynamodb.md +++ b/docs/services/dynamodb.md @@ -186,6 +186,31 @@ records behind, for example one that starts at `LATEST` before a large seed, rai the shard that replaced it has closed too, so a stream that rolls over lists at most two generations of shards while idle, and otherwise only the shards that still hold records. +## Transaction conflicts + +By default, transactions that touch the same items wait for each other and then all go through, +one at a time. On AWS, a `TransactWriteItems` keeps its items busy until it commits, and requests +that reach a busy item are rejected instead: + +- a `PutItem`, `UpdateItem` or `DeleteItem`, or a PartiQL `ExecuteStatement` that writes one item, + fails with `TransactionConflictException`; +- another `TransactWriteItems`, or a `TransactGetItems`, is cancelled with + `TransactionCanceledException`, and the item gets the reason `TransactionConflict` + ("Transaction is ongoing for the item"). Its other items get `None`; +- a `GetItem`, `Query` or `Scan` is not affected. + +To exercise code that handles those failures, such as a retry loop, set +`FLOCI_SERVICES_DYNAMODB_TRANSACTION_CONFLICTS_ENABLED=true`. A `TransactWriteItems` then keeps its +items busy from the moment its conditions hold until 10 milliseconds after it commits, about as long +as a write transaction takes on AWS, and answers when that time is up. A client that waits for one transaction before it sends +the next never sees a conflict; requests that overlap a transaction on its items do. A cancelled or +rejected request changes nothing, so it can be retried as it was sent. + +The busy time is fixed, so the share of transactions that conflict under a given load is not AWS's. +A `BatchWriteItem`, or a write that is not part of a transaction, does not make other requests +conflict. The setting works with the native backend only; with the `local` backend Floci does not +start. + ## Time to Live With TTL enabled, a sweep runs every 60 seconds and deletes the items whose TTL attribute holds an @@ -318,6 +343,7 @@ region is rejected. | `FLOCI_SERVICES_DYNAMODB_STREAM_ITERATOR_EXPIRY_ENABLED` | `false` | Expire stream shard iterators 15 minutes after they are returned, as AWS does | | `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_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 3e07921da1..ff54ebb0ed 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -1732,6 +1732,16 @@ public interface EmulatorConfig { @WithDefault("1000") int streamMaxRecords(); + /** + * Emulates the transaction conflicts DynamoDB reports under contention: a TransactWriteItems keeps its + * items busy for a few milliseconds, so a PutItem, UpdateItem or DeleteItem on one fails with + * TransactionConflictException and another TransactWriteItems or a TransactGetItems is cancelled with + * TransactionConflict. Off, overlapping transactions serialize instead. The native backend only. + * Env: FLOCI_SERVICES_DYNAMODB_TRANSACTION_CONFLICTS_ENABLED. + */ + @WithDefault("false") + boolean transactionConflictsEnabled(); + /** 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/DynamoDbService.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java index 64f741545c..f5b1df93c4 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java @@ -184,6 +184,7 @@ public class DynamoDbService { private DynamoDbStreamService streamService; private KinesisStreamingForwarder kinesisForwarder; private S3Service s3Service; + private DynamoDbTransactionConflicts transactionConflicts = DynamoDbTransactionConflicts.OFF; private final int vectorIndexAllocationSeconds; private final int vectorIndexBackfillSeconds; private static final long MAX_DYNAMODB_LIST_INDEX = 4_294_967_294L; @@ -210,6 +211,13 @@ public class DynamoDbService { config.services().dynamodb().vectorIndexAllocationSeconds(), config.services().dynamodb().vectorIndexBackfillSeconds(), config.services().dynamodb().latestRestorableLagSeconds(), Clock.systemUTC()); + this.transactionConflicts = DynamoDbTransactionConflicts.of( + config.services().dynamodb().transactionConflictsEnabled()); + } + + /** Package-private for tests: the transaction conflict emulation this service applies. */ + void useTransactionConflicts(DynamoDbTransactionConflicts transactionConflicts) { + this.transactionConflicts = transactionConflicts; } /** The item store the configured {@code item-layout} selects; package-private for tests. */ @@ -354,6 +362,7 @@ public class DynamoDbService { /** Emulator reset: drops the in-process item cache, locks and idempotency tokens, and stream state. */ public void clearProcessState() { itemsByTable.clear(); + transactionConflicts.clear(); itemLocks.clear(); txIdempotency.clear(); pointInTimeRecovery.clear(); @@ -1166,7 +1175,7 @@ public class DynamoDbService { String canonicalTableName = canonicalTableName(region, tableName); requireActiveTable(regionKey(region, canonicalTableName)); return putItemInternal(tableName, item, conditionExpression, exprAttrNames, exprAttrValues, - region, returnValuesOnConditionCheckFailure, true, null, null, existingItemCheck); + region, returnValuesOnConditionCheckFailure, true, null, null, existingItemCheck, true); } private JsonNode putItemInternal(String tableName, JsonNode item, @@ -1185,7 +1194,7 @@ public class DynamoDbService { boolean shouldPersist, Consumer deferredStreamEvents) { return putItemInternal(tableName, item, conditionExpression, exprAttrNames, exprAttrValues, - region, returnValuesOnConditionCheckFailure, shouldPersist, deferredStreamEvents, null, null); + region, returnValuesOnConditionCheckFailure, shouldPersist, deferredStreamEvents, null, null, false); } private JsonNode putItemInternal(String tableName, JsonNode item, @@ -1195,7 +1204,8 @@ public class DynamoDbService { boolean shouldPersist, Consumer deferredStreamEvents, Map> stagedItems, - Consumer existingItemCheck) { + Consumer existingItemCheck, + boolean singleItemWrite) { String canonicalTableName = canonicalTableName(region, tableName); String storageKey = regionKey(region, canonicalTableName); TableDefinition table = tableStore.get(storageKey) @@ -1208,6 +1218,9 @@ public class DynamoDbService { validateIndexKeyTypes(table, normalizedItem, false); return withItemLock(storageKey, itemKey, () -> { + if (singleItemWrite) { + transactionConflicts.rejectSingleItemWrite(scopedItemsKey(storageKey), itemKey); + } ConcurrentSkipListMap tableItems = itemsFor(storageKey, stagedItems, true); JsonNode existing = tableItems.get(itemKey); @@ -1290,7 +1303,7 @@ public class DynamoDbService { String region, String returnValuesOnConditionCheckFailure, Consumer existingItemCheck) { return deleteItemInternal(tableName, key, conditionExpression, exprAttrNames, exprAttrValues, - region, returnValuesOnConditionCheckFailure, true, null, null, existingItemCheck); + region, returnValuesOnConditionCheckFailure, true, null, null, existingItemCheck, true); } private JsonNode deleteItemInternal(String tableName, JsonNode key, @@ -1309,7 +1322,7 @@ public class DynamoDbService { boolean shouldPersist, Consumer deferredStreamEvents) { return deleteItemInternal(tableName, key, conditionExpression, exprAttrNames, exprAttrValues, - region, returnValuesOnConditionCheckFailure, shouldPersist, deferredStreamEvents, null, null); + region, returnValuesOnConditionCheckFailure, shouldPersist, deferredStreamEvents, null, null, false); } private JsonNode deleteItemInternal(String tableName, JsonNode key, @@ -1319,7 +1332,8 @@ public class DynamoDbService { boolean shouldPersist, Consumer deferredStreamEvents, Map> stagedItems, - Consumer existingItemCheck) { + Consumer existingItemCheck, + boolean singleItemWrite) { String canonicalTableName = canonicalTableName(region, tableName); String storageKey = regionKey(region, canonicalTableName); TableDefinition table = requireActiveTable(storageKey); @@ -1327,6 +1341,9 @@ public class DynamoDbService { String itemKey = buildItemKey(table, key, true); return withItemLock(storageKey, itemKey, () -> { + if (singleItemWrite) { + transactionConflicts.rejectSingleItemWrite(scopedItemsKey(storageKey), itemKey); + } ConcurrentSkipListMap items = itemsFor(storageKey, stagedItems, false); if (existingItemCheck != null) { existingItemCheck.accept(items == null ? null : items.get(itemKey)); @@ -1404,7 +1421,7 @@ public class DynamoDbService { return updateItemInternal(tableName, key, attributeUpdates, updateExpression, expressionAttrNames, expressionAttrValues, returnValues, conditionExpression, region, returnValuesOnConditionCheckFailure, true, null, null, - UpdateSizeRule.UPDATE_ITEM, existingItemCheck); + UpdateSizeRule.UPDATE_ITEM, existingItemCheck, true); } UpdateResult updateItem(String tableName, JsonNode key, JsonNode attributeUpdates, @@ -1415,7 +1432,8 @@ public class DynamoDbService { UpdateSizeRule sizeRule) { return updateItemInternal(tableName, key, attributeUpdates, updateExpression, expressionAttrNames, expressionAttrValues, returnValues, - conditionExpression, region, returnValuesOnConditionCheckFailure, true, sizeRule); + conditionExpression, region, returnValuesOnConditionCheckFailure, true, null, null, sizeRule, + null, true); } private UpdateResult updateItemInternal(String tableName, JsonNode key, JsonNode attributeUpdates, @@ -1442,7 +1460,7 @@ public class DynamoDbService { return updateItemInternal(tableName, key, attributeUpdates, updateExpression, expressionAttrNames, expressionAttrValues, returnValues, conditionExpression, region, returnValuesOnConditionCheckFailure, shouldPersist, - deferredStreamEvents, null, sizeRule, null); + deferredStreamEvents, null, sizeRule, null, false); } private UpdateResult updateItemInternal(String tableName, JsonNode key, JsonNode attributeUpdates, @@ -1454,7 +1472,8 @@ public class DynamoDbService { Consumer deferredStreamEvents, Map> stagedItems, UpdateSizeRule sizeRule, - Consumer existingItemCheck) { + Consumer existingItemCheck, + boolean singleItemWrite) { String canonicalTableName = canonicalTableName(region, tableName); String storageKey = regionKey(region, canonicalTableName); TableDefinition table = requireActiveTable(storageKey); @@ -1468,6 +1487,9 @@ public class DynamoDbService { } return withItemLock(storageKey, itemKey, () -> { + if (singleItemWrite) { + transactionConflicts.rejectSingleItemWrite(scopedItemsKey(storageKey), itemKey); + } ConcurrentSkipListMap items = itemsFor(storageKey, stagedItems, true); // Get existing item or create new one from key @@ -2170,11 +2192,15 @@ public class DynamoDbService { } List acquired = new ArrayList<>(toAcquire.size()); + List held = List.of(); + long holdDeadline = 0; + boolean committed = false; try { for (ReentrantLock lock : toAcquire.values()) { lock.lock(); acquired.add(lock); } + rejectHeldParticipants(memberParticipants); List pendingStreamEvents = new ArrayList<>(); Set affectedStorageKeys = new LinkedHashSet<>(); @@ -2209,6 +2235,10 @@ public class DynamoDbService { if (hasFailed) { throw new TransactionCanceledException(cancellationReasons); } + held = toAcquire.keySet().stream() + .map(p -> new DynamoDbTransactionConflicts.Item(scopedItemsKey(p.storageKey()), p.itemKey())) + .toList(); + holdDeadline = transactionConflicts.hold(held); List oldImages = stagedImages(memberParticipants, staged); for (JsonNode transactItem : transactItems) { if (transactItem.has("Put")) { @@ -2216,14 +2246,14 @@ public class DynamoDbService { String tableName = put.path("TableName").asText(); String storageKey = regionKey(region, canonicalTableName(region, tableName)); putItemInternal(tableName, put.get("Item"), null, null, null, region, "NONE", false, - pendingStreamEvents::add, staged, null); + pendingStreamEvents::add, staged, null, false); affectedStorageKeys.add(storageKey); } else if (transactItem.has("Delete")) { JsonNode del = transactItem.get("Delete"); String tableName = del.path("TableName").asText(); String storageKey = regionKey(region, canonicalTableName(region, tableName)); deleteItemInternal(tableName, del.get("Key"), null, null, null, region, "NONE", false, - pendingStreamEvents::add, staged, null); + pendingStreamEvents::add, staged, null, false); affectedStorageKeys.add(storageKey); } else if (transactItem.has("Update")) { JsonNode upd = transactItem.get("Update"); @@ -2234,7 +2264,7 @@ public class DynamoDbService { upd.has("ExpressionAttributeNames") ? upd.get("ExpressionAttributeNames") : null, upd.has("ExpressionAttributeValues") ? upd.get("ExpressionAttributeValues") : null, "NONE", null, region, "NONE", false, pendingStreamEvents::add, staged, - UpdateSizeRule.FINISHED_ITEM, null); + UpdateSizeRule.FINISHED_ITEM, null, false); affectedStorageKeys.add(storageKey); } } @@ -2272,11 +2302,39 @@ public class DynamoDbService { for (Runnable streamEvent : pendingStreamEvents) { streamEvent.run(); } + holdDeadline = transactionConflicts.settle(held, holdDeadline); + committed = true; return new AppliedTransactWrite(writeCapacity, replayCapacity); } finally { for (int i = acquired.size() - 1; i >= 0; i--) { acquired.get(i).unlock(); } + transactionConflicts.release(held, holdDeadline, committed); + } + } + + /** + * With transaction conflicts emulated, cancels a write transaction one of whose items another write + * transaction holds, with {@code TransactionConflict} at that item, before any condition is evaluated. + */ + private void rejectHeldParticipants(List memberParticipants) { + if (!transactionConflicts.enabled()) { + return; + } + List reasons = new ArrayList<>(); + boolean conflicted = false; + for (TransactParticipant participant : memberParticipants) { + if (participant != null + && transactionConflicts.busy(scopedItemsKey(participant.storageKey()), participant.itemKey())) { + conflicted = true; + reasons.add(new TransactionCanceledException.CancellationReason( + DynamoDbTransactionConflicts.REASON, null, DynamoDbTransactionConflicts.MESSAGE)); + } else { + reasons.add(new TransactionCanceledException.CancellationReason("", null)); + } + } + if (conflicted) { + throw new TransactionCanceledException(reasons); } } @@ -2578,9 +2636,18 @@ public class DynamoDbService { JsonNode key = get.get("Key"); try { JsonNode item = getItem(tableName, key, region); + TableDefinition table = requireTableForItemCall(tableName, region); + String itemsKey = scopedItemsKey(regionKey(region, canonicalTableName(region, tableName))); + if (transactionConflicts.busy(itemsKey, buildItemKey(table, key, true))) { + hasCancelled = true; + results.add(null); + cancelReasons.add(new TransactionCanceledException.CancellationReason( + DynamoDbTransactionConflicts.REASON, null, DynamoDbTransactionConflicts.MESSAGE)); + continue; + } results.add(projectTransactGet(item, get)); capacity.merge(canonicalTableName(region, tableName), - DynamoDbTransactCapacity.read(requireTableForItemCall(tableName, region), item, null), + DynamoDbTransactCapacity.read(table, item, null), DynamoDbWriteCapacity.Cost::plus); cancelReasons.add(new TransactionCanceledException.CancellationReason("", null)); } catch (AwsException e) { diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbTransactionConflicts.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbTransactionConflicts.java new file mode 100644 index 0000000000..ab6689c710 --- /dev/null +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbTransactionConflicts.java @@ -0,0 +1,169 @@ +package io.floci.aws.services.dynamodb; + +import io.floci.aws.core.common.AwsException; + +import java.time.Duration; +import java.util.Collection; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.LockSupport; +import java.util.function.LongSupplier; + +/** + * Opt-in emulation of the transaction conflicts DynamoDB reports under contention, switched on by + * {@code floci.services.dynamodb.transaction-conflicts-enabled}. + * + *

On AWS a TransactWriteItems keeps each of its items busy from the moment the item accepts the + * transaction until the transaction commits. The developer guide rejects a PutItem, UpdateItem or + * DeleteItem on a busy item with {@code TransactionConflictException}, and cancels another + * TransactWriteItems, or a TransactGetItems, that reaches one with the reason {@code TransactionConflict}; + * a GetItem is not affected. Floci applies a transaction in microseconds, so with the switch on a write + * transaction marks its items busy from the moment they accept it until {@link #HOLD} after it commits, and + * answers only when that time is up: a caller that waits for one transaction before it sends the next never + * sees a conflict, callers that overlap do. The mark is a deadline kept beside the item, so no item lock is + * held while a transaction waits. + * + *

Off, the default, every method is a no-op and overlapping transactions keep serializing on their + * item locks. + */ +final class DynamoDbTransactionConflicts { + + /** + * How long a write transaction keeps its items busy. DynamoDB answers in single-digit milliseconds, and + * a write transaction takes about four times as long as a PutItem ("Distributed Transactions at Scale in + * Amazon DynamoDB", USENIX ATC 2023). + */ + static final Duration HOLD = Duration.ofMillis(10); + + static final String REASON = "TransactionConflict"; + + /** The message AWS gives the {@code TransactionConflict} reason and {@code TransactionConflictException}. */ + static final String MESSAGE = "Transaction is ongoing for the item"; + + /** How far ahead a mark is dated while its transaction still commits, so it cannot lapse before {@link #settle}. */ + private static final long WHILE_COMMITTING_NANOS = Long.MAX_VALUE / 4; + + static final DynamoDbTransactionConflicts OFF = new DynamoDbTransactionConflicts(false, HOLD, System::nanoTime, + DynamoDbTransactionConflicts::park); + + /** One item of one table: the table's account-scoped items key and the item key. */ + record Item(String table, String itemKey) {} + + /** Waits until {@code deadlineNanos} on the clock {@code nanoTime} reads. */ + @FunctionalInterface + interface Waiter { + void awaitDeadline(long deadlineNanos, LongSupplier nanoTime); + } + + private final boolean enabled; + private final long holdNanos; + private final LongSupplier nanoTime; + private final Waiter waiter; + private final ConcurrentHashMap busyUntil = new ConcurrentHashMap<>(); + + DynamoDbTransactionConflicts(boolean enabled, Duration hold, LongSupplier nanoTime, Waiter waiter) { + this.enabled = enabled; + this.holdNanos = hold.toNanos(); + this.nanoTime = nanoTime; + this.waiter = waiter; + } + + /** The emulation the configuration asks for. */ + static DynamoDbTransactionConflicts of(boolean enabled) { + return enabled ? new DynamoDbTransactionConflicts(true, HOLD, System::nanoTime, + DynamoDbTransactionConflicts::park) : OFF; + } + + boolean enabled() { + return enabled; + } + + /** Whether a write transaction in flight holds the item now. */ + boolean busy(String table, String itemKey) { + if (!enabled) { + return false; + } + Long until = busyUntil.get(new Item(table, itemKey)); + return until != null && until - nanoTime.getAsLong() > 0; + } + + /** Rejects a single-item write, a PutItem, UpdateItem, DeleteItem or PartiQL statement, on a held item. */ + void rejectSingleItemWrite(String table, String itemKey) { + if (busy(table, itemKey)) { + throw new AwsException("TransactionConflictException", MESSAGE, 400); + } + } + + /** + * Marks a write transaction's items busy, called while it holds their locks and after its conditions + * held. The marks last until {@link #settle} dates them, however long the commit takes. Returns the + * value the marks carry, or 0 when the emulation is off. + */ + long hold(Collection items) { + if (!enabled || items.isEmpty()) { + return 0; + } + long mark = nanoTime.getAsLong() + WHILE_COMMITTING_NANOS; + for (Item item : items) { + busyUntil.put(item, mark); + } + return mark; + } + + /** + * Starts the {@link #HOLD} of a transaction that has committed, called while it still holds its item locks, + * so the window counts from the moment it would answer. Returns the deadline its marks now carry, for + * {@link #release}, or 0 when nothing was held. + */ + long settle(Collection items, long mark) { + if (mark == 0) { + return 0; + } + long deadline = nanoTime.getAsLong() + holdNanos; + for (Item item : items) { + busyUntil.replace(item, mark, deadline); + } + return deadline; + } + + /** + * Ends a transaction's hold, called once it has released its item locks: a committed transaction first + * waits out the hold, as it would still be running on AWS, and one that failed does not. Only marks + * this transaction set are removed. + */ + void release(Collection items, long deadline, boolean committed) { + if (deadline == 0) { + return; + } + try { + if (committed) { + waiter.awaitDeadline(deadline, nanoTime); + } + } finally { + for (Item item : items) { + busyUntil.remove(item, deadline); + } + } + } + + /** Emulator reset: forgets every mark. */ + void clear() { + busyUntil.clear(); + } + + /** + * Waits until the deadline. An interrupt does not cut the hold short, since overlapping requests would then + * get through while the transaction is still meant to be running: the wait goes on, and the interrupt + * status is restored once it ends. + */ + static void park(long deadlineNanos, LongSupplier nanoTime) { + boolean interrupted = false; + long remaining; + while ((remaining = deadlineNanos - nanoTime.getAsLong()) > 0) { + LockSupport.parkNanos(remaining); + interrupted |= Thread.interrupted(); + } + if (interrupted) { + Thread.currentThread().interrupt(); + } + } +} 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 d4d2003a32..ab0bc1e50f 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java +++ b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java @@ -3365,7 +3365,7 @@ public class NativeDynamoDbJsonHandler { ObjectNode r = objectMapper.createObjectNode(); r.put("Code", reason.code().isEmpty() ? "None" : reason.code()); if (!reason.code().isEmpty()) { - r.put("Message", ""); + r.put("Message", reason.message() != null ? reason.message() : ""); } if (reason.item() != null) { r.set("Item", reason.item()); diff --git a/src/main/java/io/floci/aws/services/dynamodb/backend/DynamoDbBackendSelector.java b/src/main/java/io/floci/aws/services/dynamodb/backend/DynamoDbBackendSelector.java index fedbf87282..5e816cef4b 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/backend/DynamoDbBackendSelector.java +++ b/src/main/java/io/floci/aws/services/dynamodb/backend/DynamoDbBackendSelector.java @@ -32,6 +32,11 @@ public class DynamoDbBackendSelector { default -> throw new IllegalStateException( "floci.services.dynamodb.backend must be 'native' or 'local', got '" + configured + "'"); }; + // DynamoDB Local applies its own transactions, so Floci has nothing to emulate the conflicts in. + if ("local".equals(selected) && config.services().dynamodb().transactionConflictsEnabled()) { + throw new IllegalStateException("floci.services.dynamodb.transaction-conflicts-enabled needs the native " + + "backend; floci.services.dynamodb.backend is 'local'"); + } } /** The selected engine name, {@code native} or {@code local}. */ diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 95127c2402..56b008416f 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -485,6 +485,7 @@ floci: stream-iterator-expiry-enabled: false # FLOCI_SERVICES_DYNAMODB_STREAM_ITERATOR_EXPIRY_ENABLED. 15-minute iterators. 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). 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/DynamoDbTransactionConflictsServiceTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbTransactionConflictsServiceTest.java new file mode 100644 index 0000000000..e62236ed9d --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbTransactionConflictsServiceTest.java @@ -0,0 +1,236 @@ +package io.floci.aws.services.dynamodb; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; +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.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The opt-in transaction conflict emulation at the service: what a write transaction's busy items reject + * while it holds them, and that nothing is held once it answers or when it fails. + */ +class DynamoDbTransactionConflictsServiceTest { + + private static final String REGION = "us-east-1"; + private static final String TABLE = "Counters"; + + private final ObjectMapper mapper = new ObjectMapper(); + // The marks never expire on their own here: a transaction's hold ends when the test releases it. + private final AtomicLong clock = new AtomicLong(1_000_000_000L); + private final AtomicInteger holds = new AtomicInteger(); + private final CountDownLatch firstHolding = new CountDownLatch(1); + private final CountDownLatch releaseFirst = new CountDownLatch(1); + private DynamoDbService service; + + @BeforeEach + void setUp() { + service = new DynamoDbService(new InMemoryStorage<>()); + service.createTable(TABLE, List.of(new KeySchemaElement("pk", "HASH")), + List.of(new AttributeDefinition("pk", "S")), 5L, 5L, REGION); + // The first committed transaction stays inside its hold until the test lets it go; later ones answer at once. + service.useTransactionConflicts(new DynamoDbTransactionConflicts(true, Duration.ofMillis(10), clock::get, + (deadline, nanoTime) -> { + if (holds.incrementAndGet() == 1) { + firstHolding.countDown(); + awaitQuietly(releaseFirst); + } + })); + } + + // Catches: requests that overlap a write transaction on its items waiting for it, as they do by default, + // instead of failing the way AWS fails them, so a caller's TransactionConflict handling never runs. + @Test + void requestsOnTheItemsOfATransactionInFlightAreRejectedAndTheRestGoThrough() throws Exception { + service.putItem(TABLE, item("hot", 0), REGION); + AtomicReference firstFailure = new AtomicReference<>(); + Thread first = Thread.ofPlatform().start(() -> { + try { + service.transactWriteItems(List.of(increment("hot")), REGION); + } catch (Throwable t) { + firstFailure.set(t); + } + }); + assertTrue(firstHolding.await(10, TimeUnit.SECONDS), "the first transaction never reached its hold"); + + TransactionCanceledException write = assertThrows(TransactionCanceledException.class, + () -> service.transactWriteItems(List.of(put("other"), increment("hot")), REGION)); + assertEquals(List.of("", "TransactionConflict"), codes(write)); + assertEquals("Transaction is ongoing for the item", write.getCancellationReasons().get(1).message()); + assertEquals("Transaction cancelled, please refer cancellation reasons for specific reasons " + + "[None, TransactionConflict]", write.getMessage()); + TransactionCanceledException read = assertThrows(TransactionCanceledException.class, + () -> service.transactGetItems(List.of(get("other"), get("hot")), REGION)); + assertEquals(List.of("", "TransactionConflict"), codes(read)); + NativeDynamoDbJsonHandler handler = new NativeDynamoDbJsonHandler(service, null, null, mapper); + Response wire = handler.handle("TransactWriteItems", json("{\"TransactItems\":[" + increment("hot") + "]}"), REGION); + assertEquals(400, wire.getStatus()); + JsonNode reason = mapper.convertValue(wire.getEntity(), JsonNode.class).path("CancellationReasons").get(0); + assertEquals("TransactionConflict", reason.path("Code").asText()); + assertEquals("Transaction is ongoing for the item", reason.path("Message").asText()); + Response wireRead = handler.handle("TransactGetItems", json("{\"TransactItems\":[" + get("hot") + "]}"), REGION); + JsonNode readReason = mapper.convertValue(wireRead.getEntity(), JsonNode.class).path("CancellationReasons").get(0); + assertEquals("TransactionConflict", readReason.path("Code").asText()); + assertEquals("Transaction is ongoing for the item", readReason.path("Message").asText()); + assertEquals("TransactionConflictException", assertThrows(AwsException.class, () -> handler.handle( + "ExecuteStatement", json("{\"Statement\":\"UPDATE \\\"Counters\\\" SET n = 9 WHERE pk = 'hot'\"}"), REGION)) + .getErrorCode()); + assertEquals("TransactionConflictException", assertThrows(AwsException.class, + () -> service.putItem(TABLE, item("hot", 9), REGION)).getErrorCode()); + // The conflict is reported before a condition that would fail too. + assertEquals("TransactionConflictException", assertThrows(AwsException.class, + () -> service.updateItem(TABLE, key("hot"), null, "SET n = :n", null, json("{\":n\":{\"N\":\"9\"}}"), + "NONE", "attribute_not_exists(pk)", REGION, "NONE")).getErrorCode()); + assertEquals("TransactionConflictException", assertThrows(AwsException.class, + () -> service.deleteItem(TABLE, key("hot"), REGION)).getErrorCode()); + // A GetItem is not affected, and items the transaction does not hold are not either. + assertNotNull(service.getItem(TABLE, key("hot"), REGION)); + service.putItem(TABLE, item("cold", 1), REGION); + service.transactWriteItems(List.of(put("cold-too")), REGION); + + releaseFirst.countDown(); + first.join(TimeUnit.SECONDS.toMillis(10)); + assertNull(firstFailure.get()); + // What was rejected changed nothing; the transaction that held the item went through once. + assertEquals("1", counter("hot")); + assertNull(service.getItem(TABLE, key("other"), REGION)); + } + + // Catches: a caller that waits for each transaction before it sends the next being told of a conflict + // with its own earlier, finished transaction. + @Test + void aTransactionSentAfterTheLastOneAnsweredGoesThrough() { + service.putItem(TABLE, item("hot", 0), REGION); + releaseFirst.countDown(); + + service.transactWriteItems(List.of(increment("hot")), REGION); + service.transactWriteItems(List.of(increment("hot")), REGION); + service.putItem(TABLE, item("hot", 5), REGION); + service.transactGetItems(List.of(get("hot")), REGION); + + assertEquals("5", counter("hot")); + } + + // Catches: a transaction cancelled by its own condition keeping its items busy, so it blocks requests + // although it changed nothing. + @Test + void aTransactionThatFailsHoldsNothing() { + service.putItem(TABLE, item("hot", 0), REGION); + + assertThrows(TransactionCanceledException.class, () -> service.transactWriteItems(List.of( + json("{\"Put\":{\"TableName\":\"Counters\",\"Item\":{\"pk\":{\"S\":\"hot\"}}," + + "\"ConditionExpression\":\"attribute_not_exists(pk)\"}}")), REGION)); + + service.putItem(TABLE, item("hot", 1), REGION); + assertEquals(0, holds.get()); + } + + // Catches: the issue's contention, many callers adding to one counter in transactions, losing or repeating + // an increment, or failing in some way other than the TransactionConflict cancellation. + @Test + void contendingTransactionsEitherCommitOnceOrAreCancelledWithTransactionConflict() throws Exception { + service.useTransactionConflicts(DynamoDbTransactionConflicts.of(true)); + service.putItem(TABLE, item("hot", 0), REGION); + int threads = 12; + int callsEach = 15; + CountDownLatch start = new CountDownLatch(1); + AtomicInteger committed = new AtomicInteger(); + AtomicInteger conflicted = new AtomicInteger(); + List> callers = new ArrayList<>(); + try (ExecutorService pool = Executors.newFixedThreadPool(threads)) { + for (int t = 0; t < threads; t++) { + callers.add(pool.submit(() -> { + awaitQuietly(start); + for (int call = 0; call < callsEach; call++) { + try { + service.transactWriteItems(List.of(increment("hot"), put(UUID.randomUUID().toString())), REGION); + committed.incrementAndGet(); + } catch (TransactionCanceledException e) { + assertEquals("TransactionConflict", e.getCancellationReasons().get(0).code()); + conflicted.incrementAndGet(); + } + } + return null; + })); + } + start.countDown(); + for (Future caller : callers) { + caller.get(60, TimeUnit.SECONDS); + } + } + + assertEquals(threads * callsEach, committed.get() + conflicted.get()); + assertEquals(String.valueOf(committed.get()), counter("hot")); + } + + private static List codes(TransactionCanceledException e) { + return e.getCancellationReasons().stream().map(TransactionCanceledException.CancellationReason::code).toList(); + } + + private String counter(String pk) { + return service.getItem(TABLE, key(pk), REGION).path("n").path("N").asText(); + } + + private JsonNode item(String pk, int n) { + return json("{\"pk\":{\"S\":\"" + pk + "\"},\"n\":{\"N\":\"" + n + "\"}}"); + } + + private JsonNode key(String pk) { + return json("{\"pk\":{\"S\":\"" + pk + "\"}}"); + } + + private JsonNode increment(String pk) { + return json("{\"Update\":{\"TableName\":\"Counters\",\"Key\":{\"pk\":{\"S\":\"" + pk + "\"}}," + + "\"UpdateExpression\":\"SET n = n + :one\",\"ExpressionAttributeValues\":{\":one\":{\"N\":\"1\"}}}}"); + } + + private JsonNode put(String pk) { + return json("{\"Put\":{\"TableName\":\"Counters\",\"Item\":{\"pk\":{\"S\":\"" + pk + "\"}}}}"); + } + + private JsonNode get(String pk) { + return json("{\"Get\":{\"TableName\":\"Counters\",\"Key\":{\"pk\":{\"S\":\"" + pk + "\"}}}}"); + } + + private JsonNode json(String text) { + try { + return mapper.readTree(text); + } catch (Exception e) { + throw new IllegalArgumentException(text, e); + } + } + + private static void awaitQuietly(CountDownLatch latch) { + try { + if (!latch.await(30, TimeUnit.SECONDS)) { + throw new IllegalStateException("latch never opened"); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } +} diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbTransactionConflictsTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbTransactionConflictsTest.java new file mode 100644 index 0000000000..6cd8ee5e84 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbTransactionConflictsTest.java @@ -0,0 +1,109 @@ +package io.floci.aws.services.dynamodb; + +import io.floci.aws.core.common.AwsException; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** The busy marks a write transaction leaves on its items, and the emulation's switch. */ +class DynamoDbTransactionConflictsTest { + + private static final DynamoDbTransactionConflicts.Item HOT = new DynamoDbTransactionConflicts.Item("000000000000/us-east-1::t", "hot"); + + private final AtomicLong clock = new AtomicLong(5_000_000_000L); + private final AtomicInteger waits = new AtomicInteger(); + private final DynamoDbTransactionConflicts conflicts = new DynamoDbTransactionConflicts(true, Duration.ofMillis(10), + clock::get, (deadline, nanoTime) -> waits.incrementAndGet()); + + // Catches: the default doing anything at all, so turning the emulation on is the only way to change behaviour. + @Test + void offIsTheDefaultAndHoldsNothing() { + DynamoDbTransactionConflicts off = DynamoDbTransactionConflicts.of(false); + + assertSame(DynamoDbTransactionConflicts.OFF, off); + assertFalse(off.enabled()); + assertEquals(0, off.hold(List.of(HOT))); + assertFalse(off.busy(HOT.table(), HOT.itemKey())); + off.rejectSingleItemWrite(HOT.table(), HOT.itemKey()); + } + + // Catches: a mark outliving its hold, a slow commit using up the window before the transaction answers, or a + // single write going through on a held item. + @Test + void aMarkHoldsTheItemWhileItCommitsAndForTheHoldAfter() { + long mark = conflicts.hold(List.of(HOT)); + clock.addAndGet(Duration.ofSeconds(1).toNanos()); + + assertTrue(conflicts.busy(HOT.table(), HOT.itemKey()), "a commit that takes long still holds its items"); + conflicts.settle(List.of(HOT), mark); + assertTrue(conflicts.busy(HOT.table(), HOT.itemKey())); + AwsException rejected = assertThrows(AwsException.class, + () -> conflicts.rejectSingleItemWrite(HOT.table(), HOT.itemKey())); + assertEquals("TransactionConflictException", rejected.getErrorCode()); + assertEquals("Transaction is ongoing for the item", rejected.getMessage()); + assertEquals(400, rejected.getHttpStatus()); + assertFalse(conflicts.busy(HOT.table(), "cold")); + + clock.addAndGet(Duration.ofMillis(10).toNanos()); + assertFalse(conflicts.busy(HOT.table(), HOT.itemKey())); + } + + // Catches: a finished transaction freeing an item a later transaction holds, or a failed one waiting out a hold. + @Test + void releasingRemovesOnlyTheTransactionsOwnMarks() { + long first = conflicts.settle(List.of(HOT), conflicts.hold(List.of(HOT))); + conflicts.release(List.of(HOT), first, true); + assertEquals(1, waits.get()); + assertFalse(conflicts.busy(HOT.table(), HOT.itemKey())); + + long earlier = conflicts.hold(List.of(HOT)); + clock.addAndGet(1); + conflicts.hold(List.of(HOT)); + conflicts.release(List.of(HOT), earlier, false); + assertEquals(1, waits.get()); + assertTrue(conflicts.busy(HOT.table(), HOT.itemKey())); + + conflicts.clear(); + assertFalse(conflicts.busy(HOT.table(), HOT.itemKey())); + } + + // Catches: an interrupt ending a committed transaction's hold early, so overlapping requests get through while + // it is still meant to be running, or the interrupt being swallowed. + @Test + void anInterruptDoesNotCutAHoldShort() throws Exception { + DynamoDbTransactionConflicts parking = new DynamoDbTransactionConflicts(true, Duration.ofMillis(10), + clock::get, DynamoDbTransactionConflicts::park); + long deadline = parking.settle(List.of(HOT), parking.hold(List.of(HOT))); + AtomicBoolean interruptKept = new AtomicBoolean(); + CountDownLatch answered = new CountDownLatch(1); + Thread committer = Thread.ofPlatform().start(() -> { + Thread.currentThread().interrupt(); + parking.release(List.of(HOT), deadline, true); + interruptKept.set(Thread.currentThread().isInterrupted()); + answered.countDown(); + }); + + await("the committer parks").atMost(Duration.ofSeconds(5)) + .until(() -> committer.getState() == Thread.State.TIMED_WAITING); + assertTrue(parking.busy(HOT.table(), HOT.itemKey()), "an interrupted transaction still holds its items"); + assertEquals(1, answered.getCount()); + + clock.addAndGet(Duration.ofMillis(10).toNanos()); + assertTrue(answered.await(5, TimeUnit.SECONDS), "the hold ends at its deadline"); + assertTrue(interruptKept.get(), "the interrupt status is restored"); + assertFalse(parking.busy(HOT.table(), HOT.itemKey())); + } +} diff --git a/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbBackendSelectorTest.java b/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbBackendSelectorTest.java new file mode 100644 index 0000000000..2384d7f193 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbBackendSelectorTest.java @@ -0,0 +1,40 @@ +package io.floci.aws.services.dynamodb.backend; + +import io.floci.aws.config.EmulatorConfig; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +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; + +/** The backend selection's startup checks. */ +class DynamoDbBackendSelectorTest { + + // Catches: transaction conflicts asked for over DynamoDB Local, which applies its own transactions, starting + // without them instead of failing at startup. + @Test + void transactionConflictsNeedTheNativeBackend() { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().dynamodb().backend()).thenReturn("Local"); + when(config.services().dynamodb().transactionConflictsEnabled()).thenReturn(true); + + IllegalStateException refused = assertThrows(IllegalStateException.class, + () -> new DynamoDbBackendSelector(config, mock(NativeDynamoDbBackend.class), + mock(DynamoDbLocalBackend.class))); + + assertTrue(refused.getMessage().contains("transaction-conflicts-enabled"), refused.getMessage()); + } + + @Test + void transactionConflictsRunOnTheNativeBackend() { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().dynamodb().backend()).thenReturn("native"); + when(config.services().dynamodb().transactionConflictsEnabled()).thenReturn(true); + + assertEquals("native", new DynamoDbBackendSelector(config, mock(NativeDynamoDbBackend.class), + mock(DynamoDbLocalBackend.class)).selected()); + } +}