|
| 1 | +package software.amazon.cryptography.example.hierarchy.concurrent; |
| 2 | + |
| 3 | +import java.text.DateFormat; |
| 4 | +import java.text.SimpleDateFormat; |
| 5 | +import java.util.Arrays; |
| 6 | +import java.util.Collections; |
| 7 | +import java.util.Date; |
| 8 | +import java.util.HashMap; |
| 9 | +import java.util.List; |
| 10 | +import java.util.Map; |
| 11 | +import java.util.TimeZone; |
| 12 | +import java.util.concurrent.ConcurrentHashMap; |
| 13 | +import java.util.concurrent.ConcurrentLinkedDeque; |
| 14 | +import org.testng.Assert; |
| 15 | +import org.testng.annotations.AfterClass; |
| 16 | +import org.testng.annotations.BeforeClass; |
| 17 | +import org.testng.annotations.Test; |
| 18 | +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; |
| 19 | +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; |
| 20 | +import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; |
| 21 | +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; |
| 22 | +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest; |
| 23 | +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsResponse; |
| 24 | +import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException; |
| 25 | +import software.amazon.awssdk.utils.ImmutableMap; |
| 26 | +import software.amazon.cryptography.example.DdbHelper; |
| 27 | +import software.amazon.cryptography.example.Fixtures; |
| 28 | + |
| 29 | +// These concurrent tests check that DynamoDB behaves the way we expect when |
| 30 | +// there are multiple request to write an item to DynamoDB. Our libraries use the |
| 31 | +// TransactWriteItems API with a condition check that the primary key we are writing |
| 32 | +// does not exist. This will result in either 1. ConditionCheckFailure if an item has been |
| 33 | +// written, and we are trying to write over it and 2. TransactionConflict if we are trying to write |
| 34 | +// while there is a transaction being committed. |
| 35 | +public class ConcurrentConditionCheckWriteTest { |
| 36 | + |
| 37 | + private static final Integer threadCount = 5; |
| 38 | + private static final String mLockedId = "concurrency-test-write-key"; |
| 39 | + private static final Map<String, String> INDEX_EXPR_ATT_NAMES = |
| 40 | + ImmutableMap.of("#pk", "branch-key-id"); |
| 41 | + |
| 42 | + private static final List<String> identifiers = Collections.unmodifiableList( |
| 43 | + Arrays.asList("1", "2", "3", "4", "5") |
| 44 | + ); |
| 45 | + private Map<String, DynamoDbClient> threadIdToDdbClient; |
| 46 | + private static Map<String, String> indexToThreadId; |
| 47 | + private ConcurrentLinkedDeque<String> unpickedIndices; |
| 48 | + |
| 49 | + @BeforeClass |
| 50 | + public void setup() { |
| 51 | + threadIdToDdbClient = new ConcurrentHashMap<>(6, 1, threadCount); |
| 52 | + identifiers.forEach(id -> |
| 53 | + threadIdToDdbClient.put(id, DynamoDbClient.create()) |
| 54 | + ); |
| 55 | + indexToThreadId = new ConcurrentHashMap<>(6, 1, threadCount); |
| 56 | + unpickedIndices = new ConcurrentLinkedDeque<>(identifiers); |
| 57 | + } |
| 58 | + |
| 59 | + @AfterClass |
| 60 | + public void teardown() { |
| 61 | + DynamoDbClient _ddbClient = DynamoDbClient.create(); |
| 62 | + identifiers.forEach(id -> |
| 63 | + DdbHelper.deleteKeyStoreDdbItem( |
| 64 | + mLockedId, |
| 65 | + "branch:ACTIVE", |
| 66 | + Fixtures.TEST_KEYSTORE_NAME, |
| 67 | + _ddbClient, |
| 68 | + true |
| 69 | + ) |
| 70 | + ); |
| 71 | + } |
| 72 | + |
| 73 | + public static Map<String, AttributeValue> indexItem( |
| 74 | + final AttributeValue value, |
| 75 | + final String timestamp |
| 76 | + ) { |
| 77 | + Map<String, AttributeValue> item = new HashMap<>(); |
| 78 | + |
| 79 | + item.put("branch-key-id", AttributeValue.builder().s(mLockedId).build()); |
| 80 | + item.put("type", AttributeValue.builder().s(indexType()).build()); |
| 81 | + item.put("value", value); |
| 82 | + item.put("timestamp", AttributeValue.builder().s(timestamp).build()); |
| 83 | + return item; |
| 84 | + } |
| 85 | + |
| 86 | + private static String indexType() { |
| 87 | + return "branch:ACTIVE"; |
| 88 | + } |
| 89 | + |
| 90 | + public static TransactWriteItem conditionalWrite( |
| 91 | + final AttributeValue value, |
| 92 | + final String timestamp |
| 93 | + ) { |
| 94 | + return TransactWriteItem |
| 95 | + .builder() |
| 96 | + .put(putBuilder -> |
| 97 | + putBuilder |
| 98 | + .tableName(Fixtures.TEST_KEYSTORE_NAME) |
| 99 | + .item(indexItem(value, timestamp)) |
| 100 | + .conditionExpression("attribute_not_exists(#pk)") |
| 101 | + .expressionAttributeNames(INDEX_EXPR_ATT_NAMES) |
| 102 | + ) |
| 103 | + .build(); |
| 104 | + } |
| 105 | + |
| 106 | + private DynamoDbClient clientForThread(final String threadIdToIndex) { |
| 107 | + return threadIdToDdbClient.computeIfAbsent( |
| 108 | + threadIdToIndex, |
| 109 | + ddbClient -> DynamoDbClient.create() |
| 110 | + ); |
| 111 | + } |
| 112 | + |
| 113 | + @Test(threadPoolSize = 5, invocationCount = 30, timeOut = 1000) |
| 114 | + public void TestConcurrentWriteCheck() { |
| 115 | + String threadId = String.valueOf(Thread.currentThread().getId()); |
| 116 | + String threadIdToIndex = indexToThreadId.computeIfAbsent( |
| 117 | + threadId, |
| 118 | + str -> unpickedIndices.pop() |
| 119 | + ); |
| 120 | + AttributeValue value = AttributeValue.builder().s(threadIdToIndex).build(); |
| 121 | + TimeZone tz = TimeZone.getTimeZone("UTC"); |
| 122 | + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset |
| 123 | + df.setTimeZone(tz); |
| 124 | + String timestamp = df.format(new Date()); |
| 125 | + |
| 126 | + System.out.println( |
| 127 | + "Thread ID: " + |
| 128 | + Thread.currentThread().getId() + |
| 129 | + " ThreadIndex: " + |
| 130 | + threadIdToIndex + |
| 131 | + " Timestamp: " + |
| 132 | + timestamp |
| 133 | + ); |
| 134 | + |
| 135 | + try { |
| 136 | + DynamoDbClient client = clientForThread(threadIdToIndex); |
| 137 | + TransactWriteItemsResponse transactWriteItemsResponse = |
| 138 | + client.transactWriteItems( |
| 139 | + TransactWriteItemsRequest |
| 140 | + .builder() |
| 141 | + .transactItems(conditionalWrite(value, timestamp)) |
| 142 | + .build() |
| 143 | + ); |
| 144 | + Assert.assertTrue( |
| 145 | + transactWriteItemsResponse.sdkHttpResponse().isSuccessful() |
| 146 | + ); |
| 147 | + } catch (TransactionCanceledException exception) { |
| 148 | + // We can fail for two reasons, either there's already a transact write in flight |
| 149 | + // 0r we have failed the condition check. |
| 150 | + exception |
| 151 | + .cancellationReasons() |
| 152 | + .forEach(cancellationReason -> { |
| 153 | + Assert.assertTrue( |
| 154 | + (cancellationReason.code().equals("TransactionConflict") || |
| 155 | + cancellationReason.code().equals("ConditionalCheckFailed")) |
| 156 | + ); |
| 157 | + }); |
| 158 | + } |
| 159 | + } |
| 160 | +} |
0 commit comments