mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(dynamodb): route stream consumers through one account-scoped reader (#4394)
* refactor(dynamodb): add a stream reader and key native streams by table ARN DynamoDbStreamReader is the engine-neutral way to read DynamoDB Streams. DynamoDbApiStreamReader implements it over the selected DynamoDbOperations using the Streams wire API. Native streams were keyed by region and table name, so same-named tables in two accounts shared one stream. They are now keyed by table ARN, and ListStreams returns only the caller's account and region. Streams of every account are restored from persisted tables at startup. * refactor(dynamodb): move stream consumers onto the stream reader The Lambda DynamoDB Streams poller reads through DynamoDbStreamReader: each tick renews iterators from committed progress for every readable shard, and reads a child shard only after its parent was read to its end. It discards restart checkpoints only for a process-lifetime engine, and pins LATEST per shard via newestSequenceNumbers, replacing DynamoDbStreamService.latestSequenceNumber. A read fills a batch from as many GetRecords calls as it needs, so a batch is not cut at the 1000 record GetRecords maximum. EventBridge Pipes reads DynamoDB streams the same way, committing a batch only once it is delivered or sent to the DLQ, delivers the AWS stream record shape with eventSourceARN, and honors LATEST. The Redshift zero-ETL consumer reads the same way, keeping per-shard progress in the integration (legacy checkpointSequenceNumber is ignored on load) and committing a batch only after it is written to the landing table. It discards that progress at startup for a process-lifetime engine, and the writer now takes AWS stream records, so Redshift no longer uses DynamoDbStreamService or DynamoDbStreamRecord, whose SHARD_ID is now package-private.
This commit is contained in:
1 parent
0a4320132d
commit
2df052181d
31 files changed
+2601
-799
No files matched your search
+94
-33
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
|
||||
@@ -20,6 +21,9 @@ class DynamoDbStreamServiceTest {
|
||||
|
||||
private static final String TABLE_ARN =
|
||||
"arn:aws:dynamodb:us-east-1:000000000000:table/ViewTypeTable";
|
||||
private static final String SHARED_TABLE = "Shared";
|
||||
private static final String ACCOUNT_A = "111111111111";
|
||||
private static final String ACCOUNT_B = "222222222222";
|
||||
|
||||
private DynamoDbStreamService service;
|
||||
private ObjectMapper mapper;
|
||||
@@ -74,7 +78,7 @@ class DynamoDbStreamServiceTest {
|
||||
service.enableStream("ViewTypeTable", TABLE_ARN, "KEYS_ONLY", "us-east-1");
|
||||
|
||||
JsonNode item = mapper.readTree("{\"userId\":{\"S\":\"u1\"},\"name\":{\"S\":\"a\"}}");
|
||||
service.captureEvent("ViewTypeTable", "INSERT", null, item, table, "us-east-1");
|
||||
service.captureEvent("INSERT", null, item, table, "us-east-1");
|
||||
|
||||
String iterator = service.getShardIterator(
|
||||
sd.getStreamArn(), "shardId-000000000000", "TRIM_HORIZON", null);
|
||||
@@ -88,25 +92,43 @@ class DynamoDbStreamServiceTest {
|
||||
|
||||
@Test
|
||||
void loadsStreamOnStartup() {
|
||||
var streams = service.listStreams(null, null);
|
||||
List<StreamDescription> streams = service.listStreams(null, "000000000000", "us-west-2");
|
||||
assertEquals(1, streams.size());
|
||||
StreamDescription stream = streams.get(0);
|
||||
assertEquals("TestTable", stream.getTableName());
|
||||
assertEquals("ENABLED", stream.getStreamStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsPersistedStreamsOfEveryAccountOnStartup() {
|
||||
AccountAwareStorageBackend<TableDefinition> tables = AccountAwareStorageBackend.inMemory(ACCOUNT_A);
|
||||
TableDefinition tableA = sharedNameTable(ACCOUNT_A);
|
||||
TableDefinition tableB = sharedNameTable(ACCOUNT_B);
|
||||
tableA.setStreamArn(tableA.getTableArn() + "/stream/2026-01-01T00:00:00.000");
|
||||
tableB.setStreamArn(tableB.getTableArn() + "/stream/2026-01-02T00:00:00.000");
|
||||
tables.putForAccount(ACCOUNT_A, "us-east-1::" + SHARED_TABLE, tableA);
|
||||
tables.putForAccount(ACCOUNT_B, "us-east-1::" + SHARED_TABLE, tableB);
|
||||
|
||||
DynamoDbStreamService restarted = new DynamoDbStreamService(mapper, tables);
|
||||
|
||||
assertEquals(List.of(tableA.getStreamArn()),
|
||||
streamArns(restarted.listStreams(null, ACCOUNT_A, "us-east-1")));
|
||||
assertEquals(List.of(tableB.getStreamArn()),
|
||||
streamArns(restarted.listStreams(null, ACCOUNT_B, "us-east-1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAnIteratorWhenItsSequenceNumberHasBeenTrimmed() throws Exception {
|
||||
var table = createTestTableWithStream();
|
||||
service.enableStream(table.getTableName(), TABLE_ARN, "NEW_IMAGE", "us-east-1");
|
||||
service.enableStream(table.getTableName(), table.getTableArn(), "NEW_IMAGE", "us-east-1");
|
||||
JsonNode item = mapper.readTree("{\"userId\":{\"S\":\"u1\"}}");
|
||||
|
||||
service.captureEvent(table.getTableName(), "INSERT", null, item, table, "us-east-1");
|
||||
service.captureEvent("INSERT", null, item, table, "us-east-1");
|
||||
String iterator = service.getShardIterator(
|
||||
table.getStreamArn(), DynamoDbStreamService.SHARD_ID, "AT_SEQUENCE_NUMBER", "000000000000000000001");
|
||||
|
||||
for (int i = 0; i < DynamoDbStreamService.MAX_RECORDS; i++) {
|
||||
service.captureEvent(table.getTableName(), "INSERT", null, item, table, "us-east-1");
|
||||
service.captureEvent("INSERT", null, item, table, "us-east-1");
|
||||
}
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
@@ -123,13 +145,13 @@ class DynamoDbStreamServiceTest {
|
||||
"us-east-1", "000000000000");
|
||||
table.setStreamEnabled(true);
|
||||
StreamDescription stream = service.enableStream(
|
||||
table.getTableName(), TABLE_ARN, "NEW_IMAGE", "us-east-1");
|
||||
table.getTableName(), table.getTableArn(), "NEW_IMAGE", "us-east-1");
|
||||
JsonNode item = mapper.readTree("{\"userId\":{\"S\":\"u1\"}}");
|
||||
String iterator = service.getShardIterator(
|
||||
stream.getStreamArn(), DynamoDbStreamService.SHARD_ID, "TRIM_HORIZON", null);
|
||||
|
||||
for (int i = 0; i <= DynamoDbStreamService.MAX_RECORDS; i++) {
|
||||
service.captureEvent(table.getTableName(), "INSERT", null, item, table, "us-east-1");
|
||||
service.captureEvent("INSERT", null, item, table, "us-east-1");
|
||||
}
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
@@ -146,13 +168,13 @@ class DynamoDbStreamServiceTest {
|
||||
"us-east-1", "000000000000");
|
||||
table.setStreamEnabled(true);
|
||||
StreamDescription stream = service.enableStream(
|
||||
table.getTableName(), TABLE_ARN, "NEW_IMAGE", "us-east-1");
|
||||
table.getTableName(), table.getTableArn(), "NEW_IMAGE", "us-east-1");
|
||||
JsonNode item = mapper.readTree("{\"userId\":{\"S\":\"u1\"}}");
|
||||
String iterator = service.getShardIterator(
|
||||
stream.getStreamArn(), DynamoDbStreamService.SHARD_ID, "LATEST", null);
|
||||
|
||||
for (int i = 0; i <= DynamoDbStreamService.MAX_RECORDS; i++) {
|
||||
service.captureEvent(table.getTableName(), "INSERT", null, item, table, "us-east-1");
|
||||
service.captureEvent("INSERT", null, item, table, "us-east-1");
|
||||
}
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
@@ -169,13 +191,13 @@ class DynamoDbStreamServiceTest {
|
||||
"us-east-1", "000000000000");
|
||||
table.setStreamEnabled(true);
|
||||
StreamDescription stream = service.enableStream(
|
||||
table.getTableName(), TABLE_ARN, "NEW_IMAGE", "us-east-1");
|
||||
table.getTableName(), table.getTableArn(), "NEW_IMAGE", "us-east-1");
|
||||
JsonNode item = mapper.readTree("{\"userId\":{\"S\":\"u1\"}}");
|
||||
String iterator = service.getShardIterator(
|
||||
stream.getStreamArn(), DynamoDbStreamService.SHARD_ID, "TRIM_HORIZON", null);
|
||||
|
||||
for (int i = 0; i < DynamoDbStreamService.MAX_RECORDS; i++) {
|
||||
service.captureEvent(table.getTableName(), "INSERT", null, item, table, "us-east-1");
|
||||
service.captureEvent("INSERT", null, item, table, "us-east-1");
|
||||
}
|
||||
|
||||
var result = service.getRecords(iterator, 1);
|
||||
@@ -187,11 +209,11 @@ class DynamoDbStreamServiceTest {
|
||||
@Test
|
||||
void appliesInclusiveAndExclusiveSequencePositions() throws Exception {
|
||||
var table = createTestTableWithStream();
|
||||
service.enableStream(table.getTableName(), TABLE_ARN, "NEW_IMAGE", "us-east-1");
|
||||
service.enableStream(table.getTableName(), table.getTableArn(), "NEW_IMAGE", "us-east-1");
|
||||
JsonNode item = mapper.readTree("{\"userId\":{\"S\":\"u1\"}}");
|
||||
|
||||
service.captureEvent(table.getTableName(), "INSERT", null, item, table, "us-east-1");
|
||||
service.captureEvent(table.getTableName(), "MODIFY", item, item, table, "us-east-1");
|
||||
service.captureEvent("INSERT", null, item, table, "us-east-1");
|
||||
service.captureEvent("MODIFY", item, item, table, "us-east-1");
|
||||
|
||||
String at = service.getShardIterator(
|
||||
table.getStreamArn(), DynamoDbStreamService.SHARD_ID,
|
||||
@@ -211,17 +233,17 @@ class DynamoDbStreamServiceTest {
|
||||
@Test
|
||||
void resumesAtTheRetainedSequenceAfterTheHeadIsTrimmed() throws Exception {
|
||||
var table = createTestTableWithStream();
|
||||
service.enableStream(table.getTableName(), TABLE_ARN, "NEW_IMAGE", "us-east-1");
|
||||
service.enableStream(table.getTableName(), table.getTableArn(), "NEW_IMAGE", "us-east-1");
|
||||
JsonNode item = mapper.readTree("{\"userId\":{\"S\":\"u1\"}}");
|
||||
|
||||
service.captureEvent(table.getTableName(), "EVENT_1", null, item, table, "us-east-1");
|
||||
service.captureEvent(table.getTableName(), "EVENT_2", null, item, table, "us-east-1");
|
||||
service.captureEvent("EVENT_1", null, item, table, "us-east-1");
|
||||
service.captureEvent("EVENT_2", null, item, table, "us-east-1");
|
||||
String iterator = service.getShardIterator(
|
||||
table.getStreamArn(), DynamoDbStreamService.SHARD_ID,
|
||||
"AT_SEQUENCE_NUMBER", "000000000000000000002");
|
||||
|
||||
for (int i = 3; i <= DynamoDbStreamService.MAX_RECORDS + 1; i++) {
|
||||
service.captureEvent(table.getTableName(), "EVENT_" + i, null, item, table, "us-east-1");
|
||||
service.captureEvent("EVENT_" + i, null, item, table, "us-east-1");
|
||||
}
|
||||
|
||||
var records = service.getRecords(iterator, 1).records();
|
||||
@@ -233,11 +255,11 @@ class DynamoDbStreamServiceTest {
|
||||
@Test
|
||||
void advancesToTheNextSequenceWithoutDuplicatingRecords() throws Exception {
|
||||
var table = createTestTableWithStream();
|
||||
service.enableStream(table.getTableName(), TABLE_ARN, "NEW_IMAGE", "us-east-1");
|
||||
service.enableStream(table.getTableName(), table.getTableArn(), "NEW_IMAGE", "us-east-1");
|
||||
JsonNode item = mapper.readTree("{\"userId\":{\"S\":\"u1\"}}");
|
||||
|
||||
service.captureEvent(table.getTableName(), "EVENT_1", null, item, table, "us-east-1");
|
||||
service.captureEvent(table.getTableName(), "EVENT_2", null, item, table, "us-east-1");
|
||||
service.captureEvent("EVENT_1", null, item, table, "us-east-1");
|
||||
service.captureEvent("EVENT_2", null, item, table, "us-east-1");
|
||||
String iterator = service.getShardIterator(
|
||||
table.getStreamArn(), DynamoDbStreamService.SHARD_ID,
|
||||
"TRIM_HORIZON", null);
|
||||
@@ -249,24 +271,63 @@ class DynamoDbStreamServiceTest {
|
||||
assertEquals("000000000000000000002", secondPage.records().get(0).getSequenceNumber());
|
||||
}
|
||||
|
||||
@Test
|
||||
void latestSequenceNumberIsNullForAnUnknownOrEmptyStream() {
|
||||
TableDefinition table = createTestTableWithStream();
|
||||
private TableDefinition sharedNameTable(String accountId) {
|
||||
TableDefinition table = new TableDefinition(SHARED_TABLE,
|
||||
List.of(new KeySchemaElement("userId", "HASH")),
|
||||
List.of(new AttributeDefinition("userId", "S")),
|
||||
"us-east-1", accountId);
|
||||
table.setStreamEnabled(true);
|
||||
return table;
|
||||
}
|
||||
|
||||
assertNull(service.latestSequenceNumber(TABLE_ARN + "/stream/unknown"));
|
||||
assertNull(service.latestSequenceNumber(table.getStreamArn()));
|
||||
private List<String> userIdsIn(String streamArn) {
|
||||
String iterator = service.getShardIterator(streamArn, DynamoDbStreamService.SHARD_ID, "TRIM_HORIZON", null);
|
||||
return service.getRecords(iterator, 100).records().stream()
|
||||
.map(record -> record.getKeys().path("userId").path("S").asText())
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static List<String> streamArns(List<StreamDescription> streams) {
|
||||
return streams.stream().map(StreamDescription::getStreamArn).toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void latestSequenceNumberIsTheNewestRetainedRecord() throws Exception {
|
||||
TableDefinition table = createTestTableWithStream();
|
||||
service.enableStream(table.getTableName(), TABLE_ARN, "NEW_IMAGE", "us-east-1");
|
||||
JsonNode item = mapper.readTree("{\"userId\":{\"S\":\"u1\"}}");
|
||||
void sameNamedTablesInTwoAccountsKeepSeparateStreams() throws Exception {
|
||||
TableDefinition tableA = sharedNameTable(ACCOUNT_A);
|
||||
TableDefinition tableB = sharedNameTable(ACCOUNT_B);
|
||||
StreamDescription streamA = service.enableStream(SHARED_TABLE, tableA.getTableArn(), "NEW_IMAGE", "us-east-1");
|
||||
StreamDescription streamB = service.enableStream(SHARED_TABLE, tableB.getTableArn(), "NEW_IMAGE", "us-east-1");
|
||||
|
||||
service.captureEvent(table.getTableName(), "INSERT", null, item, table, "us-east-1");
|
||||
service.captureEvent(table.getTableName(), "MODIFY", item, item, table, "us-east-1");
|
||||
service.captureEvent("INSERT", null, mapper.readTree("{\"userId\":{\"S\":\"a\"}}"),
|
||||
tableA, "us-east-1");
|
||||
service.captureEvent("INSERT", null, mapper.readTree("{\"userId\":{\"S\":\"b\"}}"),
|
||||
tableB, "us-east-1");
|
||||
|
||||
assertEquals("000000000000000000002", service.latestSequenceNumber(table.getStreamArn()));
|
||||
assertNotEquals(streamA.getStreamArn(), streamB.getStreamArn());
|
||||
assertEquals(List.of(streamA.getStreamArn()),
|
||||
streamArns(service.listStreams(SHARED_TABLE, ACCOUNT_A, "us-east-1")));
|
||||
assertEquals(List.of(streamB.getStreamArn()),
|
||||
streamArns(service.listStreams(null, ACCOUNT_B, "us-east-1")));
|
||||
assertEquals(List.of("a"), userIdsIn(streamA.getStreamArn()));
|
||||
assertEquals(List.of("b"), userIdsIn(streamB.getStreamArn()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void disablingOrDeletingOneAccountsStreamLeavesTheOtherEnabled() {
|
||||
TableDefinition tableA = sharedNameTable(ACCOUNT_A);
|
||||
TableDefinition tableB = sharedNameTable(ACCOUNT_B);
|
||||
StreamDescription streamA = service.enableStream(SHARED_TABLE, tableA.getTableArn(), "NEW_IMAGE", "us-east-1");
|
||||
StreamDescription streamB = service.enableStream(SHARED_TABLE, tableB.getTableArn(), "NEW_IMAGE", "us-east-1");
|
||||
|
||||
service.disableStream(tableA.getTableArn());
|
||||
|
||||
assertEquals("DISABLED", service.describeStream(streamA.getStreamArn()).getStreamStatus());
|
||||
assertEquals("ENABLED", service.describeStream(streamB.getStreamArn()).getStreamStatus());
|
||||
|
||||
service.deleteStream(tableA.getTableArn());
|
||||
|
||||
assertThrows(AwsException.class, () -> service.describeStream(streamA.getStreamArn()));
|
||||
assertEquals("ENABLED", service.describeStream(streamB.getStreamArn()).getStreamStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -103,7 +103,7 @@ class DynamoDbStreamViewTypeDurabilityTest {
|
||||
// The restart itself: a fresh stream service rebuilds streams from the persisted table.
|
||||
StorageBackend<String, TableDefinition> reopened = diskStore(file);
|
||||
DynamoDbStreamService afterRestart = new DynamoDbStreamService(mapper, reopened);
|
||||
StreamDescription sd = afterRestart.listStreams(TABLE, REGION).get(0);
|
||||
StreamDescription sd = afterRestart.listStreams(TABLE, "000000000000", REGION).get(0);
|
||||
assertEquals("KEYS_ONLY", sd.getStreamViewType(),
|
||||
"a restarted stream must not resume the old image shape");
|
||||
}
|
||||
|
||||
+5
-5
@@ -133,7 +133,7 @@ class NativeDynamoDbTableServiceTest {
|
||||
|
||||
private void assertNoTableAndNoStream() {
|
||||
assertTrue(dynamoDbService.findTable(TABLE, REGION).isEmpty(), "no table may be left behind");
|
||||
assertTrue(streams.listStreams(TABLE, REGION).isEmpty(), "no stream may be left behind");
|
||||
assertTrue(streams.listStreams(TABLE, ACCOUNT, REGION).isEmpty(), "no stream may be left behind");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -206,7 +206,7 @@ class NativeDynamoDbTableServiceTest {
|
||||
persisted.getKmsMasterKeyArn());
|
||||
|
||||
StreamDescription stream = new DynamoDbStreamService(mapper, diskStore(file))
|
||||
.listStreams(TABLE, REGION).get(0);
|
||||
.listStreams(TABLE, ACCOUNT, REGION).get(0);
|
||||
assertEquals("NEW_IMAGE", stream.getStreamViewType(),
|
||||
"a restarted stream must come back with the persisted view type");
|
||||
}
|
||||
@@ -270,7 +270,7 @@ class NativeDynamoDbTableServiceTest {
|
||||
assertNull(persisted.getKmsMasterKeyArn());
|
||||
|
||||
StreamDescription stream = new DynamoDbStreamService(mapper, diskStore(file))
|
||||
.listStreams(TABLE, REGION).get(0);
|
||||
.listStreams(TABLE, ACCOUNT, REGION).get(0);
|
||||
assertEquals("NEW_IMAGE", stream.getStreamViewType(),
|
||||
"a restarted stream must not resume the old image shape");
|
||||
}
|
||||
@@ -283,7 +283,7 @@ class NativeDynamoDbTableServiceTest {
|
||||
tableService.updateTable(updateRequest(List.of(), List.of(), settings(null, false, null, null, null)), REGION);
|
||||
|
||||
assertFalse(reloadFromDisk().isStreamEnabled());
|
||||
assertEquals("DISABLED", streams.listStreams(TABLE, REGION).get(0).getStreamStatus());
|
||||
assertEquals("DISABLED", streams.listStreams(TABLE, ACCOUNT, REGION).get(0).getStreamStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -330,7 +330,7 @@ class NativeDynamoDbTableServiceTest {
|
||||
assertFalse(persisted.isDeletionProtectionEnabled());
|
||||
assertNull(persisted.getTableClass());
|
||||
assertFalse(persisted.isStreamEnabled());
|
||||
assertTrue(streams.listStreams(TABLE, REGION).isEmpty(), "the rejected update must not enable a stream");
|
||||
assertTrue(streams.listStreams(TABLE, ACCOUNT, REGION).isEmpty(), "the rejected update must not enable a stream");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+458
@@ -0,0 +1,458 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.backend;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Api;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Call;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Reply;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.CheckpointLifetime;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.Cursor;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.Position;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.RecordsPage;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.Shard;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
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 DynamoDB Streams reader over the raw seam, driven by a scripted engine. */
|
||||
class DynamoDbApiStreamReaderTest {
|
||||
|
||||
private static final String STREAM_ARN =
|
||||
"arn:aws:dynamodb:eu-west-1:333333333333:table/orders/stream/2026-09-25T00:00:00.000";
|
||||
private static final Stream STREAM = Stream.of(STREAM_ARN);
|
||||
private static final String ERROR_PREFIX = "com.amazonaws.dynamodb.v20120810#";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final List<Call> calls = new ArrayList<>();
|
||||
|
||||
private interface Script {
|
||||
Reply answer(Call call) throws Exception;
|
||||
}
|
||||
|
||||
private DynamoDbStreamReader reader(Script script) {
|
||||
return new DynamoDbApiStreamReader(call -> {
|
||||
calls.add(call);
|
||||
return script.answer(call);
|
||||
}, CheckpointLifetime.PROCESS);
|
||||
}
|
||||
|
||||
private Reply ok(String json) throws IOException {
|
||||
return new Reply(200, mapper.readTree(json), Map.of());
|
||||
}
|
||||
|
||||
private JsonNode json(String text) throws IOException {
|
||||
return mapper.readTree(text);
|
||||
}
|
||||
|
||||
private static String recordJson(String sequenceNumber) {
|
||||
return "{\"eventName\":\"INSERT\",\"dynamodb\":{\"SequenceNumber\":\"" + sequenceNumber + "\"}}";
|
||||
}
|
||||
|
||||
private static Shard shard(String shardId, String parentShardId) {
|
||||
return new Shard(shardId, parentShardId, null, null);
|
||||
}
|
||||
|
||||
private Reply trimmed() throws IOException {
|
||||
return new Reply(400, json("{\"__type\":\"" + ERROR_PREFIX
|
||||
+ "TrimmedDataAccessException\",\"message\":\"Trimmed\"}"), Map.of());
|
||||
}
|
||||
|
||||
private long trimHorizonIteratorCalls() {
|
||||
return calls.stream()
|
||||
.filter(call -> "GetShardIterator".equals(call.action()))
|
||||
.filter(call -> "TRIM_HORIZON".equals(call.body().path("ShardIteratorType").asText()))
|
||||
.count();
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamOfScopesToTheStreamOwner() {
|
||||
assertEquals(new Scope("333333333333", "eu-west-1"), STREAM.scope());
|
||||
assertEquals(STREAM_ARN, STREAM.arn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shardsFollowsLastEvaluatedShardIdAcrossPages() throws Exception {
|
||||
DynamoDbStreamReader reader = reader(call -> call.body().has("ExclusiveStartShardId")
|
||||
? ok("""
|
||||
{"StreamDescription":{"Shards":[{"ShardId":"child","ParentShardId":"parent",
|
||||
"SequenceNumberRange":{"StartingSequenceNumber":"5","EndingSequenceNumber":"9"}}],
|
||||
"LastEvaluatedShardId":null}}""")
|
||||
: ok("""
|
||||
{"StreamDescription":{"Shards":[{"ShardId":"parent",
|
||||
"SequenceNumberRange":{"StartingSequenceNumber":"1"}}],
|
||||
"LastEvaluatedShardId":"parent"}}"""));
|
||||
|
||||
List<Shard> shards = reader.shards(STREAM);
|
||||
|
||||
assertEquals(List.of(new Shard("parent", null, "1", null), new Shard("child", "parent", "5", "9")), shards);
|
||||
assertEquals(json("{\"StreamArn\":\"" + STREAM_ARN + "\"}"), calls.get(0).body());
|
||||
assertEquals(json("{\"StreamArn\":\"" + STREAM_ARN + "\",\"ExclusiveStartShardId\":\"parent\"}"),
|
||||
calls.get(1).body());
|
||||
assertEquals(2, calls.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeStreamSendsTheLimitAndReadsAMissingLastEvaluatedShardIdAsNull() throws Exception {
|
||||
DynamoDbStreamReader reader = reader(call -> ok("{\"StreamDescription\":{\"Shards\":[]}}"));
|
||||
|
||||
DynamoDbStreamReader.ShardsPage page = reader.describeStream(STREAM, "s0", 2);
|
||||
|
||||
assertEquals(json("{\"StreamArn\":\"" + STREAM_ARN + "\",\"ExclusiveStartShardId\":\"s0\",\"Limit\":2}"),
|
||||
calls.get(0).body());
|
||||
assertSame(STREAM, page.stream());
|
||||
assertTrue(page.shards().isEmpty());
|
||||
assertNull(page.lastEvaluatedShardId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void readableHoldsAChildUntilItsParentIsFinished() {
|
||||
List<Shard> shards = List.of(shard("parent", null), shard("child", "parent"),
|
||||
shard("orphan", "trimmed-away"), shard("grandchild", "child"));
|
||||
|
||||
assertEquals(List.of(shard("parent", null), shard("orphan", "trimmed-away")),
|
||||
DynamoDbStreamReader.readable(shards, Set.of()));
|
||||
assertEquals(List.of(shard("child", "parent"), shard("orphan", "trimmed-away")),
|
||||
DynamoDbStreamReader.readable(shards, Set.of("parent")));
|
||||
assertEquals(List.of(shard("orphan", "trimmed-away"), shard("grandchild", "child")),
|
||||
DynamoDbStreamReader.readable(shards, Set.of("parent", "child")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOpenEmptyPageKeepsItsCursorWhileAClosedShardEndsWithNone() throws Exception {
|
||||
DynamoDbStreamReader reader = reader(call -> switch (call.body().path("ShardIterator").asText()) {
|
||||
case "open" -> ok("{\"Records\":[],\"NextShardIterator\":\"open-2\"}");
|
||||
case "closed" -> ok("{\"Records\":[],\"NextShardIterator\":null}");
|
||||
default -> ok("{\"Records\":[]}");
|
||||
});
|
||||
|
||||
RecordsPage open = reader.getRecords(new Cursor(STREAM, "s1", "open"), 10);
|
||||
RecordsPage closed = reader.getRecords(new Cursor(STREAM, "s1", "closed"), 10);
|
||||
RecordsPage missing = reader.getRecords(new Cursor(STREAM, "s1", "missing"), 10);
|
||||
|
||||
assertTrue(open.records().isEmpty());
|
||||
assertEquals(new Cursor(STREAM, "s1", "open-2"), open.nextCursor());
|
||||
assertTrue(closed.records().isEmpty());
|
||||
assertNull(closed.nextCursor());
|
||||
assertNull(missing.nextCursor());
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorRepliesBecomeAwsExceptionsWithTheShortCode() {
|
||||
DynamoDbStreamReader reader = reader(call -> switch (call.body().path("ShardIterator").asText()) {
|
||||
case "expired" -> new Reply(400, json("{\"__type\":\"" + ERROR_PREFIX
|
||||
+ "ExpiredIteratorException\",\"message\":\"Iterator expired\"}"), Map.of());
|
||||
default -> new Reply(400, json("{\"__type\":\"" + ERROR_PREFIX
|
||||
+ "TrimmedDataAccessException\",\"Message\":\"Trimmed\"}"), Map.of());
|
||||
});
|
||||
|
||||
AwsException expired = assertThrows(AwsException.class,
|
||||
() -> reader.getRecords(new Cursor(STREAM, "s1", "expired"), 10));
|
||||
AwsException trimmed = assertThrows(AwsException.class,
|
||||
() -> reader.getRecords(new Cursor(STREAM, "s1", "trimmed"), 10));
|
||||
|
||||
assertEquals("ExpiredIteratorException", expired.getErrorCode());
|
||||
assertEquals("Iterator expired", expired.getMessage());
|
||||
assertEquals(400, expired.getHttpStatus());
|
||||
assertEquals("TrimmedDataAccessException", trimmed.getErrorCode());
|
||||
assertEquals("Trimmed", trimmed.getMessage());
|
||||
assertEquals(400, trimmed.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anErrorReplyWithoutATypeIsAnInternalServerError() {
|
||||
DynamoDbStreamReader reader = reader(call -> new Reply(500, null, Map.of()));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> reader.describeStream(STREAM, null, null));
|
||||
|
||||
assertEquals("InternalServerError", error.getErrorCode());
|
||||
assertEquals(500, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aThrownAwsExceptionPropagatesUnchanged() {
|
||||
AwsException thrown = new AwsException("ResourceNotFoundException", "Stream not found", 400);
|
||||
DynamoDbStreamReader reader = reader(call -> {
|
||||
throw thrown;
|
||||
});
|
||||
|
||||
assertSame(thrown, assertThrows(AwsException.class, () -> reader.describeStream(STREAM, null, null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCheckedExceptionBecomesAnIllegalStateException() {
|
||||
IOException thrown = new IOException("boom");
|
||||
DynamoDbStreamReader reader = reader(call -> {
|
||||
throw thrown;
|
||||
});
|
||||
|
||||
IllegalStateException error = assertThrows(IllegalStateException.class,
|
||||
() -> reader.describeStream(STREAM, null, null));
|
||||
assertSame(thrown, error.getCause());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyCallRunsUnderTheStreamScopeOnTheStreamsApi() throws Exception {
|
||||
DynamoDbStreamReader reader = reader(call -> switch (call.action()) {
|
||||
case "DescribeStream" -> ok("{\"StreamDescription\":{\"Shards\":[]}}");
|
||||
case "GetShardIterator" -> ok("{\"ShardIterator\":\"it\"}");
|
||||
default -> ok("{\"Records\":[],\"NextShardIterator\":\"it\"}");
|
||||
});
|
||||
|
||||
reader.describeStream(STREAM, null, null);
|
||||
Cursor cursor = reader.getShardIterator(STREAM, "s1", Position.LATEST, null);
|
||||
reader.getRecords(cursor, 10);
|
||||
|
||||
assertEquals(List.of("DescribeStream", "GetShardIterator", "GetRecords"),
|
||||
calls.stream().map(Call::action).toList());
|
||||
for (Call call : calls) {
|
||||
assertEquals(new Scope("333333333333", "eu-west-1"), call.scope());
|
||||
assertEquals(Api.DYNAMODB_STREAMS, call.api());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getShardIteratorSendsTheSequenceNumberOnlyWhenGiven() throws Exception {
|
||||
DynamoDbStreamReader reader = reader(call -> ok("{\"ShardIterator\":\"it-" + calls.size() + "\"}"));
|
||||
|
||||
Cursor fromStart = reader.getShardIterator(STREAM, "s1", Position.TRIM_HORIZON, null);
|
||||
Cursor afterFive = reader.getShardIterator(STREAM, "s1", Position.AFTER_SEQUENCE_NUMBER, "5");
|
||||
|
||||
assertEquals(json("{\"StreamArn\":\"" + STREAM_ARN
|
||||
+ "\",\"ShardId\":\"s1\",\"ShardIteratorType\":\"TRIM_HORIZON\"}"), calls.get(0).body());
|
||||
assertEquals(json("{\"StreamArn\":\"" + STREAM_ARN
|
||||
+ "\",\"ShardId\":\"s1\",\"ShardIteratorType\":\"AFTER_SEQUENCE_NUMBER\",\"SequenceNumber\":\"5\"}"),
|
||||
calls.get(1).body());
|
||||
assertEquals(new Cursor(STREAM, "s1", "it-1"), fromStart);
|
||||
assertEquals(new Cursor(STREAM, "s1", "it-2"), afterFive);
|
||||
}
|
||||
|
||||
@Test
|
||||
void repeatReadsOfOneCursorSendIdenticalRequestsAndLeaveTheRecordUntouched() throws Exception {
|
||||
Reply reply = ok("{\"Records\":[" + recordJson("7") + "],\"NextShardIterator\":\"next\"}");
|
||||
DynamoDbStreamReader reader = reader(call -> reply);
|
||||
Cursor cursor = new Cursor(STREAM, "s1", "it");
|
||||
|
||||
RecordsPage first = reader.getRecords(cursor, 10);
|
||||
RecordsPage second = reader.getRecords(cursor, 10);
|
||||
|
||||
assertEquals(json("{\"ShardIterator\":\"it\",\"Limit\":10}"), calls.get(0).body());
|
||||
assertEquals(calls.get(0).body(), calls.get(1).body());
|
||||
assertEquals("7", first.records().get(0).sequenceNumber());
|
||||
assertEquals(json(recordJson("7")), first.records().get(0).awsRecord());
|
||||
assertEquals(json(recordJson("7")), second.records().get(0).awsRecord());
|
||||
assertEquals(new Cursor(STREAM, "s1", "next"), first.nextCursor());
|
||||
}
|
||||
|
||||
@Test
|
||||
void newestSequenceNumbersRestartsAShardWhoseOldestRecordsWereTrimmedMeanwhile() throws Exception {
|
||||
DynamoDbStreamReader reader = reader(call -> switch (call.action()) {
|
||||
case "DescribeStream" -> ok("{\"StreamDescription\":{\"Shards\":[{\"ShardId\":\"s1\"}]}}");
|
||||
case "GetShardIterator" -> ok("{\"ShardIterator\":\"s1-" + trimHorizonIteratorCalls() + "\"}");
|
||||
default -> switch (call.body().path("ShardIterator").asText()) {
|
||||
case "s1-1" -> trimmed();
|
||||
case "s1-2" -> ok("{\"Records\":[" + recordJson("5") + "," + recordJson("6")
|
||||
+ "],\"NextShardIterator\":\"s1-3\"}");
|
||||
default -> ok("{\"Records\":[],\"NextShardIterator\":\"idle\"}");
|
||||
};
|
||||
});
|
||||
|
||||
Map<String, String> newest = reader.newestSequenceNumbers(STREAM);
|
||||
|
||||
assertEquals(Map.of("s1", "6"), newest);
|
||||
assertEquals(2, trimHorizonIteratorCalls());
|
||||
}
|
||||
|
||||
@Test
|
||||
void newestSequenceNumbersGivesUpAfterRepeatedTrims() {
|
||||
DynamoDbStreamReader reader = reader(call -> switch (call.action()) {
|
||||
case "DescribeStream" -> ok("{\"StreamDescription\":{\"Shards\":[{\"ShardId\":\"s1\"}]}}");
|
||||
case "GetShardIterator" -> ok("{\"ShardIterator\":\"it\"}");
|
||||
default -> trimmed();
|
||||
});
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> reader.newestSequenceNumbers(STREAM));
|
||||
|
||||
assertEquals("TrimmedDataAccessException", error.getErrorCode());
|
||||
assertEquals(4, trimHorizonIteratorCalls());
|
||||
}
|
||||
|
||||
@Test
|
||||
void newestSequenceNumbersScansEveryShardFromTrimHorizon() throws Exception {
|
||||
DynamoDbStreamReader reader = reader(call -> switch (call.action()) {
|
||||
case "DescribeStream" -> ok("""
|
||||
{"StreamDescription":{"Shards":[{"ShardId":"s1"},{"ShardId":"s2","ParentShardId":"s1"},
|
||||
{"ShardId":"s3"}]}}""");
|
||||
case "GetShardIterator" -> ok("{\"ShardIterator\":\"" + call.body().path("ShardId").asText() + "-0\"}");
|
||||
default -> switch (call.body().path("ShardIterator").asText()) {
|
||||
case "s1-0" -> ok("{\"Records\":[" + recordJson("1") + "," + recordJson("2")
|
||||
+ "],\"NextShardIterator\":\"s1-1\"}");
|
||||
case "s1-1" -> ok("{\"Records\":[" + recordJson("3") + "],\"NextShardIterator\":\"s1-2\"}");
|
||||
case "s2-0" -> ok("{\"Records\":[" + recordJson("10") + "],\"NextShardIterator\":null}");
|
||||
default -> ok("{\"Records\":[],\"NextShardIterator\":\"idle\"}");
|
||||
};
|
||||
});
|
||||
|
||||
Map<String, String> newest = reader.newestSequenceNumbers(STREAM);
|
||||
|
||||
assertEquals(Map.of("s1", "3", "s2", "10"), newest);
|
||||
assertFalse(calls.stream().anyMatch(call -> "idle".equals(call.body().path("ShardIterator").asText())));
|
||||
for (Call call : calls) {
|
||||
if ("GetShardIterator".equals(call.action())) {
|
||||
assertEquals("TRIM_HORIZON", call.body().path("ShardIteratorType").asText());
|
||||
} else if ("GetRecords".equals(call.action())) {
|
||||
assertEquals(1000, call.body().path("Limit").asInt());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getRecordsCapsTheLimitAtTheAwsMaximum() throws Exception {
|
||||
DynamoDbStreamReader reader = reader(call -> ok("{\"Records\":[],\"NextShardIterator\":\"it\"}"));
|
||||
|
||||
reader.getRecords(new Cursor(STREAM, "s1", "it"), 5000);
|
||||
|
||||
assertEquals(json("{\"ShardIterator\":\"it\",\"Limit\":1000}"), calls.get(0).body());
|
||||
}
|
||||
|
||||
@Test
|
||||
void readAfterStartsAtTheTrimHorizonWithoutACommittedSequenceAndAfterItOtherwise() throws Exception {
|
||||
DynamoDbStreamReader reader = reader(call -> {
|
||||
if ("GetShardIterator".equals(call.action())) {
|
||||
return ok("{\"ShardIterator\":\"it\"}");
|
||||
}
|
||||
return "it".equals(call.body().path("ShardIterator").asText())
|
||||
? ok("{\"Records\":[" + recordJson("7") + "],\"NextShardIterator\":\"next\"}")
|
||||
: ok("{\"Records\":[],\"NextShardIterator\":\"next\"}");
|
||||
});
|
||||
|
||||
reader.readAfter(STREAM, "s1", null, 10);
|
||||
assertEquals(json("{\"StreamArn\":\"" + STREAM_ARN
|
||||
+ "\",\"ShardId\":\"s1\",\"ShardIteratorType\":\"TRIM_HORIZON\"}"), calls.get(0).body());
|
||||
assertEquals(json("{\"ShardIterator\":\"it\",\"Limit\":10}"), calls.get(1).body());
|
||||
calls.clear();
|
||||
RecordsPage page = reader.readAfter(STREAM, "s1", "5", 10);
|
||||
|
||||
assertEquals(json("{\"StreamArn\":\"" + STREAM_ARN
|
||||
+ "\",\"ShardId\":\"s1\",\"ShardIteratorType\":\"AFTER_SEQUENCE_NUMBER\",\"SequenceNumber\":\"5\"}"),
|
||||
calls.get(0).body());
|
||||
assertEquals(json("{\"ShardIterator\":\"it\",\"Limit\":10}"), calls.get(1).body());
|
||||
assertEquals("7", page.records().get(0).sequenceNumber());
|
||||
}
|
||||
|
||||
/** A shard of 3000 records whose iterator {@code at-N} reads after the Nth one. */
|
||||
private DynamoDbStreamReader shardOf3000Records() {
|
||||
return reader(call -> {
|
||||
if ("GetShardIterator".equals(call.action())) {
|
||||
return ok("{\"ShardIterator\":\"at-0\"}");
|
||||
}
|
||||
int after = Integer.parseInt(call.body().path("ShardIterator").asText().substring(3));
|
||||
int end = Math.min(after + call.body().path("Limit").asInt(), 3000);
|
||||
StringBuilder records = new StringBuilder();
|
||||
for (int i = after + 1; i <= end; i++) {
|
||||
records.append(i > after + 1 ? "," : "").append(recordJson(String.valueOf(i)));
|
||||
}
|
||||
return ok("{\"Records\":[" + records + "],\"NextShardIterator\":\"at-" + end + "\"}");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void readAfterFillsALimitAboveTheAwsMaximumFromSeveralReads() throws Exception {
|
||||
RecordsPage page = shardOf3000Records().readAfter(STREAM, "s1", null, 2500);
|
||||
|
||||
assertEquals(List.of(1000, 1000, 500), calls.stream()
|
||||
.filter(call -> "GetRecords".equals(call.action()))
|
||||
.map(call -> call.body().path("Limit").asInt())
|
||||
.toList());
|
||||
assertEquals(2500, page.records().size());
|
||||
assertEquals("1", page.records().get(0).sequenceNumber());
|
||||
assertEquals("2500", page.records().get(2499).sequenceNumber());
|
||||
assertEquals(new Cursor(STREAM, "s1", "at-2500"), page.nextCursor());
|
||||
}
|
||||
|
||||
@Test
|
||||
void readAfterKeepsTheRecordsAlreadyReadWhenALaterReadIsTrimmed() throws Exception {
|
||||
List<String> firstPage = new ArrayList<>();
|
||||
StringBuilder records = new StringBuilder();
|
||||
for (int i = 1; i <= 1000; i++) {
|
||||
firstPage.add(String.valueOf(i));
|
||||
records.append(i > 1 ? "," : "").append(recordJson(String.valueOf(i)));
|
||||
}
|
||||
DynamoDbStreamReader reader = reader(call -> {
|
||||
if ("GetShardIterator".equals(call.action())) {
|
||||
return ok("{\"ShardIterator\":\"first\"}");
|
||||
}
|
||||
return "first".equals(call.body().path("ShardIterator").asText())
|
||||
? ok("{\"Records\":[" + records + "],\"NextShardIterator\":\"second\"}")
|
||||
: trimmed();
|
||||
});
|
||||
|
||||
RecordsPage page = reader.readAfter(STREAM, "s1", null, 1500);
|
||||
|
||||
assertEquals(firstPage, page.records().stream().map(DynamoDbStreamReader.Record::sequenceNumber).toList());
|
||||
assertFalse(page.closed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void readAfterReturnsWhatItReadAtTheTipOfAnOpenShardAndTheEndOfAClosedOne() throws Exception {
|
||||
DynamoDbStreamReader reader = reader(call -> {
|
||||
if ("GetShardIterator".equals(call.action())) {
|
||||
return ok("{\"ShardIterator\":\"" + call.body().path("ShardId").asText() + "\"}");
|
||||
}
|
||||
return switch (call.body().path("ShardIterator").asText()) {
|
||||
case "open" -> ok("{\"Records\":[" + recordJson("1") + "],\"NextShardIterator\":\"tip\"}");
|
||||
case "tip" -> ok("{\"Records\":[],\"NextShardIterator\":\"tip-2\"}");
|
||||
case "closing" -> ok("{\"Records\":[" + recordJson("2") + "],\"NextShardIterator\":null}");
|
||||
default -> ok("{\"Records\":[],\"NextShardIterator\":null}");
|
||||
};
|
||||
});
|
||||
|
||||
RecordsPage open = reader.readAfter(STREAM, "open", null, 10);
|
||||
RecordsPage closing = reader.readAfter(STREAM, "closing", null, 10);
|
||||
RecordsPage closed = reader.readAfter(STREAM, "closed", null, 10);
|
||||
|
||||
assertEquals(List.of("1"), open.records().stream().map(DynamoDbStreamReader.Record::sequenceNumber).toList());
|
||||
assertEquals(new Cursor(STREAM, "open", "tip-2"), open.nextCursor());
|
||||
assertEquals(List.of("2"), closing.records().stream().map(DynamoDbStreamReader.Record::sequenceNumber).toList());
|
||||
assertTrue(closed.closed());
|
||||
assertEquals(List.of(10, 9, 10, 10), calls.stream()
|
||||
.filter(call -> "GetRecords".equals(call.action()))
|
||||
.map(call -> call.body().path("Limit").asInt())
|
||||
.toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPageIsClosedOnlyWhenItHasNoRecordsAndNoNextCursor() throws Exception {
|
||||
List<DynamoDbStreamReader.Record> one = List.of(new DynamoDbStreamReader.Record("7", json(recordJson("7"))));
|
||||
Cursor next = new Cursor(STREAM, "s1", "next");
|
||||
|
||||
assertTrue(new RecordsPage(List.of(), null).closed());
|
||||
assertFalse(new RecordsPage(List.of(), next).closed());
|
||||
assertFalse(new RecordsPage(one, null).closed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkpointLifetimeEchoesTheConstructorValue() {
|
||||
DynamoDbOperations unused = call -> {
|
||||
throw new AssertionError("no call expected");
|
||||
};
|
||||
|
||||
assertEquals(CheckpointLifetime.PROCESS,
|
||||
new DynamoDbApiStreamReader(unused, CheckpointLifetime.PROCESS).checkpointLifetime());
|
||||
assertEquals(CheckpointLifetime.STREAM,
|
||||
new DynamoDbApiStreamReader(unused, CheckpointLifetime.STREAM).checkpointLifetime());
|
||||
}
|
||||
}
|
||||
+103
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.backend;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
@@ -8,8 +9,15 @@ import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Api;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Call;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.CheckpointLifetime;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.Cursor;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.Position;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.RecordsPage;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.Shard;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.Stream;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
import io.quarkus.arc.ClientProxy;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
@@ -21,6 +29,7 @@ import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -42,6 +51,9 @@ class DynamoDbBackendSelectionTest {
|
||||
@Inject
|
||||
DynamoDbTableAccess tables;
|
||||
|
||||
@Inject
|
||||
DynamoDbStreamReader streamReader;
|
||||
|
||||
// Collected exactly as ResourceExplorer2Service collects its providers.
|
||||
@Inject
|
||||
Instance<ResourceProvider> providers;
|
||||
@@ -87,4 +99,95 @@ class DynamoDbBackendSelectionTest {
|
||||
tables.deleteTable(ACCOUNT_A, tableName);
|
||||
}
|
||||
}
|
||||
|
||||
private void createTable(Scope scope, String tableName) {
|
||||
tables.createTable(scope, tableName, List.of(new KeySchemaElement("id", "HASH")),
|
||||
List.of(new AttributeDefinition("id", "S")), 5L, 5L, List.of(), List.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theStreamReaderReadsTheSelectedBackendAsTheStreamOwner() {
|
||||
String tableName = "backend-stream-" + UUID.randomUUID();
|
||||
createTable(ACCOUNT_A, tableName);
|
||||
try {
|
||||
TableDefinition table = tables.enableStream(ACCOUNT_A, tableName, "NEW_AND_OLD_IMAGES");
|
||||
ObjectNode item = mapper.createObjectNode();
|
||||
item.putObject("id").put("S", "streamed");
|
||||
items.putItem(ACCOUNT_A, tableName, item, null, null, null);
|
||||
|
||||
Stream stream = Stream.of(table.getStreamArn());
|
||||
List<Shard> shards = streamReader.shards(stream);
|
||||
Cursor cursor = streamReader.getShardIterator(stream, shards.get(0).shardId(), Position.TRIM_HORIZON, null);
|
||||
RecordsPage page = streamReader.getRecords(cursor, 10);
|
||||
|
||||
assertEquals(ACCOUNT_A, stream.scope());
|
||||
assertEquals(1, shards.size());
|
||||
assertEquals(1, page.records().size());
|
||||
assertEquals(item, page.records().get(0).awsRecord().path("dynamodb").path("Keys"));
|
||||
assertEquals(CheckpointLifetime.PROCESS, streamReader.checkpointLifetime());
|
||||
} finally {
|
||||
tables.deleteTable(ACCOUNT_A, tableName);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void listStreamsAnswersOnlyTheScopeAccount() throws Exception {
|
||||
String tableName = "backend-list-streams-" + UUID.randomUUID();
|
||||
createTable(ACCOUNT_A, tableName);
|
||||
createTable(ACCOUNT_B, tableName);
|
||||
try {
|
||||
String streamA = tables.enableStream(ACCOUNT_A, tableName, "KEYS_ONLY").getStreamArn();
|
||||
String streamB = tables.enableStream(ACCOUNT_B, tableName, "KEYS_ONLY").getStreamArn();
|
||||
assertNotEquals(streamA, streamB);
|
||||
|
||||
assertEquals(List.of(streamA), listedStreamArns(ACCOUNT_A, tableName));
|
||||
assertEquals(List.of(streamB), listedStreamArns(ACCOUNT_B, tableName));
|
||||
} finally {
|
||||
tables.deleteTable(ACCOUNT_A, tableName);
|
||||
tables.deleteTable(ACCOUNT_B, tableName);
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> listedStreamArns(Scope scope, String tableName) throws Exception {
|
||||
ObjectNode body = mapper.createObjectNode().put("TableName", tableName);
|
||||
JsonNode reply = operations.execute(new Call(scope, Api.DYNAMODB_STREAMS, "ListStreams", body)).body();
|
||||
return reply.path("Streams").findValuesAsText("StreamArn");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStreamOutsideTheScopeIsNotFound() throws Exception {
|
||||
String tableName = "backend-foreign-stream-" + UUID.randomUUID();
|
||||
createTable(ACCOUNT_A, tableName);
|
||||
try {
|
||||
String streamArn = tables.enableStream(ACCOUNT_A, tableName, "KEYS_ONLY").getStreamArn();
|
||||
ObjectNode item = mapper.createObjectNode();
|
||||
item.putObject("id").put("S", "private");
|
||||
items.putItem(ACCOUNT_A, tableName, item, null, null, null);
|
||||
ObjectNode stream = mapper.createObjectNode().put("StreamArn", streamArn);
|
||||
String shardId = streams(ACCOUNT_A, "DescribeStream", stream)
|
||||
.path("StreamDescription").path("Shards").path(0).path("ShardId").asText();
|
||||
ObjectNode fromStart = stream.deepCopy().put("ShardId", shardId).put("ShardIteratorType", "TRIM_HORIZON");
|
||||
String iterator = streams(ACCOUNT_A, "GetShardIterator", fromStart).path("ShardIterator").asText();
|
||||
ObjectNode read = mapper.createObjectNode().put("ShardIterator", iterator);
|
||||
|
||||
for (Scope outside : List.of(ACCOUNT_B, new Scope(ACCOUNT_A.accountId(), "eu-west-1"))) {
|
||||
assertStreamNotFound(outside, "DescribeStream", stream, streamArn);
|
||||
assertStreamNotFound(outside, "GetShardIterator", fromStart, streamArn);
|
||||
assertStreamNotFound(outside, "GetRecords", read, streamArn);
|
||||
}
|
||||
assertEquals(1, streams(ACCOUNT_A, "GetRecords", read).path("Records").size());
|
||||
} finally {
|
||||
tables.deleteTable(ACCOUNT_A, tableName);
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode streams(Scope scope, String action, ObjectNode body) throws Exception {
|
||||
return operations.execute(new Call(scope, Api.DYNAMODB_STREAMS, action, body)).body();
|
||||
}
|
||||
|
||||
private void assertStreamNotFound(Scope scope, String action, ObjectNode body, String streamArn) {
|
||||
AwsException notFound = assertThrows(AwsException.class, () -> streams(scope, action, body));
|
||||
assertEquals("ResourceNotFoundException", notFound.getErrorCode());
|
||||
assertEquals("Stream not found: " + streamArn, notFound.getMessage());
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -63,7 +63,8 @@ class DynamoDbNativeBackendTest {
|
||||
mock(KinesisStreamingForwarder.class), null, mapper, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS));
|
||||
NativeDynamoDbTableService tables = new NativeDynamoDbTableService(service, streams, mock(KinesisService.class));
|
||||
backend = new NativeDynamoDbBackend(new NativeDynamoDbJsonHandler(service, tables, mapper),
|
||||
new NativeDynamoDbStreamsJsonHandler(streams, service, mapper), service, mapper);
|
||||
new NativeDynamoDbStreamsJsonHandler(streams, service, new RegionResolver(REGION, ACCOUNT), mapper),
|
||||
service, mapper);
|
||||
}
|
||||
|
||||
private Reply call(Api api, String action, JsonNode body) throws Exception {
|
||||
|
||||
+351
-245
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,5 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.json.JsonPath;
|
||||
import io.restassured.path.json.config.JsonPathConfig;
|
||||
@@ -283,9 +282,10 @@ class EsmIntegrationTest {
|
||||
{"TableName": "%s", "Item": {"pk": {"S": "%s"}}}
|
||||
""".formatted(tableName, pk));
|
||||
}
|
||||
String shardId = "shardId-0000000001-00000000001";
|
||||
String iterator = dynamoDb("DynamoDBStreams_20120810.GetShardIterator", """
|
||||
{"StreamArn": "%s", "ShardId": "%s", "ShardIteratorType": "TRIM_HORIZON"}
|
||||
""".formatted(streamArn, DynamoDbStreamService.SHARD_ID)).getString("ShardIterator");
|
||||
""".formatted(streamArn, shardId)).getString("ShardIterator");
|
||||
String newestSequence = dynamoDb("DynamoDBStreams_20120810.GetRecords", """
|
||||
{"ShardIterator": "%s"}
|
||||
""".formatted(iterator)).getString("Records[-1].dynamodb.SequenceNumber");
|
||||
@@ -309,7 +309,7 @@ class EsmIntegrationTest {
|
||||
.path("UUID");
|
||||
|
||||
assertEquals(newestSequence, esmStore.getForAccount(ACCOUNT_ID, uuid).orElseThrow()
|
||||
.getShardSequenceNumbers().get(DynamoDbStreamService.SHARD_ID));
|
||||
.getShardSequenceNumbers().get(shardId));
|
||||
|
||||
given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid).then().statusCode(202);
|
||||
dynamoDb("DynamoDB_20120810.DeleteTable", "{\"TableName\": \"%s\"}".formatted(tableName));
|
||||
|
||||
@@ -2,12 +2,19 @@ package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader;
|
||||
import io.github.hectorvent.floci.services.kinesis.KinesisService;
|
||||
import io.github.hectorvent.floci.services.pipes.model.DesiredState;
|
||||
import io.github.hectorvent.floci.services.pipes.model.Pipe;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.sqs.model.Message;
|
||||
import io.vertx.core.Handler;
|
||||
import io.vertx.core.Vertx;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -17,20 +24,36 @@ import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.contains;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doNothing;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -38,25 +61,74 @@ import static org.mockito.Mockito.when;
|
||||
class PipesPollerTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String STREAM_ARN =
|
||||
"arn:aws:dynamodb:us-east-1:000000000000:table/orders/stream/2026-09-01T00:00:00.000";
|
||||
private static final String SHARD_ID = "shardId-0000000001-00000000001";
|
||||
private static final String DLQ_ARN = "arn:aws:sqs:us-east-1:000000000000:pipe-dlq";
|
||||
|
||||
@Mock private Vertx vertx;
|
||||
@Mock private SqsService sqsService;
|
||||
@Mock private KinesisService kinesisService;
|
||||
@Mock private DynamoDbStreamService dynamoDbStreamService;
|
||||
@Mock private PipesKafkaConsumerManager kafkaConsumerManager;
|
||||
@Mock private PipesTargetInvoker targetInvoker;
|
||||
@Mock private EmulatorConfig config;
|
||||
|
||||
private FakeStreamReader streams;
|
||||
private PipesPoller poller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
|
||||
lenient().when(kafkaConsumerManager.resolveBatchSize(any(), anyInt())).thenReturn(10);
|
||||
poller = new PipesPoller(vertx, sqsService, kinesisService, dynamoDbStreamService,
|
||||
streams = new FakeStreamReader();
|
||||
poller = pollerOver(streams);
|
||||
}
|
||||
|
||||
private PipesPoller pollerOver(DynamoDbStreamReader streamReader) {
|
||||
return new PipesPoller(vertx, sqsService, kinesisService, streamReader,
|
||||
kafkaConsumerManager, targetInvoker, new PipesFilterMatcher(MAPPER), MAPPER, config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves one open shard from memory the way the native engine does. A cursor is the sequence to
|
||||
* read after, or empty for the trim horizon, and a sequence older than the oldest retained record
|
||||
* is trimmed.
|
||||
*/
|
||||
static class FakeStreamReader implements DynamoDbStreamReader {
|
||||
|
||||
final List<Record> shard = new CopyOnWriteArrayList<>();
|
||||
|
||||
@Override
|
||||
public ShardsPage describeStream(Stream stream, String exclusiveStartShardId, Integer limit) {
|
||||
return new ShardsPage(stream, List.of(new Shard(SHARD_ID, null, null, null)), null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Cursor getShardIterator(Stream stream, String shardId, Position position, String sequenceNumber) {
|
||||
return new Cursor(stream, shardId, position == Position.TRIM_HORIZON ? "" : sequenceNumber);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RecordsPage getRecords(Cursor cursor, int limit) {
|
||||
String after = cursor.token();
|
||||
if (!after.isEmpty() && !shard.isEmpty() && after.compareTo(shard.get(0).sequenceNumber()) < 0) {
|
||||
throw new AwsException("TrimmedDataAccessException",
|
||||
"The requested sequence number has been trimmed", 400);
|
||||
}
|
||||
List<Record> page = shard.stream()
|
||||
.filter(record -> record.sequenceNumber().compareTo(after) > 0)
|
||||
.limit(limit)
|
||||
.toList();
|
||||
return new RecordsPage(page, page.isEmpty() ? cursor
|
||||
: new Cursor(cursor.stream(), cursor.shardId(), page.get(page.size() - 1).sequenceNumber()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CheckpointLifetime checkpointLifetime() {
|
||||
return CheckpointLifetime.PROCESS;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void asEventArrayWrapsSingleObjectInBatchArray() throws Exception {
|
||||
// Pipes delivers events to a target as a batch array; a single-object enrichment response
|
||||
@@ -275,6 +347,306 @@ class PipesPollerTest {
|
||||
assertEquals(2L, singleOffset(offsetsCaptor.getValue(), "orders", 0));
|
||||
}
|
||||
|
||||
// ──────────────────────────── DynamoDB Streams ────────────────────────────
|
||||
|
||||
@Test
|
||||
void targetFailureWithoutDlqRereadsTheSameDynamoDbRecordsNextPoll() throws Exception {
|
||||
Pipe pipe = dynamoDbPipe("{\"StartingPosition\":\"TRIM_HORIZON\"}");
|
||||
streams.shard.add(ddbRecord("001", "active"));
|
||||
doThrow(new RuntimeException("target down")).doNothing()
|
||||
.when(targetInvoker).invoke(eq(pipe), anyString(), eq("us-east-1"));
|
||||
|
||||
poller.startPolling(pipe);
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
|
||||
assertEquals(List.of(List.of("001"), List.of("001")), deliveredSequences(pipe));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dynamoDbBatchSentToTheDeadLetterQueueIsCommitted() throws Exception {
|
||||
Pipe pipe = dynamoDbPipe("{\"DeadLetterConfig\":{\"Arn\":\"" + DLQ_ARN + "\"}}");
|
||||
streams.shard.add(ddbRecord("001", "active"));
|
||||
doThrow(new RuntimeException("target down"))
|
||||
.when(targetInvoker).invoke(eq(pipe), anyString(), eq("us-east-1"));
|
||||
|
||||
poller.startPolling(pipe);
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
streams.shard.add(ddbRecord("002", "active"));
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
|
||||
assertEquals(List.of(List.of("001"), List.of("002")), deliveredSequences(pipe));
|
||||
verify(sqsService, times(2)).sendMessage(contains("pipe-dlq"), anyString(), eq(0), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dynamoDbBatchTheDeadLetterQueueRejectsIsRereadNextPoll() throws Exception {
|
||||
Pipe pipe = dynamoDbPipe("{\"DeadLetterConfig\":{\"Arn\":\"" + DLQ_ARN + "\"}}");
|
||||
streams.shard.add(ddbRecord("001", "active"));
|
||||
doThrow(new RuntimeException("target down"))
|
||||
.when(targetInvoker).invoke(eq(pipe), anyString(), eq("us-east-1"));
|
||||
doThrow(new RuntimeException("dlq down"))
|
||||
.when(sqsService).sendMessage(anyString(), anyString(), anyInt(), anyString());
|
||||
|
||||
poller.startPolling(pipe);
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
|
||||
assertEquals(List.of(List.of("001"), List.of("001")), deliveredSequences(pipe));
|
||||
}
|
||||
|
||||
@Test
|
||||
void laterDynamoDbRecordsWaitBehindAnUndeliveredBatch() throws Exception {
|
||||
Pipe pipe = dynamoDbPipe("{\"BatchSize\":1}");
|
||||
streams.shard.add(ddbRecord("001", "active"));
|
||||
streams.shard.add(ddbRecord("002", "active"));
|
||||
doThrow(new RuntimeException("target down")).doNothing()
|
||||
.when(targetInvoker).invoke(eq(pipe), anyString(), eq("us-east-1"));
|
||||
|
||||
poller.startPolling(pipe);
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
|
||||
assertEquals(List.of(List.of("001"), List.of("001"), List.of("002")), deliveredSequences(pipe));
|
||||
}
|
||||
|
||||
@Test
|
||||
void latestStartingPositionDeliversOnlyDynamoDbRecordsWrittenAfterTheFirstPoll() throws Exception {
|
||||
Pipe pipe = dynamoDbPipe("{\"StartingPosition\":\"LATEST\"}");
|
||||
streams.shard.add(ddbRecord("001", "active"));
|
||||
|
||||
poller.startPolling(pipe);
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
streams.shard.add(ddbRecord("002", "active"));
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
|
||||
assertEquals(List.of(List.of("002")), deliveredSequences(pipe));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stoppedAndRestartedLatestPipeResumesAfterItsLastDeliveredRecord() throws Exception {
|
||||
Pipe pipe = dynamoDbPipe("{\"StartingPosition\":\"LATEST\"}");
|
||||
streams.shard.add(ddbRecord("000", "active"));
|
||||
poller.startPolling(pipe);
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
streams.shard.add(ddbRecord("001", "active"));
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
|
||||
poller.stopPolling(pipe);
|
||||
streams.shard.add(ddbRecord("002", "active"));
|
||||
poller.startPolling(pipe);
|
||||
streams.shard.add(ddbRecord("003", "active"));
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
|
||||
assertEquals(List.of(List.of("001"), List.of("002", "003")), deliveredSequences(pipe));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletedPipeForgetsItsProgress() throws Exception {
|
||||
PipesService pipes = pipesOverPoller();
|
||||
Pipe pipe = createDynamoDbPipe(pipes);
|
||||
streams.shard.add(ddbRecord("001", "active"));
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
|
||||
pipes.deletePipe(pipe.getName(), "us-east-1");
|
||||
Pipe recreated = createDynamoDbPipe(pipes);
|
||||
poller.pollDynamoDbStreams(recreated, "us-east-1");
|
||||
|
||||
assertEquals(List.of(List.of("001")), deliveredSequences(recreated));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPollThatOutlivesItsDeletedPipeLeavesTheRecreatedPipeAlone() throws Exception {
|
||||
Pipe pipe = dynamoDbPipe("{\"StartingPosition\":\"TRIM_HORIZON\"}");
|
||||
pipe.setCreationTime(Instant.parse("2026-09-01T00:00:00Z"));
|
||||
streams.shard.add(ddbRecord("001", "active"));
|
||||
CountDownLatch delivering = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
delivering.countDown();
|
||||
release.await(5, TimeUnit.SECONDS);
|
||||
return null;
|
||||
}).when(targetInvoker).invoke(any(), anyString(), eq("us-east-1"));
|
||||
poller.startPolling(pipe);
|
||||
CompletableFuture<Void> inFlight =
|
||||
CompletableFuture.runAsync(() -> poller.pollDynamoDbStreams(pipe, "us-east-1"));
|
||||
assertTrue(delivering.await(5, TimeUnit.SECONDS));
|
||||
|
||||
poller.stopPolling(pipe);
|
||||
poller.forget(pipe);
|
||||
release.countDown();
|
||||
inFlight.get(5, TimeUnit.SECONDS);
|
||||
Pipe recreated = dynamoDbPipe("{\"StartingPosition\":\"TRIM_HORIZON\"}");
|
||||
recreated.setCreationTime(Instant.parse("2026-09-02T00:00:00Z"));
|
||||
poller.startPolling(recreated);
|
||||
// A tick the delete raced: it starts once the pipe is recreated under the same ARN.
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
poller.pollDynamoDbStreams(recreated, "us-east-1");
|
||||
|
||||
assertEquals(List.of(List.of("001")), deliveredSequences(recreated));
|
||||
assertEquals(List.of(List.of("001")), deliveredSequences(pipe));
|
||||
}
|
||||
|
||||
@Test
|
||||
void latestPinFailureDoesNotFailStartPolling() throws Exception {
|
||||
AtomicBoolean readerDown = new AtomicBoolean(true);
|
||||
FakeStreamReader flaky = new FakeStreamReader() {
|
||||
@Override
|
||||
public Map<String, String> newestSequenceNumbers(Stream stream) {
|
||||
if (readerDown.get()) {
|
||||
throw new IllegalStateException("engine unreachable");
|
||||
}
|
||||
return super.newestSequenceNumbers(stream);
|
||||
}
|
||||
};
|
||||
PipesPoller flakyPoller = pollerOver(flaky);
|
||||
Pipe pipe = dynamoDbPipe("{\"StartingPosition\":\"LATEST\"}");
|
||||
flaky.shard.add(ddbRecord("001", "active"));
|
||||
|
||||
flakyPoller.startPolling(pipe);
|
||||
assertThrows(IllegalStateException.class, () -> flakyPoller.pollDynamoDbStreams(pipe, "us-east-1"));
|
||||
readerDown.set(false);
|
||||
flakyPoller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
flaky.shard.add(ddbRecord("002", "active"));
|
||||
flakyPoller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
|
||||
assertEquals(List.of(List.of("002")), deliveredSequences(pipe));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dynamoDbRecordsAreFilteredAndDeliveredInTheAwsStreamRecordShape() throws Exception {
|
||||
Pipe pipe = dynamoDbPipe("{}");
|
||||
pipe.setSourceParameters(MAPPER.readTree("""
|
||||
{"DynamoDBStreamParameters":{"StartingPosition":"TRIM_HORIZON"},
|
||||
"FilterCriteria":{"Filters":[
|
||||
{"Pattern":"{\\"dynamodb\\":{\\"NewImage\\":{\\"status\\":{\\"S\\":[\\"active\\"]}}}}"}]}}"""));
|
||||
DynamoDbStreamReader.Record active = ddbRecord("001", "active");
|
||||
JsonNode original = active.awsRecord().deepCopy();
|
||||
streams.shard.add(active);
|
||||
streams.shard.add(ddbRecord("002", "inactive"));
|
||||
|
||||
poller.startPolling(pipe);
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
|
||||
ArgumentCaptor<String> payload = ArgumentCaptor.forClass(String.class);
|
||||
verify(targetInvoker).invoke(eq(pipe), payload.capture(), eq("us-east-1"));
|
||||
ObjectNode expected = original.deepCopy();
|
||||
expected.put("eventSourceARN", STREAM_ARN);
|
||||
ObjectNode event = MAPPER.createObjectNode();
|
||||
event.putArray("Records").add(expected);
|
||||
assertEquals(event, MAPPER.readTree(payload.getValue()));
|
||||
assertEquals(original, active.awsRecord(), "the reader's record is never mutated");
|
||||
}
|
||||
|
||||
@Test
|
||||
void trimmedDynamoDbCheckpointRestartsAtTheTrimHorizon() throws Exception {
|
||||
Pipe pipe = dynamoDbPipe("{}");
|
||||
streams.shard.add(ddbRecord("001", "active"));
|
||||
poller.startPolling(pipe);
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
streams.shard.clear();
|
||||
streams.shard.add(ddbRecord("003", "active"));
|
||||
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
poller.pollDynamoDbStreams(pipe, "us-east-1");
|
||||
|
||||
assertEquals(List.of(List.of("001"), List.of("003")), deliveredSequences(pipe));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pollTickReturnsAtOnceAndReadsTheStreamOnAPipesPollerThread() throws Exception {
|
||||
CountDownLatch reading = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
AtomicReference<String> readThread = new AtomicReference<>();
|
||||
AtomicBoolean readReturned = new AtomicBoolean();
|
||||
PipesPoller blockedPoller = pollerOver(new FakeStreamReader() {
|
||||
@Override
|
||||
public ShardsPage describeStream(Stream stream, String exclusiveStartShardId, Integer limit) {
|
||||
readThread.set(Thread.currentThread().getName());
|
||||
reading.countDown();
|
||||
try {
|
||||
release.await(5, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
readReturned.set(true);
|
||||
return super.describeStream(stream, exclusiveStartShardId, limit);
|
||||
}
|
||||
});
|
||||
Pipe pipe = dynamoDbPipe("{}");
|
||||
blockedPoller.startPolling(pipe);
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Handler<Long>> tick = ArgumentCaptor.forClass(Handler.class);
|
||||
verify(vertx).setPeriodic(eq(1000L), tick.capture());
|
||||
|
||||
try {
|
||||
tick.getValue().handle(1L);
|
||||
|
||||
assertFalse(readReturned.get(), "the tick returned while the read is still blocked");
|
||||
assertTrue(reading.await(5, TimeUnit.SECONDS), "the tick hands the read to the poll executor");
|
||||
assertEquals("pipes-poller", readThread.get());
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
private Pipe dynamoDbPipe(String dynamoDbStreamParameters) throws Exception {
|
||||
Pipe pipe = new Pipe();
|
||||
pipe.setName("orders-stream-pipe");
|
||||
pipe.setArn("arn:aws:pipes:us-east-1:000000000000:pipe/orders-stream-pipe");
|
||||
pipe.setSource(STREAM_ARN);
|
||||
pipe.setTarget("arn:aws:lambda:us-east-1:000000000000:function:orders-target");
|
||||
pipe.setDesiredState(DesiredState.RUNNING);
|
||||
pipe.setSourceParameters(MAPPER.readTree("{\"DynamoDBStreamParameters\":" + dynamoDbStreamParameters + "}"));
|
||||
return pipe;
|
||||
}
|
||||
|
||||
private PipesService pipesOverPoller() {
|
||||
StorageFactory storageFactory = mock(StorageFactory.class);
|
||||
doReturn(AccountAwareStorageBackend.inMemory("000000000000"))
|
||||
.when(storageFactory).create(anyString(), anyString(), any());
|
||||
return new PipesService(storageFactory, new RegionResolver("us-east-1", "000000000000"), poller);
|
||||
}
|
||||
|
||||
private Pipe createDynamoDbPipe(PipesService pipes) throws Exception {
|
||||
return pipes.createPipe("orders-stream-pipe", STREAM_ARN,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:orders-target",
|
||||
"arn:aws:iam::000000000000:role/pipe-role", null, null, null,
|
||||
MAPPER.readTree("{\"DynamoDBStreamParameters\":{\"StartingPosition\":\"TRIM_HORIZON\"}}"),
|
||||
null, null, null, "us-east-1");
|
||||
}
|
||||
|
||||
/** A GetRecords {@code Records[]} element as the native engine returns it. */
|
||||
private static DynamoDbStreamReader.Record ddbRecord(String sequenceNumber, String status) {
|
||||
ObjectNode awsRecord = MAPPER.createObjectNode()
|
||||
.put("eventID", "event-" + sequenceNumber)
|
||||
.put("eventName", "INSERT")
|
||||
.put("eventVersion", "1.1")
|
||||
.put("eventSource", "aws:dynamodb")
|
||||
.put("awsRegion", "us-east-1");
|
||||
ObjectNode dynamodb = awsRecord.putObject("dynamodb");
|
||||
dynamodb.putObject("NewImage").putObject("status").put("S", status);
|
||||
dynamodb.put("SequenceNumber", sequenceNumber).put("SizeBytes", 50).put("StreamViewType", "NEW_IMAGE");
|
||||
return new DynamoDbStreamReader.Record(sequenceNumber, awsRecord);
|
||||
}
|
||||
|
||||
/** The sequence numbers of each batch the Lambda target was invoked with, in invocation order. */
|
||||
private List<List<String>> deliveredSequences(Pipe pipe) throws Exception {
|
||||
ArgumentCaptor<String> payloads = ArgumentCaptor.forClass(String.class);
|
||||
verify(targetInvoker, atLeastOnce()).invoke(eq(pipe), payloads.capture(), eq("us-east-1"));
|
||||
List<List<String>> batches = new ArrayList<>();
|
||||
for (String payload : payloads.getAllValues()) {
|
||||
List<String> batch = new ArrayList<>();
|
||||
for (JsonNode record : MAPPER.readTree(payload).path("Records")) {
|
||||
batch.add(record.path("dynamodb").path("SequenceNumber").asText());
|
||||
}
|
||||
batches.add(batch);
|
||||
}
|
||||
return batches;
|
||||
}
|
||||
|
||||
private Pipe selfManagedKafkaPipe() throws Exception {
|
||||
Pipe pipe = new Pipe();
|
||||
pipe.setName("orders-pipe");
|
||||
|
||||
@@ -541,6 +541,32 @@ class PipesServiceTest {
|
||||
assertTrue(ex.getMessage().contains("must be between 1 and 10"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dynamoDbStreamRetryOptionsAreAcceptedAndReturned() {
|
||||
String created = """
|
||||
{"StartingPosition":"TRIM_HORIZON","MaximumRetryAttempts":3,"MaximumRecordAgeInSeconds":60,
|
||||
"OnPartialBatchItemFailure":"AUTOMATIC_BISECT"}""";
|
||||
String updated = """
|
||||
{"MaximumRetryAttempts":10000,"MaximumRecordAgeInSeconds":604800,
|
||||
"OnPartialBatchItemFailure":"AUTOMATIC_BISECT"}""";
|
||||
|
||||
pipesService.createPipe("ddb-retry-pipe",
|
||||
"arn:aws:dynamodb:us-east-1:000000000000:table/orders/stream/2024-01-01T00:00:00.000",
|
||||
"arn:aws:sqs:us-east-1:000000000000:target", "arn:aws:iam::000000000000:role/role",
|
||||
null, null, null, sourceParameters("{\"DynamoDBStreamParameters\":" + created + "}"),
|
||||
null, null, null, "us-east-1");
|
||||
assertEquals(sourceParameters(created), pipesService.describePipe("ddb-retry-pipe", "us-east-1")
|
||||
.getSourceParameters().path("DynamoDBStreamParameters"));
|
||||
|
||||
pipesService.updatePipe("ddb-retry-pipe", null, null, null, null, null,
|
||||
sourceParameters("{\"DynamoDBStreamParameters\":" + updated + "}"), null, null, "us-east-1");
|
||||
JsonNode stored = pipesService.describePipe("ddb-retry-pipe", "us-east-1")
|
||||
.getSourceParameters().path("DynamoDBStreamParameters");
|
||||
assertEquals(10000, stored.path("MaximumRetryAttempts").asInt());
|
||||
assertEquals(604800, stored.path("MaximumRecordAgeInSeconds").asInt());
|
||||
assertEquals("AUTOMATIC_BISECT", stored.path("OnPartialBatchItemFailure").asText());
|
||||
}
|
||||
|
||||
private static JsonNode sourceParameters(String json) {
|
||||
try {
|
||||
return MAPPER.readTree(json);
|
||||
|
||||
+231
-36
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
@@ -7,11 +8,11 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.CheckpointLifetime;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.RecordingDynamoDbBackend;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.RecordingDynamoDbBackend.Invocation;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.DynamoDbStreamRecord;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Integration;
|
||||
import io.github.hectorvent.floci.services.redshiftdata.RedshiftZeroEtlWriter;
|
||||
@@ -20,7 +21,12 @@ import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -29,6 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
@@ -46,37 +53,222 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
|
||||
@Inject
|
||||
DynamoDbFacade dynamoDb;
|
||||
|
||||
private static final String SHARD_ID = "shardId-0000000001-00000000001";
|
||||
|
||||
/**
|
||||
* Serves shards from memory the way the native engine does. A cursor is the sequence to read
|
||||
* after, or empty for the trim horizon, a sequence older than the oldest retained record is
|
||||
* trimmed, and a closed shard read to its end has no next cursor.
|
||||
*/
|
||||
static class FakeStreamReader implements DynamoDbStreamReader {
|
||||
|
||||
final List<String> iteratorRequests = new CopyOnWriteArrayList<>();
|
||||
private final List<Shard> shards = new CopyOnWriteArrayList<>();
|
||||
private final Map<String, List<Record>> records = new ConcurrentHashMap<>();
|
||||
private final Set<String> closed = ConcurrentHashMap.newKeySet();
|
||||
private final CheckpointLifetime lifetime;
|
||||
|
||||
FakeStreamReader(CheckpointLifetime lifetime) {
|
||||
this.lifetime = lifetime;
|
||||
}
|
||||
|
||||
List<Record> shard(String shardId, String parentShardId) {
|
||||
shards.add(new Shard(shardId, parentShardId, null, null));
|
||||
return records.computeIfAbsent(shardId, ignored -> new CopyOnWriteArrayList<>());
|
||||
}
|
||||
|
||||
void close(String shardId) {
|
||||
closed.add(shardId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ShardsPage describeStream(Stream stream, String exclusiveStartShardId, Integer limit) {
|
||||
return new ShardsPage(stream, List.copyOf(shards), null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Cursor getShardIterator(Stream stream, String shardId, Position position, String sequenceNumber) {
|
||||
iteratorRequests.add(shardId + ":" + position + ":" + sequenceNumber);
|
||||
return new Cursor(stream, shardId, position == Position.TRIM_HORIZON ? "" : sequenceNumber);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RecordsPage getRecords(Cursor cursor, int limit) {
|
||||
List<Record> held = new ArrayList<>(records.get(cursor.shardId()));
|
||||
String after = cursor.token();
|
||||
if (!after.isEmpty() && !held.isEmpty() && after.compareTo(held.get(0).sequenceNumber()) < 0) {
|
||||
throw new AwsException("TrimmedDataAccessException",
|
||||
"The requested sequence number has been trimmed", 400);
|
||||
}
|
||||
List<Record> page = held.stream()
|
||||
.filter(record -> record.sequenceNumber().compareTo(after) > 0)
|
||||
.limit(limit)
|
||||
.toList();
|
||||
if (page.isEmpty()) {
|
||||
return new RecordsPage(page, closed.contains(cursor.shardId()) ? null : cursor);
|
||||
}
|
||||
return new RecordsPage(page,
|
||||
new Cursor(cursor.stream(), cursor.shardId(), page.get(page.size() - 1).sequenceNumber()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CheckpointLifetime checkpointLifetime() {
|
||||
return lifetime;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesRecordsAndAdvancesCheckpointOnlyAfterSuccessfulBatch() {
|
||||
DynamoDbStreamService streamService = mock(DynamoDbStreamService.class);
|
||||
void writesTheAwsStreamRecordsAndCommitsShardProgressAfterTheWrite() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
Integration integration = integration("orders");
|
||||
integration.setBackfillCompleted(true);
|
||||
DynamoDbStreamRecord record = new DynamoDbStreamRecord();
|
||||
record.setEventId("event-1");
|
||||
record.setSequenceNumber("000000000000000000001");
|
||||
String iterator = "iterator";
|
||||
when(streamService.getShardIterator(eq(integration.getSourceStreamArn()), eq(DynamoDbStreamService.SHARD_ID),
|
||||
eq("TRIM_HORIZON"), eq(null))).thenReturn(iterator);
|
||||
when(streamService.getRecords(iterator, 100)).thenReturn(
|
||||
new DynamoDbStreamService.GetRecordsResult(List.of(record), "next"));
|
||||
when(writer.writeBatch(integration.getAccountId(), "warehouse", "floci_zetl_orders", List.of(record)))
|
||||
.thenReturn(record.getSequenceNumber());
|
||||
Integration integration = streamingIntegration();
|
||||
DynamoDbStreamReader.Record first = streamRecord("s1");
|
||||
DynamoDbStreamReader.Record second = streamRecord("s2");
|
||||
streams.shard(SHARD_ID, null).addAll(List.of(first, second));
|
||||
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer =
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDb, redshiftService, writer);
|
||||
consumer.pollOnce(integration);
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer).pollOnce(integration);
|
||||
|
||||
verify(writer).createLandingTable(integration.getAccountId(), "warehouse", "floci_zetl_orders");
|
||||
verify(writer).writeBatch(integration.getAccountId(), "warehouse", "floci_zetl_orders", List.of(record));
|
||||
verify(writer).writeBatch(integration.getAccountId(), "warehouse", "floci_zetl_orders",
|
||||
List.of(first.awsRecord(), second.awsRecord()));
|
||||
verify(redshiftService).updateIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn(),
|
||||
record.getSequenceNumber(), true, null);
|
||||
Map.of(SHARD_ID, "s2"), true, null);
|
||||
assertEquals(Map.of(SHARD_ID, "s2"), integration.getShardSequenceNumbers());
|
||||
assertEquals(List.of(SHARD_ID + ":TRIM_HORIZON:null"), streams.iteratorRequests);
|
||||
}
|
||||
|
||||
@Test
|
||||
void commitsProgressForEachShardAndResumesAfterIt() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
Integration integration = streamingIntegration();
|
||||
streams.shard("shard-a", null).add(streamRecord("a1"));
|
||||
streams.shard("shard-b", null).add(streamRecord("b1"));
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer =
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, mock(RedshiftService.class), writer);
|
||||
|
||||
consumer.pollOnce(integration);
|
||||
consumer.pollOnce(integration);
|
||||
|
||||
assertEquals(Map.of("shard-a", "a1", "shard-b", "b1"), integration.getShardSequenceNumbers());
|
||||
assertEquals(List.of("shard-a:TRIM_HORIZON:null", "shard-b:TRIM_HORIZON:null",
|
||||
"shard-a:AFTER_SEQUENCE_NUMBER:a1", "shard-b:AFTER_SEQUENCE_NUMBER:b1"), streams.iteratorRequests);
|
||||
verify(writer, times(2)).writeBatch(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedWriteKeepsProgressSoTheSameRecordsAreWrittenNextTick() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
doThrow(new AwsException("InternalFailure", "Could not write Redshift zero-ETL records.", 500))
|
||||
.doNothing()
|
||||
.when(writer).writeBatch(any(), any(), any(), any());
|
||||
Integration integration = streamingIntegration();
|
||||
integration.setShardSequenceNumbers(Map.of(SHARD_ID, "s1"));
|
||||
DynamoDbStreamReader.Record second = streamRecord("s2");
|
||||
streams.shard(SHARD_ID, null).addAll(List.of(streamRecord("s1"), second));
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer =
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer);
|
||||
|
||||
assertThrows(AwsException.class, () -> consumer.pollOnce(integration));
|
||||
|
||||
assertEquals(Map.of(SHARD_ID, "s1"), integration.getShardSequenceNumbers());
|
||||
verify(redshiftService, never()).updateIntegrationRuntime(any(), any(), any(), eq(true), any());
|
||||
|
||||
consumer.pollOnce(integration);
|
||||
|
||||
verify(writer, times(2)).writeBatch(integration.getAccountId(), "warehouse", "floci_zetl_orders",
|
||||
List.of(second.awsRecord()));
|
||||
assertEquals(Map.of(SHARD_ID, "s2"), integration.getShardSequenceNumbers());
|
||||
}
|
||||
|
||||
@Test
|
||||
void trimmedCheckpointRestartsTheShardAtTheTrimHorizon() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
Integration integration = streamingIntegration();
|
||||
integration.setShardSequenceNumbers(Map.of(SHARD_ID, "s0"));
|
||||
streams.shard(SHARD_ID, null).addAll(List.of(streamRecord("s1"), streamRecord("s2")));
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer =
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, mock(RedshiftService.class), writer);
|
||||
|
||||
AwsException trimmed = assertThrows(AwsException.class, () -> consumer.pollOnce(integration));
|
||||
assertEquals("TrimmedDataAccessException", trimmed.getErrorCode());
|
||||
assertTrue(integration.getShardSequenceNumbers().isEmpty());
|
||||
|
||||
consumer.pollOnce(integration);
|
||||
|
||||
assertEquals(Map.of(SHARD_ID, "s2"), integration.getShardSequenceNumbers());
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsAChildShardOnlyAfterItsParentIsReadToItsEnd() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
Integration integration = streamingIntegration();
|
||||
streams.shard("parent", null).add(streamRecord("p1"));
|
||||
streams.close("parent");
|
||||
streams.shard("child", "parent").add(streamRecord("c1"));
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer = new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb,
|
||||
mock(RedshiftService.class), mock(RedshiftZeroEtlWriter.class));
|
||||
|
||||
consumer.pollOnce(integration);
|
||||
consumer.pollOnce(integration);
|
||||
assertEquals(Map.of("parent", "p1"), integration.getShardSequenceNumbers());
|
||||
|
||||
consumer.pollOnce(integration);
|
||||
consumer.pollOnce(integration);
|
||||
|
||||
assertEquals(Map.of("parent", "p1", "child", "c1"), integration.getShardSequenceNumbers());
|
||||
assertEquals(List.of("parent:TRIM_HORIZON:null", "parent:AFTER_SEQUENCE_NUMBER:p1",
|
||||
"child:TRIM_HORIZON:null", "child:AFTER_SEQUENCE_NUMBER:c1"), streams.iteratorRequests);
|
||||
}
|
||||
|
||||
@Test
|
||||
void processLifetimeDiscardsPersistedShardProgressAtStartup() {
|
||||
Integration integration = streamingIntegration();
|
||||
integration.setShardSequenceNumbers(Map.of(SHARD_ID, "s9"));
|
||||
|
||||
startPersisted(CheckpointLifetime.PROCESS, integration);
|
||||
|
||||
assertTrue(integration.getShardSequenceNumbers().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamLifetimeKeepsPersistedShardProgressAtStartup() {
|
||||
Integration integration = streamingIntegration();
|
||||
integration.setShardSequenceNumbers(Map.of(SHARD_ID, "s9"));
|
||||
|
||||
startPersisted(CheckpointLifetime.STREAM, integration);
|
||||
|
||||
assertEquals(Map.of(SHARD_ID, "s9"), integration.getShardSequenceNumbers());
|
||||
}
|
||||
|
||||
private void startPersisted(CheckpointLifetime lifetime, Integration integration) {
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
when(redshiftService.listDynamoDbZeroEtlIntegrations()).thenReturn(List.of(integration));
|
||||
new RedshiftDynamoDbZeroEtlConsumer(new FakeStreamReader(lifetime), dynamoDb, redshiftService,
|
||||
mock(RedshiftZeroEtlWriter.class)).startPersistedIntegrations();
|
||||
}
|
||||
|
||||
private static DynamoDbStreamReader.Record streamRecord(String sequenceNumber) {
|
||||
ObjectNode awsRecord = MAPPER.createObjectNode()
|
||||
.put("eventID", "event-" + sequenceNumber)
|
||||
.put("eventName", "MODIFY");
|
||||
awsRecord.putObject("dynamodb").put("SequenceNumber", sequenceNumber);
|
||||
return new DynamoDbStreamReader.Record(sequenceNumber, awsRecord);
|
||||
}
|
||||
|
||||
private static Integration streamingIntegration() {
|
||||
Integration integration = integration("orders");
|
||||
integration.setBackfillCompleted(true);
|
||||
return integration;
|
||||
}
|
||||
|
||||
@Test
|
||||
void backfillsOnePageAtATimeBeforeSwitchingToStreamPolling() {
|
||||
DynamoDbStreamService streamService = mock(DynamoDbStreamService.class);
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
String tableName = "orders-page-" + System.nanoTime();
|
||||
@@ -99,28 +291,31 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
|
||||
assertThrows(AwsException.class, () -> dynamoDbService.describeTable(tableName, "us-east-1"));
|
||||
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer =
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDb, redshiftService, writer);
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer);
|
||||
consumer.pollOnce(integration);
|
||||
|
||||
assertFalse(integration.isBackfillCompleted());
|
||||
assertNotNull(integration.getBackfillLastEvaluatedKey());
|
||||
verify(redshiftService).updateIntegrationBackfillProgress(eq(integration.getAccountId()),
|
||||
eq(integration.getIntegrationArn()), eq(integration.getBackfillLastEvaluatedKey()), eq(false));
|
||||
verify(streamService, never()).getShardIterator(any(), any(), any(), any());
|
||||
assertTrue(streams.iteratorRequests.isEmpty());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<DynamoDbStreamRecord>> captor = ArgumentCaptor.forClass(List.class);
|
||||
ArgumentCaptor<List<JsonNode>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(writer).writeBatch(eq(integration.getAccountId()), eq("warehouse"), eq("floci_zetl_orders"),
|
||||
captor.capture());
|
||||
assertEquals(100, captor.getValue().size());
|
||||
DynamoDbStreamRecord written = captor.getValue().get(0);
|
||||
assertEquals("INSERT", written.getEventName());
|
||||
assertTrue(written.getEventId().startsWith("backfill#" + integration.getIntegrationArn() + "#"));
|
||||
JsonNode written = captor.getValue().get(0);
|
||||
assertEquals("INSERT", written.path("eventName").asText());
|
||||
assertTrue(written.path("eventID").asText().startsWith("backfill#" + integration.getIntegrationArn() + "#"));
|
||||
assertEquals("backfill", written.path("dynamodb").path("SequenceNumber").asText());
|
||||
assertEquals(written.path("dynamodb").path("Keys").path("id"),
|
||||
written.path("dynamodb").path("NewImage").path("id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void backfillCompletesWhenScanReturnsNoLastEvaluatedKey() {
|
||||
DynamoDbStreamService streamService = mock(DynamoDbStreamService.class);
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
String tableName = "orders-empty-" + System.nanoTime();
|
||||
@@ -136,7 +331,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
|
||||
assertThrows(AwsException.class, () -> dynamoDbService.describeTable(tableName, "us-east-1"));
|
||||
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer =
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDb, redshiftService, writer);
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer);
|
||||
consumer.pollOnce(integration);
|
||||
|
||||
assertTrue(integration.isBackfillCompleted());
|
||||
@@ -147,7 +342,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
|
||||
|
||||
@Test
|
||||
void sameItemProducesTheSameEventIdAcrossScans() {
|
||||
DynamoDbStreamService streamService = mock(DynamoDbStreamService.class);
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
String tableName = "orders-same-" + System.nanoTime();
|
||||
@@ -163,16 +358,16 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
|
||||
});
|
||||
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer =
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDb, redshiftService, writer);
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer);
|
||||
consumer.pollOnce(integration);
|
||||
integration.setBackfillCompleted(false);
|
||||
consumer.pollOnce(integration);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<DynamoDbStreamRecord>> captor = ArgumentCaptor.forClass(List.class);
|
||||
ArgumentCaptor<List<JsonNode>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(writer, times(2)).writeBatch(any(), any(), any(), captor.capture());
|
||||
assertEquals(captor.getAllValues().get(0).get(0).getEventId(),
|
||||
captor.getAllValues().get(1).get(0).getEventId());
|
||||
assertEquals(captor.getAllValues().get(0).get(0).path("eventID"),
|
||||
captor.getAllValues().get(1).get(0).path("eventID"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -182,7 +377,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
|
||||
Integration integration = integration("orders");
|
||||
integration.setSourceStreamArn("arn:aws:dynamodb:eu-west-1:111111111111:table/orders/stream/one");
|
||||
|
||||
new RedshiftDynamoDbZeroEtlConsumer(mock(DynamoDbStreamService.class), recording,
|
||||
new RedshiftDynamoDbZeroEtlConsumer(new FakeStreamReader(CheckpointLifetime.PROCESS), recording,
|
||||
mock(RedshiftService.class), mock(RedshiftZeroEtlWriter.class)).pollOnce(integration);
|
||||
|
||||
assertEquals(List.of(
|
||||
|
||||
+58
-16
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
@@ -8,8 +9,9 @@ import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.StreamDescription;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbApiStreamReader;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.CheckpointLifetime;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
@@ -33,6 +35,8 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -63,7 +67,7 @@ class RedshiftServiceTest {
|
||||
private DockerHostResolver dockerHostResolver;
|
||||
private RedshiftCredentialBroker credentialBroker;
|
||||
private SecretsManagerService secretsManagerService;
|
||||
private DynamoDbStreamService streamService;
|
||||
private final Set<String> existingStreams = new HashSet<>();
|
||||
private RedshiftService service;
|
||||
|
||||
@BeforeEach
|
||||
@@ -109,22 +113,27 @@ class RedshiftServiceTest {
|
||||
|
||||
credentialBroker = new RedshiftCredentialBroker();
|
||||
secretsManagerService = mock(SecretsManagerService.class);
|
||||
streamService = mock(DynamoDbStreamService.class);
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
// Answers DescribeStream the way the native handler does: it throws for an unknown stream.
|
||||
DynamoDbOperations streams = call -> {
|
||||
String streamArn = call.body().path("StreamArn").asText();
|
||||
if (!existingStreams.contains(streamArn)) {
|
||||
throw new AwsException("ResourceNotFoundException", "Stream not found: " + streamArn, 400);
|
||||
}
|
||||
return new DynamoDbOperations.Reply(200, mapper.readTree("{\"StreamDescription\":{\"Shards\":[]}}"),
|
||||
Map.of());
|
||||
};
|
||||
|
||||
service = new RedshiftService(sf, cm, config, regionResolver, proxyManager, dockerHostResolver,
|
||||
credentialBroker, secretsManagerService, new com.fasterxml.jackson.databind.ObjectMapper(),
|
||||
streamService);
|
||||
credentialBroker, secretsManagerService, mapper,
|
||||
new DynamoDbApiStreamReader(streams, CheckpointLifetime.PROCESS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDynamoDbZeroEtlIntegrationRequiresExistingProvisionedResources() {
|
||||
String streamArn = "arn:aws:dynamodb:us-east-1:111111111111:table/orders/stream/2026-09-18T00:00:00.000";
|
||||
String targetArn = "arn:aws:redshift:us-east-1:111111111111:cluster:warehouse";
|
||||
StreamDescription stream = new StreamDescription();
|
||||
stream.setStreamArn(streamArn);
|
||||
stream.setTableName("orders");
|
||||
stream.setStreamStatus("ENABLED");
|
||||
when(streamService.describeStream(streamArn)).thenReturn(stream);
|
||||
existingStreams.add(streamArn);
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("warehouse");
|
||||
when(clusterBackend.get("warehouse")).thenReturn(Optional.of(cluster));
|
||||
@@ -140,15 +149,48 @@ class RedshiftServiceTest {
|
||||
assertFalse(integration.isBackfillCompleted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDynamoDbZeroEtlIntegrationRejectsAMissingStreamWithResourceNotFound() {
|
||||
String streamArn = "arn:aws:dynamodb:us-east-1:111111111111:table/orders/stream/2026-09-18T00:00:00.000";
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.createIntegration(
|
||||
"orders-to-warehouse", streamArn, "arn:aws:redshift:us-east-1:111111111111:cluster:warehouse",
|
||||
null, null, Map.of(), Map.of(), "us-east-1"));
|
||||
|
||||
assertEquals("ResourceNotFoundException", error.getErrorCode());
|
||||
assertEquals("Stream not found: " + streamArn, error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
verify(integrationBackend, never()).put(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateIntegrationRuntimeStoresACopyOfShardProgressOnlyOnSuccess() {
|
||||
String integrationArn = "arn:aws:redshift:us-east-1:111111111111:integration:one";
|
||||
Integration integration = new Integration();
|
||||
integration.setIntegrationArn(integrationArn);
|
||||
when(integrationBackend.keysForAccount("111111111111")).thenReturn(Set.of("one"));
|
||||
when(integrationBackend.getForAccount("111111111111", "one")).thenReturn(Optional.of(integration));
|
||||
Map<String, String> progress = new HashMap<>(Map.of("shard-1", "s1"));
|
||||
|
||||
service.updateIntegrationRuntime("111111111111", integrationArn, progress, true, null);
|
||||
progress.put("shard-1", "s2");
|
||||
|
||||
assertEquals(Map.of("shard-1", "s1"), integration.getShardSequenceNumbers());
|
||||
assertEquals("active", integration.getStatus());
|
||||
|
||||
service.updateIntegrationRuntime("111111111111", integrationArn, progress, false, "boom");
|
||||
|
||||
assertEquals(Map.of("shard-1", "s1"), integration.getShardSequenceNumbers());
|
||||
assertEquals("failed", integration.getStatus());
|
||||
assertEquals("boom", integration.getLastError());
|
||||
verify(integrationBackend, times(2)).putForAccount("111111111111", "one", integration);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateIntegrationBackfillProgressPersistsCheckpointAndFlipsStatusOnCompletion() {
|
||||
String streamArn = "arn:aws:dynamodb:us-east-1:111111111111:table/orders/stream/2026-09-18T00:00:00.000";
|
||||
String targetArn = "arn:aws:redshift:us-east-1:111111111111:cluster:warehouse";
|
||||
StreamDescription stream = new StreamDescription();
|
||||
stream.setStreamArn(streamArn);
|
||||
stream.setTableName("orders");
|
||||
stream.setStreamStatus("ENABLED");
|
||||
when(streamService.describeStream(streamArn)).thenReturn(stream);
|
||||
existingStreams.add(streamArn);
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("warehouse");
|
||||
when(clusterBackend.get("warehouse")).thenReturn(Optional.of(cluster));
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package io.github.hectorvent.floci.services.redshift.model;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class IntegrationModelTest {
|
||||
|
||||
@Test
|
||||
void legacyJsonWithCheckpointSequenceNumberLoadsWithEmptyShardSequenceNumbers() throws Exception {
|
||||
// A default ObjectMapper, as the storage backends use, so an unknown property fails the load.
|
||||
Integration restored = new ObjectMapper().readValue("""
|
||||
{"integrationArn":"arn:aws:redshift:us-east-1:111111111111:integration:one",
|
||||
"checkpointSequenceNumber":"000000000000000000042","backfillCompleted":true}
|
||||
""", Integration.class);
|
||||
|
||||
assertEquals("arn:aws:redshift:us-east-1:111111111111:integration:one", restored.getIntegrationArn());
|
||||
assertTrue(restored.isBackfillCompleted());
|
||||
assertTrue(restored.getShardSequenceNumbers().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shardSequenceNumbersStayNonNullAndAreCopiedOnSet() throws Exception {
|
||||
Integration integration = new Integration();
|
||||
assertTrue(integration.getShardSequenceNumbers().isEmpty());
|
||||
|
||||
integration.setShardSequenceNumbers(null);
|
||||
assertTrue(integration.getShardSequenceNumbers().isEmpty());
|
||||
|
||||
Map<String, String> progress = new HashMap<>(Map.of("shard-1", "s1"));
|
||||
integration.setShardSequenceNumbers(progress);
|
||||
progress.put("shard-2", "s2");
|
||||
assertEquals(Map.of("shard-1", "s1"), integration.getShardSequenceNumbers());
|
||||
|
||||
Integration nulled = new ObjectMapper().readValue("{\"shardSequenceNumbers\":null}", Integration.class);
|
||||
assertTrue(nulled.getShardSequenceNumbers().isEmpty());
|
||||
}
|
||||
}
|
||||
+27
-18
@@ -1,8 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.DynamoDbStreamRecord;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -10,9 +10,10 @@ import org.junit.jupiter.api.Test;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Types;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.contains;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
@@ -40,7 +41,7 @@ class RedshiftZeroEtlWriterTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesStreamRecordsIdempotentlyAndReturnsNewestSequence() throws Exception {
|
||||
void writesAwsStreamRecordsIdempotently() throws Exception {
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftDataConnectionFactory connectionFactory = mock(RedshiftDataConnectionFactory.class);
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
@@ -50,16 +51,23 @@ class RedshiftZeroEtlWriterTest {
|
||||
when(connectionFactory.open(any())).thenReturn(connection);
|
||||
when(connection.prepareStatement(contains("ON CONFLICT (event_id) DO NOTHING"))).thenReturn(statement);
|
||||
|
||||
DynamoDbStreamRecord first = record("event-1", "000000000000000000001");
|
||||
DynamoDbStreamRecord second = record("event-2", "000000000000000000002");
|
||||
JsonNode first = record("event-1", "000000000000000000001");
|
||||
JsonNode second = record("event-2", "000000000000000000002");
|
||||
RedshiftZeroEtlWriter writer = new RedshiftZeroEtlWriter(redshiftService, connectionFactory, objectMapper);
|
||||
|
||||
String sequence = writer.writeBatch("111111111111", "warehouse", "floci_zetl_orders", List.of(first, second));
|
||||
writer.writeBatch("111111111111", "warehouse", "floci_zetl_orders", List.of(first, second));
|
||||
|
||||
assertEquals("000000000000000000002", sequence);
|
||||
verify(statement, times(2)).executeUpdate();
|
||||
verify(statement).setString(1, "event-1");
|
||||
verify(statement).setString(1, "event-2");
|
||||
verify(statement, times(2)).setString(2, "INSERT");
|
||||
verify(statement, times(2)).setString(3, "aws:dynamodb");
|
||||
verify(statement, times(2)).setString(4, "us-east-1");
|
||||
verify(statement).setString(5, "000000000000000000002");
|
||||
verify(statement, times(2)).setObject(6, Instant.ofEpochSecond(1_758_153_600L));
|
||||
verify(statement, times(2)).setString(7, "{\"id\":\"1\"}");
|
||||
verify(statement, times(2)).setNull(8, Types.VARCHAR);
|
||||
verify(statement, times(2)).setString(9, "{\"value\":\"new\"}");
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
@@ -73,16 +81,17 @@ class RedshiftZeroEtlWriterTest {
|
||||
return cluster;
|
||||
}
|
||||
|
||||
private static DynamoDbStreamRecord record(String eventId, String sequenceNumber) {
|
||||
DynamoDbStreamRecord record = new DynamoDbStreamRecord();
|
||||
record.setEventId(eventId);
|
||||
record.setEventName("INSERT");
|
||||
record.setEventSource("aws:dynamodb");
|
||||
record.setAwsRegion("us-east-1");
|
||||
record.setSequenceNumber(sequenceNumber);
|
||||
record.setApproximateCreationDateTime(1_758_153_600L);
|
||||
record.setKeys(JsonNodeFactory.instance.objectNode().put("id", "1"));
|
||||
record.setNewImage(JsonNodeFactory.instance.objectNode().put("value", "new"));
|
||||
private static JsonNode record(String eventId, String sequenceNumber) {
|
||||
ObjectNode record = new ObjectMapper().createObjectNode()
|
||||
.put("eventID", eventId)
|
||||
.put("eventName", "INSERT")
|
||||
.put("eventSource", "aws:dynamodb")
|
||||
.put("awsRegion", "us-east-1");
|
||||
ObjectNode dynamodb = record.putObject("dynamodb")
|
||||
.put("SequenceNumber", sequenceNumber)
|
||||
.put("ApproximateCreationDateTime", 1_758_153_600L);
|
||||
dynamodb.putObject("Keys").put("id", "1");
|
||||
dynamodb.putObject("NewImage").put("value", "new");
|
||||
return record;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user