mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(dynamodb): evaluate legacy Expected under the item lock (#6278)
* fix(dynamodb): evaluate legacy Expected under the item lock PutItem, UpdateItem and DeleteItem evaluated a legacy Expected condition in the request handler, against an item read before the per-item lock was taken, and only then called the locked write. Concurrent writers holding the same version could all pass the check, so an optimistic-locking client saw several of them accepted where DynamoDB accepts exactly one. The handler still validates the Expected map, but now hands its evaluation to the service, which runs it against the stored item under the same lock as the write, beside ConditionExpression. PutItem with ReturnValues ALL_OLD now returns the item the put replaced instead of that earlier read. Closes #6276 * fix(dynamodb): report key errors before legacy Expected errors Validate the table and the key a write names before the legacy Expected map, as the handler's earlier unlocked read did, but without reading the stored item. UpdateItem and DeleteItem keep their key-argument wording; PutItem now reports its item-body wording whether or not the request carries Expected or ReturnValues ALL_OLD, matching a plain PutItem. * test(dynamodb): share the round loop of the legacy Expected race tests Rename the class to DynamoDbLegacyExpectedIntegrationTest now that it also covers error precedence. * test(dynamodb): share the start-gate helper and the DynamoDB request helper Move the start-gate thread pool from DynamoDbConcurrencyIntegrationTest into testing/StartGate, which returns each task's result along with any errors, and use it from DynamoDbLegacyExpectedIntegrationTest too. The legacy Expected test now sends its requests through DynamoDbRequests.ddb instead of its own copy.
This commit is contained in:
1 parent
94c4572fed
commit
f94e0583b7
5 files changed
+371
-71
No files matched your search
+6
-31
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
import io.github.hectorvent.floci.services.kinesis.KinesisService;
|
||||
import io.github.hectorvent.floci.services.kinesis.model.KinesisRecord;
|
||||
import io.github.hectorvent.floci.services.kinesis.model.KinesisStream;
|
||||
import io.github.hectorvent.floci.testing.StartGate;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.RepeatedTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -30,10 +31,6 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
@@ -45,7 +42,7 @@ import static org.mockito.Mockito.when;
|
||||
/**
|
||||
* Concurrency compatibility suite for {@link DynamoDbService}.
|
||||
*
|
||||
* <p>All scenarios use a {@link CountDownLatch} starting gate so threads release
|
||||
* <p>All scenarios use a {@link StartGate} so threads release
|
||||
* simultaneously, maximising contention. Wrapped in {@code @RepeatedTest(5)} so a
|
||||
* regression that surfaces intermittently has a real chance of being observed in a
|
||||
* single CI run.
|
||||
@@ -106,32 +103,10 @@ class DynamoDbConcurrencyIntegrationTest {
|
||||
|
||||
/** Run {@code work} in {@code threadCount} threads, released together. */
|
||||
private List<Throwable> runConcurrently(int threadCount, Runnable work) throws InterruptedException {
|
||||
ExecutorService pool = Executors.newFixedThreadPool(threadCount);
|
||||
CountDownLatch startGate = new CountDownLatch(1);
|
||||
CountDownLatch doneGate = new CountDownLatch(threadCount);
|
||||
List<Throwable> errors = Collections.synchronizedList(new ArrayList<>());
|
||||
try {
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
pool.submit(() -> {
|
||||
try {
|
||||
startGate.await();
|
||||
work.run();
|
||||
} catch (Throwable t) {
|
||||
errors.add(t);
|
||||
} finally {
|
||||
doneGate.countDown();
|
||||
}
|
||||
});
|
||||
}
|
||||
startGate.countDown();
|
||||
assertTrue(doneGate.await(30, TimeUnit.SECONDS),
|
||||
"concurrent tasks did not complete within 30s");
|
||||
return errors;
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS),
|
||||
"thread pool did not terminate");
|
||||
}
|
||||
return StartGate.runConcurrently(threadCount, i -> {
|
||||
work.run();
|
||||
return null;
|
||||
}).errors();
|
||||
}
|
||||
|
||||
@RepeatedTest(REPEATS)
|
||||
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.github.hectorvent.floci.testing.StartGate;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.RepeatedTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.IntFunction;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.DynamoDbRequests.ddb;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Writes carrying a legacy {@code Expected} condition, sent over HTTP so the condition goes through
|
||||
* the request handler. Concurrent writers of one version: exactly one may win, as on DynamoDB.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class DynamoDbLegacyExpectedIntegrationTest {
|
||||
|
||||
private static final int REPEATS = 3;
|
||||
private static final int WRITERS = 16;
|
||||
private static final int ROUNDS = 5;
|
||||
|
||||
private String table;
|
||||
|
||||
@BeforeAll
|
||||
static void configureJson() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void createTable() {
|
||||
table = "legacy-expected-" + UUID.randomUUID();
|
||||
ddb("CreateTable", """
|
||||
{"TableName":"%s","KeySchema":[{"AttributeName":"pk","KeyType":"HASH"}],
|
||||
"AttributeDefinitions":[{"AttributeName":"pk","AttributeType":"S"}],
|
||||
"BillingMode":"PAY_PER_REQUEST"}
|
||||
""".formatted(table)).statusCode(200);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void deleteTable() {
|
||||
ddb("DeleteTable", "{\"TableName\":\"" + table + "\"}").statusCode(200);
|
||||
}
|
||||
|
||||
@RepeatedTest(REPEATS)
|
||||
void updateItem_concurrentWritersOfOneVersion_acceptsExactlyOne() throws InterruptedException {
|
||||
assertOneWriterWinsEachRound("update", (pk, writer) -> ddb("UpdateItem", """
|
||||
{"TableName":"%s","Key":{"pk":{"S":"%s"}},
|
||||
"AttributeUpdates":{"version":{"Action":"PUT","Value":{"N":"1"}},
|
||||
"writer":{"Action":"PUT","Value":{"S":"%d"}}},
|
||||
"Expected":{"version":{"Value":{"N":"0"}}}}
|
||||
""".formatted(table, pk, writer)));
|
||||
}
|
||||
|
||||
@RepeatedTest(REPEATS)
|
||||
void putItem_concurrentWritersOfOneVersion_acceptsExactlyOne() throws InterruptedException {
|
||||
assertOneWriterWinsEachRound("put", (pk, writer) -> ddb("PutItem", """
|
||||
{"TableName":"%s",
|
||||
"Item":{"pk":{"S":"%s"},"version":{"N":"1"},"writer":{"S":"%d"}},
|
||||
"Expected":{"version":{"Value":{"N":"0"}}}}
|
||||
""".formatted(table, pk, writer)));
|
||||
}
|
||||
|
||||
@RepeatedTest(REPEATS)
|
||||
void deleteItem_concurrentDeletesOfOneVersion_acceptsExactlyOne() throws InterruptedException {
|
||||
assertOneWriterWinsEachRound("delete", (pk, writer) -> ddb("DeleteItem", """
|
||||
{"TableName":"%s","Key":{"pk":{"S":"%s"}},
|
||||
"Expected":{"version":{"Value":{"N":"0"}}}}
|
||||
""".formatted(table, pk)));
|
||||
}
|
||||
|
||||
@RepeatedTest(REPEATS)
|
||||
void putItem_concurrentAllOld_returnsTheItemEachPutReplaced() throws InterruptedException {
|
||||
String pk = "all-old";
|
||||
ddb("PutItem", """
|
||||
{"TableName":"%s","Item":{"pk":{"S":"%s"},"writer":{"S":"seed"}}}
|
||||
""".formatted(table, pk)).statusCode(200);
|
||||
|
||||
List<ValidatableResponse> responses = runConcurrently(writer -> ddb("PutItem", """
|
||||
{"TableName":"%s","Item":{"pk":{"S":"%s"},"writer":{"S":"%d"}},
|
||||
"ReturnValues":"ALL_OLD"}
|
||||
""".formatted(table, pk, writer)));
|
||||
|
||||
List<String> replaced = new ArrayList<>();
|
||||
for (ValidatableResponse response : responses) {
|
||||
replaced.add(response.statusCode(200).extract().jsonPath().getString("Attributes.writer.S"));
|
||||
}
|
||||
replaced.add(ddb("GetItem", """
|
||||
{"TableName":"%s","Key":{"pk":{"S":"%s"}},"ConsistentRead":true}
|
||||
""".formatted(table, pk)).extract().jsonPath().getString("Item.writer.S"));
|
||||
|
||||
List<String> everyValue = new ArrayList<>();
|
||||
everyValue.add("seed");
|
||||
for (int writer = 0; writer < WRITERS; writer++) {
|
||||
everyValue.add(String.valueOf(writer));
|
||||
}
|
||||
Collections.sort(replaced);
|
||||
Collections.sort(everyValue);
|
||||
assertEquals(everyValue, replaced,
|
||||
"every value but the last must be replaced by exactly one put, and the last must be stored");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateItem_staleExpectedVersion_isRejected() {
|
||||
seed("stale");
|
||||
String update = """
|
||||
{"TableName":"%s","Key":{"pk":{"S":"stale"}},
|
||||
"AttributeUpdates":{"version":{"Action":"PUT","Value":{"N":"1"}}},
|
||||
"Expected":{"version":{"Value":{"N":"0"}}}}
|
||||
""".formatted(table);
|
||||
ddb("UpdateItem", update).statusCode(200);
|
||||
ddb("UpdateItem", update).statusCode(400)
|
||||
.body("__type", equalTo("ConditionalCheckFailedException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateAndDelete_malformedKeyAndInvalidExpected_reportTheKeyError() {
|
||||
ddb("UpdateItem", """
|
||||
{"TableName":"%s","Key":{"other":{"S":"a"}},
|
||||
"AttributeUpdates":{"version":{"Action":"PUT","Value":{"N":"1"}}},
|
||||
"Expected":{"version":{}}}
|
||||
""".formatted(table)).statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", equalTo("The provided key element does not match the schema"));
|
||||
ddb("DeleteItem", """
|
||||
{"TableName":"%s","Key":{"other":{"S":"a"}},"Expected":{"version":{}}}
|
||||
""".formatted(table)).statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", equalTo("The provided key element does not match the schema"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void putItem_itemWithoutItsKey_reportsTheItemKeyErrorWithAnyReturnValuesOrExpected() {
|
||||
for (String extra : List.of("", ",\"ReturnValues\":\"ALL_OLD\"", ",\"Expected\":{\"version\":{}}")) {
|
||||
ddb("PutItem", """
|
||||
{"TableName":"%s","Item":{"other":{"S":"a"}}%s}
|
||||
""".formatted(table, extra)).statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", equalTo("One of the required keys was not given a value"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateItem_invalidExpectedOnAMissingTable_reportsTheMissingTable() {
|
||||
ddb("UpdateItem", """
|
||||
{"TableName":"absent-%s","Key":{"pk":{"S":"a"}},"Expected":{"version":{}}}
|
||||
""".formatted(UUID.randomUUID())).statusCode(400)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
private void seed(String pk) {
|
||||
ddb("PutItem", """
|
||||
{"TableName":"%s","Item":{"pk":{"S":"%s"},"version":{"N":"0"}}}
|
||||
""".formatted(table, pk)).statusCode(200);
|
||||
}
|
||||
|
||||
/** Seeds a fresh item at version 0 each round and races every writer at it. */
|
||||
private void assertOneWriterWinsEachRound(String keyPrefix, BiFunction<String, Integer, ValidatableResponse> request)
|
||||
throws InterruptedException {
|
||||
for (int round = 0; round < ROUNDS; round++) {
|
||||
String pk = keyPrefix + "-" + round;
|
||||
seed(pk);
|
||||
List<ValidatableResponse> responses = runConcurrently(writer -> request.apply(pk, writer));
|
||||
int accepted = 0;
|
||||
for (ValidatableResponse response : responses) {
|
||||
if (response.extract().statusCode() == 200) {
|
||||
accepted++;
|
||||
} else {
|
||||
response.statusCode(400)
|
||||
.body("__type", equalTo("ConditionalCheckFailedException"));
|
||||
}
|
||||
}
|
||||
assertEquals(1, accepted, "exactly one writer of a version may be accepted");
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends one request per writer, all released together. */
|
||||
private static List<ValidatableResponse> runConcurrently(IntFunction<ValidatableResponse> request)
|
||||
throws InterruptedException {
|
||||
StartGate.Results<ValidatableResponse> results = StartGate.runConcurrently(WRITERS, request);
|
||||
assertTrue(results.errors().isEmpty(), () -> "unexpected errors: " + results.errors());
|
||||
return results.values();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package io.github.hectorvent.floci.testing;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.IntFunction;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** Runs tasks on their own threads, all released together, so a race in the code under test has its best chance. */
|
||||
public final class StartGate {
|
||||
|
||||
private StartGate() {}
|
||||
|
||||
/**
|
||||
* What the tasks returned, in task order, with {@code null} for a task that threw, and what the
|
||||
* throwing tasks threw.
|
||||
*/
|
||||
public record Results<T>(List<T> values, List<Throwable> errors) {}
|
||||
|
||||
/**
|
||||
* Runs {@code task} once per index from 0 to {@code threadCount - 1}, each on its own thread, and
|
||||
* waits up to 30 seconds for all of them.
|
||||
*/
|
||||
public static <T> Results<T> runConcurrently(int threadCount, IntFunction<T> task) throws InterruptedException {
|
||||
ExecutorService pool = Executors.newFixedThreadPool(threadCount);
|
||||
CountDownLatch startGate = new CountDownLatch(1);
|
||||
CountDownLatch doneGate = new CountDownLatch(threadCount);
|
||||
Object[] values = new Object[threadCount];
|
||||
List<Throwable> errors = Collections.synchronizedList(new ArrayList<>());
|
||||
try {
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
int index = i;
|
||||
pool.submit(() -> {
|
||||
try {
|
||||
startGate.await();
|
||||
values[index] = task.apply(index);
|
||||
} catch (Throwable t) {
|
||||
errors.add(t);
|
||||
} finally {
|
||||
doneGate.countDown();
|
||||
}
|
||||
});
|
||||
}
|
||||
startGate.countDown();
|
||||
assertTrue(doneGate.await(30, TimeUnit.SECONDS),
|
||||
"concurrent tasks did not complete within 30s");
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS),
|
||||
"thread pool did not terminate");
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
List<T> results = (List<T>) Arrays.asList(values);
|
||||
return new Results<>(results, List.copyOf(errors));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user