mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(dynamodb): correct UpdateExpression semantics and TransactWriteItems idempotency (#804)
Three related DynamoDB correctness fixes, all in the same DynamoDbService surface: 1. Cross-attribute SET reads pre-update values (#798) "SET a = :v, b = a" now writes the *original* value of `a` into `b`, matching real DynamoDB. Snapshot the item once at the start of applySetClause and resolve every RHS reference against the snapshot; defer writes to `item`. Previously, in-place mutation between comma-separated clauses caused later clauses to read post-update values, silently corrupting audit/history fields. 2. ClientRequestToken idempotency for TransactWriteItems (#799) Same token + same body → no-op success. Same token + different body → IdempotentParameterMismatchException. Implemented via a per-region in-memory cache with a 10-minute TTL (matching the AWS window) keyed by "region::token" with a SHA-256 of the raw request body for comparison. handleTransactWriteItems now extracts ClientRequestToken from the request and forwards it plus the raw body through a new 4-arg transactWriteItems(items, region, token, rawRequest) overload. The original 2-arg signature is preserved as a no-token convenience that delegates. 3. Parenthesized arithmetic in SET silently dropped (#802) "SET c = (c - :v)" now applies identically to "SET c = c - :v". Added stripOuterParens() and call it on each SET-action RHS before findArithmeticOperator() — which still correctly only finds operators at depth 0, but now sees an unwrapped expression to scan. Combined forms like "SET c = (if_not_exists(c, :d) - :v), other = :s" now apply both clauses instead of dropping the parenthesized one while applying the other. Tests - DynamoDbServiceTest gains 8 regression tests: cross-attribute SET (plain + #name), parenthesized arithmetic (simple, with if_not_exists, doubled parens, alongside a plain assignment), and TransactWriteItems idempotency (no-op replay, parameter-mismatch error, null-token bypass). Refs: #798, #799, #802
This commit is contained in:
1 parent
558983078c
commit
6b2c081f0b
3 files changed
+397
-9
No files matched your search
@@ -622,8 +622,15 @@ public class DynamoDbJsonHandler {
|
||||
transactItemsNode.forEach(transactItems::add);
|
||||
}
|
||||
|
||||
// ClientRequestToken makes TransactWriteItems idempotent within ~10 minutes.
|
||||
// Forward the token and the raw request body so the service can hash the body
|
||||
// and reject replays whose parameters changed.
|
||||
String clientRequestToken = request.has("ClientRequestToken") && !request.get("ClientRequestToken").isNull()
|
||||
? request.get("ClientRequestToken").asText()
|
||||
: null;
|
||||
|
||||
try {
|
||||
dynamoDbService.transactWriteItems(transactItems, region);
|
||||
dynamoDbService.transactWriteItems(transactItems, region, clientRequestToken, request);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
} catch (TransactionCanceledException e) {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
|
||||
@@ -62,6 +62,14 @@ public class DynamoDbService {
|
||||
// relies on ReentrantLock's re-entrancy so the inner put/update/delete calls do
|
||||
// not deadlock after the outer transaction already took each participant's lock.
|
||||
private final ConcurrentHashMap<String, ConcurrentHashMap<String, ReentrantLock>> itemLocks = new ConcurrentHashMap<>();
|
||||
// ClientRequestToken idempotency for TransactWriteItems. AWS retains tokens for
|
||||
// ~10 minutes; floci uses the same window. The cache entry stores a hash of the
|
||||
// request body so a replay with the same token but different parameters can be
|
||||
// rejected with IdempotentParameterMismatchException.
|
||||
private final ConcurrentHashMap<String, IdempotencyEntry> txIdempotency = new ConcurrentHashMap<>();
|
||||
private static final long TX_IDEMPOTENCY_TTL_NANOS = java.time.Duration.ofMinutes(10).toNanos();
|
||||
|
||||
private record IdempotencyEntry(String requestHash, long insertedAtNanos) {}
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
private DynamoDbStreamService streamService;
|
||||
@@ -741,7 +749,60 @@ public class DynamoDbService {
|
||||
|
||||
// --- Transact Operations ---
|
||||
|
||||
/**
|
||||
* Backward-compatible overload for callers that do not pass a ClientRequestToken.
|
||||
* The 4-arg variant is what {@link DynamoDbJsonHandler#handleTransactWriteItems}
|
||||
* uses so the caller's ClientRequestToken is honoured.
|
||||
*/
|
||||
public void transactWriteItems(List<JsonNode> transactItems, String region) {
|
||||
transactWriteItems(transactItems, region, null, null);
|
||||
}
|
||||
|
||||
public void transactWriteItems(List<JsonNode> transactItems, String region,
|
||||
String clientRequestToken, JsonNode rawRequest) {
|
||||
// Idempotency check via ClientRequestToken — AWS contract:
|
||||
// * Same token + identical request body → no-op success (silently dedupe).
|
||||
// * Same token + different request body → IdempotentParameterMismatchException.
|
||||
// * No token, or expired token → proceed normally.
|
||||
if (clientRequestToken != null && !clientRequestToken.isEmpty() && rawRequest != null) {
|
||||
String cacheKey = region + "::" + clientRequestToken;
|
||||
String requestHash = sha256(rawRequest.toString());
|
||||
long nowNanos = System.nanoTime();
|
||||
|
||||
IdempotencyEntry existing = txIdempotency.get(cacheKey);
|
||||
if (existing != null && nowNanos - existing.insertedAtNanos() <= TX_IDEMPOTENCY_TTL_NANOS) {
|
||||
if (existing.requestHash().equals(requestHash)) {
|
||||
LOG.debugv("transactWriteItems: idempotent replay for token={0}", clientRequestToken);
|
||||
return;
|
||||
}
|
||||
throw new AwsException("IdempotentParameterMismatchException",
|
||||
"Request parameters do not match those of an in-flight or recent transaction using the same ClientRequestToken",
|
||||
400);
|
||||
}
|
||||
|
||||
// Register the token. compute() is used so a concurrent replay with the same body
|
||||
// collapses onto the same entry without double-applying writes.
|
||||
IdempotencyEntry registered = txIdempotency.compute(cacheKey, (k, v) -> {
|
||||
if (v != null && nowNanos - v.insertedAtNanos() <= TX_IDEMPOTENCY_TTL_NANOS) {
|
||||
return v;
|
||||
}
|
||||
return new IdempotencyEntry(requestHash, nowNanos);
|
||||
});
|
||||
if (!registered.requestHash().equals(requestHash)) {
|
||||
throw new AwsException("IdempotentParameterMismatchException",
|
||||
"Request parameters do not match those of an in-flight or recent transaction using the same ClientRequestToken",
|
||||
400);
|
||||
}
|
||||
if (registered.insertedAtNanos() != nowNanos) {
|
||||
// Lost the race to a concurrent identical request — treat as a replay.
|
||||
LOG.debugv("transactWriteItems: concurrent identical replay for token={0}", clientRequestToken);
|
||||
return;
|
||||
}
|
||||
|
||||
// Best-effort eviction of stale entries.
|
||||
txIdempotency.entrySet().removeIf(e -> nowNanos - e.getValue().insertedAtNanos() > TX_IDEMPOTENCY_TTL_NANOS);
|
||||
}
|
||||
|
||||
// Acquire every participant's item lock in a deterministic (storageKey, itemKey)
|
||||
// order before evaluating conditions or applying writes. Total-ordered acquisition
|
||||
// prevents deadlock across concurrent transactions; ReentrantLock lets the inner
|
||||
@@ -1129,6 +1190,13 @@ public class DynamoDbService {
|
||||
// Stop when we hit another clause keyword (REMOVE, ADD, DELETE) or end
|
||||
LOG.debugv("applySetClause: clause={0}, exprAttrNames={1}, exprAttrValues={2}",
|
||||
clause, exprAttrNames, exprAttrValues);
|
||||
|
||||
// Snapshot the item before applying any assignments so cross-attribute
|
||||
// references within the same SET expression (e.g. "SET b = a, a = :v")
|
||||
// resolve to pre-update values, matching real DynamoDB semantics
|
||||
// (actions are applied atomically and attribute references read original values).
|
||||
ObjectNode snapshot = item.deepCopy();
|
||||
|
||||
while (!clause.isEmpty()) {
|
||||
String upper = clause.toUpperCase();
|
||||
if (upper.startsWith("REMOVE ") || upper.startsWith("ADD ") || upper.startsWith("DELETE ")) {
|
||||
@@ -1163,18 +1231,27 @@ public class DynamoDbService {
|
||||
rest = "";
|
||||
}
|
||||
|
||||
// Strip balanced outer parentheses so producers that wrap the RHS
|
||||
// (e.g. ElectroDB emits "SET c = (c - :v)") behave the same as the
|
||||
// unwrapped form. DynamoDB grammar accepts parentheses around any
|
||||
// SET-action RHS.
|
||||
valuePart = stripOuterParens(valuePart);
|
||||
|
||||
// Resolve the value
|
||||
// Check for arithmetic expressions (operand + operand, operand - operand)
|
||||
// before handling individual expression types, since the left operand can be
|
||||
// a function like if_not_exists(...).
|
||||
//
|
||||
// RHS reads use `snapshot` (pre-update item state) so multiple comma-separated
|
||||
// assignments behave atomically: each clause sees the original values, not the
|
||||
// intermediate state produced by previous clauses in the same expression.
|
||||
int arithmeticIdx = findArithmeticOperator(valuePart);
|
||||
if (arithmeticIdx >= 0) {
|
||||
String leftExpr = valuePart.substring(0, arithmeticIdx).trim();
|
||||
char operator = valuePart.charAt(arithmeticIdx);
|
||||
String rightExpr = valuePart.substring(arithmeticIdx + 1).trim();
|
||||
JsonNode leftVal = evaluateSetExpr(item, leftExpr, exprAttrNames, exprAttrValues);
|
||||
JsonNode rightVal = evaluateSetExpr(item, rightExpr, exprAttrNames, exprAttrValues);
|
||||
JsonNode leftVal = evaluateSetExpr(snapshot, leftExpr, exprAttrNames, exprAttrValues);
|
||||
JsonNode rightVal = evaluateSetExpr(snapshot, rightExpr, exprAttrNames, exprAttrValues);
|
||||
if (leftVal == null || rightVal == null || !leftVal.has("N") || !rightVal.has("N")) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Invalid UpdateExpression: Incorrect operand type for operator or function", 400);
|
||||
@@ -1200,14 +1277,14 @@ public class DynamoDbService {
|
||||
String checkAttr = resolveAttributeName(args[0].trim(), exprAttrNames);
|
||||
String fallbackExpr = args[1].trim();
|
||||
JsonNode resolved;
|
||||
if (hasValueAtPath(item, checkAttr, exprAttrNames)) {
|
||||
if (hasValueAtPath(snapshot, checkAttr, exprAttrNames)) {
|
||||
// attrRef exists — evaluate to its current value
|
||||
resolved = getValueAtPath(item, checkAttr, exprAttrNames);
|
||||
resolved = getValueAtPath(snapshot, checkAttr, exprAttrNames);
|
||||
} else if (fallbackExpr.startsWith(":") && exprAttrValues != null) {
|
||||
resolved = exprAttrValues.get(fallbackExpr);
|
||||
} else {
|
||||
// fallback is itself an attribute reference
|
||||
resolved = getValueAtPath(item, resolveAttributeName(fallbackExpr, exprAttrNames), exprAttrNames);
|
||||
resolved = getValueAtPath(snapshot, resolveAttributeName(fallbackExpr, exprAttrNames), exprAttrNames);
|
||||
}
|
||||
if (resolved != null) {
|
||||
setValueAtPath(item, attrPath, resolved, exprAttrNames);
|
||||
@@ -1222,8 +1299,8 @@ public class DynamoDbService {
|
||||
if (commaPos >= 0) {
|
||||
String arg1 = inner.substring(0, commaPos).trim();
|
||||
String arg2 = inner.substring(commaPos + 1).trim();
|
||||
JsonNode list1 = evaluateSetExpr(item, arg1, exprAttrNames, exprAttrValues);
|
||||
JsonNode list2 = evaluateSetExpr(item, arg2, exprAttrNames, exprAttrValues);
|
||||
JsonNode list1 = evaluateSetExpr(snapshot, arg1, exprAttrNames, exprAttrValues);
|
||||
JsonNode list2 = evaluateSetExpr(snapshot, arg2, exprAttrNames, exprAttrValues);
|
||||
if (list1 != null && list2 != null && list1.has("L") && list2.has("L")) {
|
||||
com.fasterxml.jackson.databind.node.ArrayNode merged =
|
||||
com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.arrayNode();
|
||||
@@ -1249,7 +1326,7 @@ public class DynamoDbService {
|
||||
} else if (!valuePart.isEmpty()) {
|
||||
// Plain attribute reference: SET a = b or SET a = #alias
|
||||
String refAttr = resolveAttributeName(valuePart, exprAttrNames);
|
||||
JsonNode refValue = getValueAtPath(item, refAttr, exprAttrNames);
|
||||
JsonNode refValue = getValueAtPath(snapshot, refAttr, exprAttrNames);
|
||||
if (refValue != null) {
|
||||
setValueAtPath(item, attrPath, refValue, exprAttrNames);
|
||||
}
|
||||
@@ -1260,6 +1337,29 @@ public class DynamoDbService {
|
||||
return clause;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip balanced outer parentheses from a SET-action RHS expression, repeatedly,
|
||||
* so that producers wrapping arithmetic or function calls in parens (e.g.
|
||||
* "(c - :v)" or "((if_not_exists(c, :d) - :v))") parse identically to the
|
||||
* unwrapped form. Rejects forms like "(a) - (b)" where the outer parens do
|
||||
* not actually enclose the whole expression.
|
||||
*/
|
||||
private static String stripOuterParens(String expr) {
|
||||
String s = expr.trim();
|
||||
while (s.length() >= 2 && s.charAt(0) == '(' && s.charAt(s.length() - 1) == ')') {
|
||||
int depth = 0;
|
||||
boolean wraps = true;
|
||||
for (int i = 0; i < s.length() - 1; i++) {
|
||||
if (s.charAt(i) == '(') depth++;
|
||||
else if (s.charAt(i) == ')') depth--;
|
||||
if (depth == 0) { wraps = false; break; }
|
||||
}
|
||||
if (!wraps) break;
|
||||
s = s.substring(1, s.length() - 1).trim();
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
private JsonNode evaluateSetExpr(ObjectNode item, String expr,
|
||||
JsonNode exprAttrNames, JsonNode exprAttrValues) {
|
||||
if (expr.toLowerCase().startsWith("if_not_exists(")) {
|
||||
@@ -2146,6 +2246,23 @@ public class DynamoDbService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SHA-256 hex digest of a string, used by ClientRequestToken idempotency to compare
|
||||
* request bodies. SHA-256 is required (not MD5) for the dedup contract because a
|
||||
* collision would allow a request with different parameters to be silently treated
|
||||
* as a replay; SHA-256 is supported on every JVM via {@link MessageDigest}.
|
||||
*/
|
||||
private static String sha256(String input) {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||
byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(digest);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
// SHA-256 is mandated by the JLS to be available on every JVM; this should never trigger.
|
||||
throw new IllegalStateException("SHA-256 is required but not available on this JVM", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String buildManifestSummary(ExportDescription desc, String exportId,
|
||||
String dataKey, long itemCount, long billedSize,
|
||||
String md5, String etag, String manifestSummaryKey) {
|
||||
|
||||
@@ -1968,4 +1968,268 @@ class DynamoDbServiceTest {
|
||||
assertTrue(returnedItem.has("customerId"), "returned item should have customerId");
|
||||
assertEquals("1", returnedItem.get("customerId").get("S").asText());
|
||||
}
|
||||
|
||||
// ── Regression tests: cross-attribute SET, parenthesized arithmetic,
|
||||
// and TransactWriteItems ClientRequestToken idempotency ──
|
||||
|
||||
@Test
|
||||
void updateItemSetCrossAttributeReferenceUsesPreUpdateValue() {
|
||||
// "SET a = :new, b = a" must write the ORIGINAL value of a into b.
|
||||
// AWS DynamoDB applies SET actions atomically; attribute references on the RHS
|
||||
// resolve to pre-update values.
|
||||
createUsersTable();
|
||||
|
||||
ObjectNode existing = mapper.createObjectNode();
|
||||
existing.set("userId", attributeValue("S", "u1"));
|
||||
existing.set("a", attributeValue("S", "original_a"));
|
||||
existing.set("b", attributeValue("S", "original_b"));
|
||||
service.putItem("Users", existing);
|
||||
|
||||
ObjectNode key = item("userId", "u1");
|
||||
ObjectNode exprValues = mapper.createObjectNode();
|
||||
exprValues.set(":new_a", attributeValue("S", "new_a_value"));
|
||||
|
||||
service.updateItem("Users", key, null,
|
||||
"SET a = :new_a, b = a",
|
||||
null, exprValues, null);
|
||||
|
||||
JsonNode stored = service.getItem("Users", key);
|
||||
assertNotNull(stored);
|
||||
assertEquals("new_a_value", stored.get("a").get("S").asText(),
|
||||
"a should be updated to the new value");
|
||||
assertEquals("original_a", stored.get("b").get("S").asText(),
|
||||
"b should receive a's pre-update value (atomic application)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateItemSetCrossAttributeReferenceWithExpressionAttributeNames() {
|
||||
// Same as above but using #placeholder names — the form most client libraries emit.
|
||||
createUsersTable();
|
||||
|
||||
ObjectNode existing = mapper.createObjectNode();
|
||||
existing.set("userId", attributeValue("S", "u1"));
|
||||
existing.set("status", attributeValue("S", "ISSUED"));
|
||||
existing.set("previousStatus", attributeValue("S", "NONE"));
|
||||
service.putItem("Users", existing);
|
||||
|
||||
ObjectNode key = item("userId", "u1");
|
||||
ObjectNode exprAttrNames = mapper.createObjectNode();
|
||||
exprAttrNames.put("#s", "status");
|
||||
exprAttrNames.put("#p", "previousStatus");
|
||||
ObjectNode exprValues = mapper.createObjectNode();
|
||||
exprValues.set(":v", attributeValue("S", "VOID"));
|
||||
|
||||
service.updateItem("Users", key, null,
|
||||
"SET #s = :v, #p = #s",
|
||||
exprAttrNames, exprValues, null);
|
||||
|
||||
JsonNode stored = service.getItem("Users", key);
|
||||
assertEquals("VOID", stored.get("status").get("S").asText());
|
||||
assertEquals("ISSUED", stored.get("previousStatus").get("S").asText(),
|
||||
"previousStatus should receive the pre-update value of status");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateItemSetParenthesizedArithmeticAppliesSubtraction() {
|
||||
// "SET c = (c - :v)" must subtract identically to the unwrapped form.
|
||||
// Previously, findArithmeticOperator only returned operators at paren-depth 0,
|
||||
// so wrapped arithmetic silently no-oped.
|
||||
createUsersTable();
|
||||
|
||||
ObjectNode existing = mapper.createObjectNode();
|
||||
existing.set("userId", attributeValue("S", "u1"));
|
||||
ObjectNode counterVal = mapper.createObjectNode();
|
||||
counterVal.put("N", "5");
|
||||
existing.set("counter", counterVal);
|
||||
service.putItem("Users", existing);
|
||||
|
||||
ObjectNode key = item("userId", "u1");
|
||||
ObjectNode exprAttrNames = mapper.createObjectNode();
|
||||
exprAttrNames.put("#c", "counter");
|
||||
ObjectNode exprValues = mapper.createObjectNode();
|
||||
ObjectNode vNode = mapper.createObjectNode();
|
||||
vNode.put("N", "1");
|
||||
exprValues.set(":v", vNode);
|
||||
|
||||
service.updateItem("Users", key, null,
|
||||
"SET #c = (#c - :v)",
|
||||
exprAttrNames, exprValues, null);
|
||||
|
||||
JsonNode stored = service.getItem("Users", key);
|
||||
assertEquals("4", stored.get("counter").get("N").asText(),
|
||||
"parenthesized arithmetic should subtract identically to the unwrapped form");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateItemSetParenthesizedIfNotExistsArithmeticAlongsidePlainAssignment() {
|
||||
// ElectroDB-style emission: "SET c = (if_not_exists(c, :d) - :v), other = :s".
|
||||
// Previously the parenthesized arithmetic was silently dropped while the simple
|
||||
// SET clause applied — a confusing partial-success outcome.
|
||||
createUsersTable();
|
||||
|
||||
ObjectNode existing = mapper.createObjectNode();
|
||||
existing.set("userId", attributeValue("S", "u1"));
|
||||
ObjectNode counterVal = mapper.createObjectNode();
|
||||
counterVal.put("N", "5");
|
||||
existing.set("counter", counterVal);
|
||||
existing.set("other", attributeValue("S", "old"));
|
||||
service.putItem("Users", existing);
|
||||
|
||||
ObjectNode key = item("userId", "u1");
|
||||
ObjectNode exprAttrNames = mapper.createObjectNode();
|
||||
exprAttrNames.put("#c", "counter");
|
||||
exprAttrNames.put("#o", "other");
|
||||
ObjectNode exprValues = mapper.createObjectNode();
|
||||
ObjectNode vNode = mapper.createObjectNode(); vNode.put("N", "1");
|
||||
ObjectNode dNode = mapper.createObjectNode(); dNode.put("N", "0");
|
||||
exprValues.set(":v", vNode);
|
||||
exprValues.set(":d", dNode);
|
||||
exprValues.set(":s", attributeValue("S", "new"));
|
||||
|
||||
service.updateItem("Users", key, null,
|
||||
"SET #c = (if_not_exists(#c, :d) - :v), #o = :s",
|
||||
exprAttrNames, exprValues, null);
|
||||
|
||||
JsonNode stored = service.getItem("Users", key);
|
||||
assertEquals("4", stored.get("counter").get("N").asText(),
|
||||
"parenthesized arithmetic should apply alongside a simple SET clause");
|
||||
assertEquals("new", stored.get("other").get("S").asText(),
|
||||
"the non-parenthesized clause should still apply");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateItemSetDoubledOuterParensStillApplies() {
|
||||
// Defence-in-depth: even multiply-wrapped expressions should parse the same as bare.
|
||||
createUsersTable();
|
||||
|
||||
ObjectNode existing = mapper.createObjectNode();
|
||||
existing.set("userId", attributeValue("S", "u1"));
|
||||
ObjectNode counterVal = mapper.createObjectNode(); counterVal.put("N", "10");
|
||||
existing.set("counter", counterVal);
|
||||
service.putItem("Users", existing);
|
||||
|
||||
ObjectNode key = item("userId", "u1");
|
||||
ObjectNode exprValues = mapper.createObjectNode();
|
||||
ObjectNode vNode = mapper.createObjectNode(); vNode.put("N", "3");
|
||||
exprValues.set(":v", vNode);
|
||||
|
||||
service.updateItem("Users", key, null,
|
||||
"SET counter = ((counter - :v))",
|
||||
null, exprValues, null);
|
||||
|
||||
JsonNode stored = service.getItem("Users", key);
|
||||
assertEquals("7", stored.get("counter").get("N").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void transactWriteItemsReplayWithSameTokenAndBodyIsNoOp() {
|
||||
// ClientRequestToken contract: same token + same body → no re-application of writes.
|
||||
createUsersTable();
|
||||
service.putItem("Users", item("userId", "u1"));
|
||||
|
||||
ObjectNode update = mapper.createObjectNode();
|
||||
update.put("TableName", "Users");
|
||||
update.set("Key", item("userId", "u1"));
|
||||
ObjectNode exprValues = mapper.createObjectNode();
|
||||
ObjectNode oneVal = mapper.createObjectNode(); oneVal.put("N", "1");
|
||||
exprValues.set(":one", oneVal);
|
||||
ObjectNode exprNames = mapper.createObjectNode();
|
||||
exprNames.put("#c", "counter");
|
||||
update.put("UpdateExpression", "ADD #c :one");
|
||||
update.set("ExpressionAttributeNames", exprNames);
|
||||
update.set("ExpressionAttributeValues", exprValues);
|
||||
|
||||
ObjectNode transactItem = mapper.createObjectNode();
|
||||
transactItem.set("Update", update);
|
||||
|
||||
ObjectNode rawRequest = mapper.createObjectNode();
|
||||
rawRequest.putArray("TransactItems").add(transactItem);
|
||||
rawRequest.put("ClientRequestToken", "tok-replay");
|
||||
|
||||
// First call applies the ADD: counter becomes 1.
|
||||
service.transactWriteItems(List.of(transactItem), "us-east-1", "tok-replay", rawRequest);
|
||||
// Replay must be a no-op.
|
||||
service.transactWriteItems(List.of(transactItem), "us-east-1", "tok-replay", rawRequest);
|
||||
|
||||
JsonNode stored = service.getItem("Users", item("userId", "u1"));
|
||||
assertEquals("1", stored.get("counter").get("N").asText(),
|
||||
"replay with the same ClientRequestToken must not re-apply the write");
|
||||
}
|
||||
|
||||
@Test
|
||||
void transactWriteItemsReplayWithSameTokenButDifferentBodyThrowsIdempotentMismatch() {
|
||||
// ClientRequestToken contract: same token + different body → IdempotentParameterMismatchException.
|
||||
createUsersTable();
|
||||
service.putItem("Users", item("userId", "u1"));
|
||||
|
||||
ObjectNode exprNames = mapper.createObjectNode();
|
||||
exprNames.put("#c", "counter");
|
||||
|
||||
// First request: ADD #c :x with :x = 1
|
||||
ObjectNode update1 = mapper.createObjectNode();
|
||||
update1.put("TableName", "Users");
|
||||
update1.set("Key", item("userId", "u1"));
|
||||
ObjectNode exprValues1 = mapper.createObjectNode();
|
||||
ObjectNode oneVal = mapper.createObjectNode(); oneVal.put("N", "1");
|
||||
exprValues1.set(":x", oneVal);
|
||||
update1.put("UpdateExpression", "ADD #c :x");
|
||||
update1.set("ExpressionAttributeNames", exprNames);
|
||||
update1.set("ExpressionAttributeValues", exprValues1);
|
||||
ObjectNode tx1 = mapper.createObjectNode(); tx1.set("Update", update1);
|
||||
ObjectNode raw1 = mapper.createObjectNode();
|
||||
raw1.putArray("TransactItems").add(tx1);
|
||||
raw1.put("ClientRequestToken", "tok-mismatch");
|
||||
|
||||
service.transactWriteItems(List.of(tx1), "us-east-1", "tok-mismatch", raw1);
|
||||
|
||||
// Second request reuses the token but changes :x to 2.
|
||||
ObjectNode update2 = mapper.createObjectNode();
|
||||
update2.put("TableName", "Users");
|
||||
update2.set("Key", item("userId", "u1"));
|
||||
ObjectNode exprValues2 = mapper.createObjectNode();
|
||||
ObjectNode twoVal = mapper.createObjectNode(); twoVal.put("N", "2");
|
||||
exprValues2.set(":x", twoVal);
|
||||
update2.put("UpdateExpression", "ADD #c :x");
|
||||
update2.set("ExpressionAttributeNames", exprNames);
|
||||
update2.set("ExpressionAttributeValues", exprValues2);
|
||||
ObjectNode tx2 = mapper.createObjectNode(); tx2.set("Update", update2);
|
||||
ObjectNode raw2 = mapper.createObjectNode();
|
||||
raw2.putArray("TransactItems").add(tx2);
|
||||
raw2.put("ClientRequestToken", "tok-mismatch");
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
service.transactWriteItems(List.of(tx2), "us-east-1", "tok-mismatch", raw2));
|
||||
assertEquals("IdempotentParameterMismatchException", ex.getErrorCode());
|
||||
|
||||
// First call applied; second was rejected — counter remains 1.
|
||||
JsonNode stored = service.getItem("Users", item("userId", "u1"));
|
||||
assertEquals("1", stored.get("counter").get("N").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void transactWriteItemsNullClientRequestTokenSkipsIdempotencyCheck() {
|
||||
// When no token is supplied, two calls with identical bodies should both apply
|
||||
// (i.e. counter ends at 2). This is the pre-existing behaviour and must remain.
|
||||
createUsersTable();
|
||||
service.putItem("Users", item("userId", "u1"));
|
||||
|
||||
ObjectNode update = mapper.createObjectNode();
|
||||
update.put("TableName", "Users");
|
||||
update.set("Key", item("userId", "u1"));
|
||||
ObjectNode exprNames = mapper.createObjectNode();
|
||||
exprNames.put("#c", "counter");
|
||||
ObjectNode exprValues = mapper.createObjectNode();
|
||||
ObjectNode oneVal = mapper.createObjectNode(); oneVal.put("N", "1");
|
||||
exprValues.set(":one", oneVal);
|
||||
update.put("UpdateExpression", "ADD #c :one");
|
||||
update.set("ExpressionAttributeNames", exprNames);
|
||||
update.set("ExpressionAttributeValues", exprValues);
|
||||
ObjectNode tx = mapper.createObjectNode(); tx.set("Update", update);
|
||||
|
||||
service.transactWriteItems(List.of(tx), "us-east-1", null, null);
|
||||
service.transactWriteItems(List.of(tx), "us-east-1", null, null);
|
||||
|
||||
JsonNode stored = service.getItem("Users", item("userId", "u1"));
|
||||
assertEquals("2", stored.get("counter").get("N").asText());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user