-
Notifications
You must be signed in to change notification settings - Fork 0
/
OrderLowLevelStreamIT.java
198 lines (150 loc) · 8.5 KB
/
OrderLowLevelStreamIT.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package com.welflex.aws.dynamodb;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBStreams;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBStreamsClientBuilder;
import com.amazonaws.services.dynamodbv2.model.*;
import com.amazonaws.services.dynamodbv2.model.Record;
import com.amazonaws.services.dynamodbv2.streamsadapter.AmazonDynamoDBStreamsAdapterClient;
import com.google.common.collect.Lists;
import com.welflex.aws.dynamodb.model.Order;
import com.welflex.aws.dynamodb.repository.Util;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class OrderLowLevelStreamIT {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderLowLevelStreamIT.class);
private AmazonDynamoDB dynamoDB;
private AmazonDynamoDBStreamsAdapterClient adapterClient;
private AmazonCloudWatchClient amazonCloudWatchClient;
private AmazonDynamoDBStreams dynamoDBStreams;
private StreamSpecification orderStreamSpecification;
private String streamArn;
@BeforeEach
public void setUp() {
dynamoDB = AmazonDynamoDBClientBuilder.standard()
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", Regions.US_WEST_1.getName()))
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("foo", "bar"))).build();
dynamoDBStreams = AmazonDynamoDBStreamsClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("foo", "bar")))
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", Regions.US_WEST_1.getName()))
.build();
adapterClient = new AmazonDynamoDBStreamsAdapterClient(dynamoDBStreams);
amazonCloudWatchClient = new AmazonCloudWatchClient(new AWSStaticCredentialsProvider(new BasicAWSCredentials("foo", "bar")), new ClientConfiguration());
Util.<Order>createTable(dynamoDB, Order.class, true);
DescribeTableResult describeTableResult = dynamoDB.describeTable("Orders");
orderStreamSpecification = describeTableResult.getTable().getStreamSpecification();
streamArn = describeTableResult.getTable().getLatestStreamArn();
LOGGER.info("Order Stream ARN {}", streamArn);
}
@Test
public void orderStreamTest() throws InterruptedException {
DescribeStreamResult describeStreamResult = dynamoDBStreams.describeStream(
new DescribeStreamRequest()
.withStreamArn(streamArn)
.withExclusiveStartShardId(null));
Map<Shard, String> shardToLastProceed = describeStreamResult.getStreamDescription()
.getShards().stream().collect(Collectors.toMap(shard -> shard, shard -> ""));
// Run and Collect ShardReader result
LOGGER.info("Starting Stream Readers and sending orders...");
List<ShardReader> shardReaders = runAndStreamOrders(shardToLastProceed);
List<String> originalRunOrders = shardReaders.stream().map(shardReader -> shardReader.getOrdersProcessed())
.reduce((strings, strings2) -> {
List<String> combined = Lists.newArrayList(strings);
combined.addAll(strings2);
return combined;
}).get();
shardToLastProceed = shardReaders.stream().collect(Collectors.toMap(shardReader -> shardReader.getShard(),
shardReader -> shardReader.getLastProcessedSequenceNumber()));
LOGGER.info("Starting Stream Readers and sending orders second time...");
List<ShardReader> secondRunReaders = runAndStreamOrders(shardToLastProceed);
List<String> secondRunOrders = secondRunReaders.stream().map(shardReader -> shardReader.getOrdersProcessed())
.reduce((strings, strings2) -> {
List<String> combined = Lists.newArrayList(strings);
combined.addAll(strings2);
return combined;
}).get();
assertFalse(secondRunOrders.stream().anyMatch(originalRunOrders::contains));
}
private List<ShardReader> runAndStreamOrders(Map<Shard, String> shardToLastProcessed) throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(100);
List<ShardReader> shardReaders = Lists.newArrayList();
shardToLastProcessed.forEach((shard, s) -> shardReaders.add(new ShardReader(shard, streamArn, s, dynamoDBStreams, latch)));;
shardReaders.forEach(thread -> thread.start());
OrderTestUtil.createOrders(100, dynamoDB);
latch.await();
shardReaders.forEach(thread -> thread.interrupt());
return shardReaders;
}
public static class ShardReader extends Thread {
private final Shard shard;
private final String streamArn;
private final AmazonDynamoDBStreams dynamoDBStreams;
private final CountDownLatch latch;
private final List<String> orderIdSet;
private String lastProcessedSequenceNumber;
public ShardReader(Shard shard, String streamArn,
String lastProcessedSequenceNumber,
AmazonDynamoDBStreams dynamoDBStreams, CountDownLatch latch) {
this.lastProcessedSequenceNumber = lastProcessedSequenceNumber;
this.shard = shard;
this.streamArn = streamArn;
this.dynamoDBStreams = dynamoDBStreams;
this.latch = latch;
this.orderIdSet = Lists.newArrayList();
LOGGER.info("Shard Reader created for Shard {}", shard.getShardId());
}
public List<String> getOrdersProcessed() {
return orderIdSet;
}
public String getLastProcessedSequenceNumber() {
return lastProcessedSequenceNumber;
}
public Shard getShard() {
return shard;
}
@Override
public void run() {
LOGGER.info("Resuming Shard {} from Sequence {}", shard.getShardId(), lastProcessedSequenceNumber);
boolean firstRun = "".equals(lastProcessedSequenceNumber);
LOGGER.info("Is this the first time we are reading from the stream? {}", firstRun);
GetShardIteratorRequest getShardIteratorRequest = new GetShardIteratorRequest()
.withStreamArn(streamArn)
.withShardId(shard.getShardId())
.withSequenceNumber(firstRun? null : lastProcessedSequenceNumber)
.withShardIteratorType(firstRun ? ShardIteratorType.TRIM_HORIZON : ShardIteratorType.AFTER_SEQUENCE_NUMBER);
GetShardIteratorResult getShardIteratorResult =
dynamoDBStreams.getShardIterator(getShardIteratorRequest);
String currentShardIter = getShardIteratorResult.getShardIterator();
LOGGER.info("Current Shard iterator {}", currentShardIter);
while (currentShardIter != null && latch.getCount() > 0) {
// Use the shard iterator to read the stream records
GetRecordsResult getRecordsResult = dynamoDBStreams.getRecords(new GetRecordsRequest()
.withShardIterator(currentShardIter));
List<Record> records = getRecordsResult.getRecords();
for (Record record : records) {
StreamRecord streamRecord = record.getDynamodb();
// System.out.println(" " + streamRecord);
Map<String, AttributeValue> keys = streamRecord.getKeys();
AttributeValue id = keys.get("id");
orderIdSet.add(id.getS());
lastProcessedSequenceNumber = streamRecord.getSequenceNumber();
latch.countDown();
}
currentShardIter = getRecordsResult.getNextShardIterator();
}
}
}
}