feat: add DynamoDB to Redshift zero-ETL replication (#3872)

* feat: add DynamoDB to Redshift zero-ETL replication

* fix(redshift): preserve zero-etl account polling state

* fix(redshift): preserve zero-etl target account
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-18 22:35:10 -04:00
1 parent ecedddbc3b
commit 29b601834b
14 files changed
+721 -22

No files matched your search

@@ -0,0 +1,54 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
import io.github.hectorvent.floci.services.dynamodb.model.DynamoDbStreamRecord;
import io.github.hectorvent.floci.services.redshift.model.Integration;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftZeroEtlWriter;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
class RedshiftDynamoDbZeroEtlConsumerTest {
@Test
void writesRecordsAndAdvancesCheckpointOnlyAfterSuccessfulBatch() {
DynamoDbStreamService streamService = mock(DynamoDbStreamService.class);
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
Integration integration = integration();
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());
RedshiftDynamoDbZeroEtlConsumer consumer =
new RedshiftDynamoDbZeroEtlConsumer(streamService, redshiftService, writer);
consumer.pollOnce(integration);
verify(writer).createLandingTable(integration.getAccountId(), "warehouse", "floci_zetl_orders");
verify(writer).writeBatch(integration.getAccountId(), "warehouse", "floci_zetl_orders", List.of(record));
verify(redshiftService).updateIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn(),
record.getSequenceNumber(), true, null);
}
private static Integration integration() {
Integration integration = new Integration();
integration.setIntegrationArn("arn:aws:redshift:us-east-1:111111111111:integration:one");
integration.setAccountId("111111111111");
integration.setSourceStreamArn("arn:aws:dynamodb:us-east-1:111111111111:table/orders/stream/one");
integration.setTargetClusterIdentifier("warehouse");
integration.setLandingTableName("floci_zetl_orders");
integration.setPollingEnabled(true);
return integration;
}
}
@@ -2,9 +2,14 @@ package io.github.hectorvent.floci.services.redshift;
import java.util.ArrayList;
import java.util.List;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.config.HttpClientConfig;
import io.restassured.config.RestAssuredConfig;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
@@ -26,9 +31,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class RedshiftIntegrationsIntegrationTest {
private static final String SOURCE = "arn:aws:dynamodb:us-east-1:000000000000:table/keystone-main";
private static final String TARGET =
"arn:aws:redshift-serverless:us-east-1:000000000000:namespace/8445f0c7-d2b1-4c1c-916c-0eeaa68fd487";
private static String source;
private static String otherSource;
private static final String TARGET = "arn:aws:redshift:us-east-1:000000000000:cluster:zero-etl-cluster";
/**
* The Authorization header is what routes a Query request to a service; without it the
@@ -48,9 +53,50 @@ class RedshiftIntegrationsIntegrationTest {
return spec.when().post("/");
}
@BeforeEach
void createZeroEtlResources() {
if (source != null) {
return;
}
RestAssured.config = RestAssuredConfig.config()
.httpClient(HttpClientConfig.httpClientConfig().setParam("http.socket.timeout", 180_000));
RestAssuredJsonUtils.configureAwsContentTypes();
String newSource = createDynamoTable("keystone-main");
String newOtherSource = createDynamoTable("keystone-other");
query("Action", "CreateCluster", "ClusterIdentifier", "zero-etl-cluster",
"NodeType", "dc2.large", "MasterUsername", "admin", "MasterUserPassword", "password123")
.then().statusCode(200);
source = newSource;
otherSource = newOtherSource;
}
private static String createDynamoTable(String tableName) {
Response response = given()
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
.contentType("application/x-amz-json-1.0")
.body("""
{
"TableName": "%s",
"KeySchema": [{"AttributeName":"id","KeyType":"HASH"}],
"AttributeDefinitions": [{"AttributeName":"id","AttributeType":"S"}],
"BillingMode": "PAY_PER_REQUEST",
"StreamSpecification": {"StreamEnabled": true, "StreamViewType": "NEW_AND_OLD_IMAGES"}
}
""".formatted(tableName))
.when().post("/");
if (response.statusCode() != 200) {
response = given()
.header("X-Amz-Target", "DynamoDB_20120810.DescribeTable")
.contentType("application/x-amz-json-1.0")
.body("{\"TableName\":\"%s\"}".formatted(tableName))
.when().post("/");
}
return response.then().statusCode(200).extract().path("TableDescription.LatestStreamArn");
}
private static String createIntegration(String name) {
return query("Action", "CreateIntegration", "IntegrationName", name,
"SourceArn", SOURCE, "TargetArn", TARGET)
"SourceArn", source, "TargetArn", TARGET)
.then().statusCode(200)
.extract().body().asString();
}
@@ -67,7 +113,7 @@ class RedshiftIntegrationsIntegrationTest {
query("Action", "DescribeIntegrations")
.then().statusCode(200)
.body(containsString("zetl-described"))
.body(containsString(SOURCE))
.body(containsString(source))
.body(containsString(TARGET))
// Lower case on real Redshift, not ACTIVE.
.body(containsString("<Status>active</Status>"))
@@ -119,7 +165,7 @@ class RedshiftIntegrationsIntegrationTest {
createIntegration("zetl-duplicate");
query("Action", "CreateIntegration", "IntegrationName", "zetl-duplicate",
"SourceArn", SOURCE, "TargetArn", TARGET)
"SourceArn", source, "TargetArn", TARGET)
.then().statusCode(400)
.body(containsString("IntegrationAlreadyExistsFault"));
}
@@ -132,7 +178,7 @@ class RedshiftIntegrationsIntegrationTest {
// trailing hyphen are each outside it, so AWS refuses names floci used to accept.
for (String name : new String[] {"1zetl", "-zetl", "zetl_name", "zetl--name", "zetl-"}) {
query("Action", "CreateIntegration", "IntegrationName", name,
"SourceArn", SOURCE, "TargetArn", TARGET)
"SourceArn", source, "TargetArn", TARGET)
.then().statusCode(400)
.body(containsString("InvalidParameterValue"))
.body(containsString("IntegrationName"));
@@ -142,7 +188,7 @@ class RedshiftIntegrationsIntegrationTest {
@Test
void anIntegrationNameOverTheModelledLengthIsRejected() {
query("Action", "CreateIntegration", "IntegrationName", "z".repeat(64),
"SourceArn", SOURCE, "TargetArn", TARGET)
"SourceArn", source, "TargetArn", TARGET)
.then().statusCode(400)
.body(containsString("InvalidParameterValue"));
}
@@ -166,7 +212,7 @@ class RedshiftIntegrationsIntegrationTest {
void tagsSurviveTheRoundTrip() {
// The Query member is TagList, not Tags: an SDK serialises the list under its own name.
query("Action", "CreateIntegration", "IntegrationName", "zetl-tagged",
"SourceArn", SOURCE, "TargetArn", TARGET,
"SourceArn", source, "TargetArn", TARGET,
"TagList.Tag.1.Key", "Environment", "TagList.Tag.1.Value", "dev")
.then().statusCode(200);
@@ -187,7 +233,7 @@ class RedshiftIntegrationsIntegrationTest {
@Test
void descriptionAndEncryptionContextAreStoredAndReturned() {
query("Action", "CreateIntegration", "IntegrationName", "zetl-full",
"SourceArn", SOURCE, "TargetArn", TARGET,
"SourceArn", source, "TargetArn", TARGET,
"Description", "nightly replica",
"KMSKeyId", "arn:aws:kms:us-east-1:000000000000:key/abc",
"AdditionalEncryptionContext.entry.1.key", "team",
@@ -204,7 +250,7 @@ class RedshiftIntegrationsIntegrationTest {
@Test
void encryptionContextWithoutAKmsKeyIsRejected() {
query("Action", "CreateIntegration", "IntegrationName", "zetl-nokms",
"SourceArn", SOURCE, "TargetArn", TARGET,
"SourceArn", source, "TargetArn", TARGET,
"AdditionalEncryptionContext.entry.1.key", "team",
"AdditionalEncryptionContext.entry.1.value", "data")
.then().statusCode(400)
@@ -218,7 +264,7 @@ class RedshiftIntegrationsIntegrationTest {
// rather than absolute counts.
for (int i = 0; i < 21; i++) {
query("Action", "CreateIntegration", "IntegrationName", String.format("zetl-page-%02d", i),
"SourceArn", SOURCE + "-" + i, "TargetArn", TARGET)
"SourceArn", source, "TargetArn", TARGET)
.then().statusCode(200);
}
@@ -283,15 +329,15 @@ class RedshiftIntegrationsIntegrationTest {
@Test
void filteringBySourceArnNarrowsTheResult() {
query("Action", "CreateIntegration", "IntegrationName", "zetl-filtered",
"SourceArn", SOURCE + "-filtered", "TargetArn", TARGET)
"SourceArn", otherSource, "TargetArn", TARGET)
.then().statusCode(200);
query("Action", "CreateIntegration", "IntegrationName", "zetl-unfiltered",
"SourceArn", SOURCE + "-other", "TargetArn", TARGET)
"SourceArn", source, "TargetArn", TARGET)
.then().statusCode(200);
query("Action", "DescribeIntegrations",
"Filters.DescribeIntegrationsFilter.1.Name", "source-arn",
"Filters.DescribeIntegrationsFilter.1.Values.Value.1", SOURCE + "-filtered")
"Filters.DescribeIntegrationsFilter.1.Values.Value.1", otherSource)
.then().statusCode(200)
.body(containsString("zetl-filtered"))
.body(not(containsString("zetl-unfiltered")));
@@ -6,12 +6,15 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
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.dynamodb.DynamoDbStreamService;
import io.github.hectorvent.floci.services.dynamodb.model.StreamDescription;
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;
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup;
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
import io.github.hectorvent.floci.services.redshift.model.Integration;
import io.github.hectorvent.floci.services.redshift.model.Parameter;
import io.github.hectorvent.floci.services.redshift.model.Snapshot;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
@@ -45,12 +48,14 @@ class RedshiftServiceTest {
private AccountAwareStorageBackend<String> snapshotDumpBackend;
private AccountAwareStorageBackend<ClusterParameterGroup> parameterGroupBackend;
private AccountAwareStorageBackend<ClusterSubnetGroup> subnetGroupBackend;
private AccountAwareStorageBackend<Integration> integrationBackend;
private RedshiftContainerManager cm;
private RegionResolver regionResolver;
private RedshiftProxyManager proxyManager;
private DockerHostResolver dockerHostResolver;
private RedshiftCredentialBroker credentialBroker;
private SecretsManagerService secretsManagerService;
private DynamoDbStreamService streamService;
private RedshiftService service;
@BeforeEach
@@ -62,6 +67,7 @@ class RedshiftServiceTest {
snapshotDumpBackend = mock(AccountAwareStorageBackend.class);
parameterGroupBackend = mock(AccountAwareStorageBackend.class);
subnetGroupBackend = mock(AccountAwareStorageBackend.class);
integrationBackend = mock(AccountAwareStorageBackend.class);
cm = mock(RedshiftContainerManager.class);
proxyManager = mock(RedshiftProxyManager.class);
dockerHostResolver = mock(DockerHostResolver.class);
@@ -86,15 +92,49 @@ class RedshiftServiceTest {
when(sf.<Snapshot>create(eq("redshift"), eq("redshift-snapshots.json"), any())).thenReturn(snapshotBackend);
when(sf.<ClusterParameterGroup>create(eq("redshift"), eq("redshift-parameter-groups.json"), any())).thenReturn(parameterGroupBackend);
when(sf.<ClusterSubnetGroup>create(eq("redshift"), eq("redshift-subnet-groups.json"), any())).thenReturn(subnetGroupBackend);
when(sf.<Integration>create(eq("redshift"), eq("redshift-integrations.json"), any())).thenReturn(integrationBackend);
when(clusterBackend.accountId()).thenReturn("111111111111");
regionResolver = new RegionResolver("us-east-1", "111111111111");
credentialBroker = new RedshiftCredentialBroker();
secretsManagerService = mock(SecretsManagerService.class);
streamService = mock(DynamoDbStreamService.class);
service = new RedshiftService(sf, cm, config, regionResolver, proxyManager, dockerHostResolver,
credentialBroker, secretsManagerService, new com.fasterxml.jackson.databind.ObjectMapper());
credentialBroker, secretsManagerService, new com.fasterxml.jackson.databind.ObjectMapper(),
streamService);
}
@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);
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("warehouse");
when(clusterBackend.get("warehouse")).thenReturn(Optional.of(cluster));
when(integrationBackend.scan(any())).thenReturn(List.of());
Integration integration = service.createIntegration("orders-to-warehouse", streamArn, targetArn,
null, null, Map.of(), Map.of(), "us-east-1");
assertEquals(streamArn, integration.getSourceStreamArn());
assertEquals("warehouse", integration.getTargetClusterIdentifier());
assertNotNull(integration.getLandingTableName());
}
@Test
void createDynamoDbZeroEtlIntegrationRejectsServerlessTarget() {
assertThrows(AwsException.class, () -> service.createIntegration(
"orders-to-serverless",
"arn:aws:dynamodb:us-east-1:111111111111:table/orders/stream/2026-09-18T00:00:00.000",
"arn:aws:redshift-serverless:us-east-1:111111111111:workgroup/analytics",
null, null, Map.of(), Map.of(), "us-east-1"));
}
/** Absolute dump path as {@code createSnapshot} now stores it: under {@code <persistentPath>/redshift-dumps/<accountId>}. */
@@ -390,6 +430,19 @@ class RedshiftServiceTest {
assertEquals("test-c", list.get(0).getClusterIdentifier());
}
@Test
void describeClustersForAccountUsesTheRequestedAccount() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("test-c");
when(clusterBackend.getForAccount("222222222222", "test-c")).thenReturn(Optional.of(cluster));
List<Cluster> list = service.describeClustersForAccount("222222222222", "test-c");
assertEquals(List.of(cluster), list);
verify(clusterBackend).getForAccount("222222222222", "test-c");
verify(clusterBackend, never()).get("test-c");
}
@Test
void testDeleteCluster() {
Cluster c = new Cluster();
@@ -0,0 +1,88 @@
package io.github.hectorvent.floci.services.redshiftdata;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import io.github.hectorvent.floci.services.dynamodb.model.DynamoDbStreamRecord;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
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.*;
class RedshiftZeroEtlWriterTest {
@Test
void createsLandingTableWithStableEventColumns() throws Exception {
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftDataConnectionFactory connectionFactory = mock(RedshiftDataConnectionFactory.class);
ObjectMapper objectMapper = new ObjectMapper();
Connection connection = mock(Connection.class);
Statement statement = mock(Statement.class);
Cluster cluster = cluster();
when(redshiftService.describeClustersForAccount("111111111111", "warehouse")).thenReturn(List.of(cluster));
when(connectionFactory.open(any())).thenReturn(connection);
when(connection.createStatement()).thenReturn(statement);
RedshiftZeroEtlWriter writer = new RedshiftZeroEtlWriter(redshiftService, connectionFactory, objectMapper);
writer.createLandingTable("111111111111", "warehouse", "floci_zetl_orders");
verify(statement).executeUpdate(contains("event_id TEXT PRIMARY KEY"));
verify(statement).executeUpdate(contains("new_image_json TEXT"));
verify(connection).close();
}
@Test
void writesStreamRecordsIdempotentlyAndReturnsNewestSequence() throws Exception {
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftDataConnectionFactory connectionFactory = mock(RedshiftDataConnectionFactory.class);
ObjectMapper objectMapper = new ObjectMapper();
Connection connection = mock(Connection.class);
PreparedStatement statement = mock(PreparedStatement.class);
when(redshiftService.describeClustersForAccount("111111111111", "warehouse")).thenReturn(List.of(cluster()));
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");
RedshiftZeroEtlWriter writer = new RedshiftZeroEtlWriter(redshiftService, connectionFactory, objectMapper);
String sequence = 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(connection).close();
}
private static Cluster cluster() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("warehouse");
cluster.setContainerHost("localhost");
cluster.setContainerPort(5432);
cluster.setMasterUsername("admin");
cluster.setMasterPassword("password");
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"));
return record;
}
}