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

@@ -1396,6 +1396,9 @@ public interface EmulatorConfig {
@WithDefault("7199")
int proxyMaxPort();
@WithDefault("1000")
long pollIntervalMs();
// Hostname clients use to reach a cluster endpoint. Empty -> resolved from
// DockerHostResolver (falls back to "localhost").
Optional<String> endpointHost();
@@ -0,0 +1,158 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
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 io.quarkus.runtime.StartupEvent;
import io.vertx.core.Vertx;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@ApplicationScoped
public class RedshiftDynamoDbZeroEtlConsumer {
private static final Logger LOG = Logger.getLogger(RedshiftDynamoDbZeroEtlConsumer.class);
private static final int BATCH_SIZE = 100;
private final Vertx vertx;
private final DynamoDbStreamService streamService;
private final RedshiftService redshiftService;
private final RedshiftZeroEtlWriter writer;
private final long pollIntervalMs;
private final ConcurrentHashMap<String, Long> timerIds = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Boolean> activePolls = new ConcurrentHashMap<>();
private final ExecutorService pollExecutor = Executors.newCachedThreadPool(runnable -> {
Thread thread = new Thread(runnable, "redshift-zero-etl");
thread.setDaemon(true);
return thread;
});
@Inject
public RedshiftDynamoDbZeroEtlConsumer(Vertx vertx,
DynamoDbStreamService streamService,
RedshiftService redshiftService,
RedshiftZeroEtlWriter writer,
EmulatorConfig config) {
this(vertx, streamService, redshiftService, writer, config.services().redshift().pollIntervalMs());
}
RedshiftDynamoDbZeroEtlConsumer(DynamoDbStreamService streamService,
RedshiftService redshiftService,
RedshiftZeroEtlWriter writer) {
this(null, streamService, redshiftService, writer, 1000);
}
private RedshiftDynamoDbZeroEtlConsumer(Vertx vertx,
DynamoDbStreamService streamService,
RedshiftService redshiftService,
RedshiftZeroEtlWriter writer,
long pollIntervalMs) {
this.vertx = vertx;
this.streamService = streamService;
this.redshiftService = redshiftService;
this.writer = writer;
this.pollIntervalMs = pollIntervalMs;
}
void onStart(@Observes StartupEvent event) {
startPersistedIntegrations();
}
public void startPersistedIntegrations() {
for (Integration integration : redshiftService.listDynamoDbZeroEtlIntegrations()) {
if (integration.isPollingEnabled()) {
startPolling(integration);
}
}
}
public void startPolling(Integration integration) {
if (vertx == null || timerIds.containsKey(integration.getIntegrationArn())) {
return;
}
long timerId = vertx.setPeriodic(pollIntervalMs, ignored -> pollAnd(integration));
timerIds.put(integration.getIntegrationArn(), timerId);
}
public void stopPolling(String integrationArn) {
Long timerId = timerIds.remove(integrationArn);
if (timerId != null) {
vertx.cancelTimer(timerId);
}
activePolls.remove(integrationArn);
}
void pollOnce(Integration integration) {
writer.createLandingTable(integration.getAccountId(), integration.getTargetClusterIdentifier(),
integration.getLandingTableName());
String iteratorType = integration.getCheckpointSequenceNumber() == null
? "TRIM_HORIZON" : "AFTER_SEQUENCE_NUMBER";
String iterator = streamService.getShardIterator(integration.getSourceStreamArn(),
DynamoDbStreamService.SHARD_ID, iteratorType, integration.getCheckpointSequenceNumber());
DynamoDbStreamService.GetRecordsResult result = streamService.getRecords(iterator, BATCH_SIZE);
if (result.records().isEmpty()) {
return;
}
String sequence = writer.writeBatch(integration.getAccountId(), integration.getTargetClusterIdentifier(),
integration.getLandingTableName(), result.records());
redshiftService.updateIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn(),
sequence, true, null);
integration.setCheckpointSequenceNumber(sequence);
}
public void reset() {
for (String integrationArn : timerIds.keySet()) {
stopPolling(integrationArn);
}
activePolls.clear();
}
@PreDestroy
void onStop() {
reset();
pollExecutor.shutdownNow();
}
private void pollAnd(Integration integration) {
String integrationArn = integration.getIntegrationArn();
if (activePolls.putIfAbsent(integrationArn, Boolean.TRUE) != null) {
return;
}
pollExecutor.submit(() -> {
try {
pollSafely(integration);
} finally {
activePolls.remove(integrationArn);
}
});
}
private void pollSafely(Integration integration) {
try {
pollOnce(integration);
} catch (Exception e) {
LOG.warnv(e, "Zero-ETL polling failed for integration {0}", integration.getIntegrationArn());
if (e instanceof AwsException awsException
&& "TrimmedDataAccessException".equals(awsException.getErrorCode())) {
integration.setCheckpointSequenceNumber(null);
}
try {
redshiftService.updateIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn(),
integration.getCheckpointSequenceNumber(), false, e.getMessage());
} catch (Exception updateError) {
LOG.warnv(updateError, "Could not persist zero-ETL failure for integration {0}",
integration.getIntegrationArn());
}
}
}
}
@@ -42,16 +42,25 @@ public class RedshiftQueryHandler {
private final EmulatorConfig config;
private final RedshiftIamDbUserResolver iamDbUserResolver;
private final RegionResolver regionResolver;
private final RedshiftDynamoDbZeroEtlConsumer zeroEtlConsumer;
@Inject
public RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker,
EmulatorConfig config, RedshiftIamDbUserResolver iamDbUserResolver,
RegionResolver regionResolver) {
RegionResolver regionResolver,
RedshiftDynamoDbZeroEtlConsumer zeroEtlConsumer) {
this.service = service;
this.credentialBroker = credentialBroker;
this.config = config;
this.iamDbUserResolver = iamDbUserResolver;
this.regionResolver = regionResolver;
this.zeroEtlConsumer = zeroEtlConsumer;
}
RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker,
EmulatorConfig config, RedshiftIamDbUserResolver iamDbUserResolver,
RegionResolver regionResolver) {
this(service, credentialBroker, config, iamDbUserResolver, regionResolver, null);
}
public Response handle(String action, MultivaluedMap<String, String> params) {
@@ -372,6 +381,9 @@ public class RedshiftQueryHandler {
encryptionContextMap(params),
tagMap(params),
regionResolver.resolveRegionFromAuth(authorizationHeader));
if (zeroEtlConsumer != null) {
zeroEtlConsumer.startPolling(integration);
}
String xml = new XmlBuilder()
.start("CreateIntegrationResponse")
.start("CreateIntegrationResult")
@@ -414,6 +426,9 @@ public class RedshiftQueryHandler {
}
case "DeleteIntegration" -> {
Integration integration = service.deleteIntegration(params.getFirst("IntegrationArn"));
if (zeroEtlConsumer != null) {
zeroEtlConsumer.stopPolling(integration.getIntegrationArn());
}
String xml = new XmlBuilder()
.start("DeleteIntegrationResponse")
.start("DeleteIntegrationResult")
@@ -8,6 +8,7 @@ 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.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager;
@@ -74,6 +75,7 @@ public class RedshiftService {
private final RedshiftCredentialBroker credentialBroker;
private final SecretsManagerService secretsManagerService;
private final ObjectMapper objectMapper;
private final DynamoDbStreamService streamService;
// Proxy ports currently handed out, so allocateProxyPort never double-assigns within this JVM.
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
@@ -82,7 +84,8 @@ public class RedshiftService {
EmulatorConfig config, RegionResolver regionResolver,
RedshiftProxyManager proxyManager, DockerHostResolver dockerHostResolver,
RedshiftCredentialBroker credentialBroker,
SecretsManagerService secretsManagerService, ObjectMapper objectMapper) {
SecretsManagerService secretsManagerService, ObjectMapper objectMapper,
DynamoDbStreamService streamService) {
this.clusters = storageFactory.create("redshift", "redshift-clusters.json", new TypeReference<Map<String, Cluster>>() {});
this.snapshots = storageFactory.create("redshift", "redshift-snapshots.json", new TypeReference<Map<String, Snapshot>>() {});
this.parameterGroups = storageFactory.create("redshift", "redshift-parameter-groups.json", new TypeReference<Map<String, ClusterParameterGroup>>() {});
@@ -96,6 +99,7 @@ public class RedshiftService {
this.credentialBroker = credentialBroker;
this.secretsManagerService = secretsManagerService;
this.objectMapper = objectMapper;
this.streamService = streamService;
}
RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager,
@@ -103,7 +107,7 @@ public class RedshiftService {
RedshiftProxyManager proxyManager, DockerHostResolver dockerHostResolver,
RedshiftCredentialBroker credentialBroker) {
this(storageFactory, containerManager, config, regionResolver, proxyManager, dockerHostResolver,
credentialBroker, null, new ObjectMapper());
credentialBroker, null, new ObjectMapper(), null);
}
// Recreate Docker containers for persisted clusters on app restart (across every account, not just default)
@@ -314,6 +318,26 @@ public class RedshiftService {
if (targetArn == null || targetArn.isBlank()) {
throw new AwsException("InvalidParameterValue", "TargetArn is required.", 400);
}
AwsArnUtils.Arn source = parseZeroEtlArn(sourceArn, "DynamoDB stream");
if (!"dynamodb".equals(source.service()) || !source.resource().startsWith("table/")
|| !source.resource().contains("/stream/")) {
throw new AwsException("InvalidParameterValue",
"SourceArn must identify a DynamoDB stream.", 400);
}
if (streamService == null) {
throw new AwsException("InternalFailure", "DynamoDB stream service is unavailable.", 500);
}
streamService.describeStream(sourceArn);
AwsArnUtils.Arn target = parseZeroEtlArn(targetArn, "Redshift cluster");
if (!"redshift".equals(target.service()) || !target.resource().startsWith("cluster:")) {
throw new AwsException("InvalidParameterValue",
"TargetArn must identify a provisioned Redshift cluster.", 400);
}
String clusterIdentifier = target.resource().substring("cluster:".length());
if (clusterIdentifier.isBlank()) {
throw new AwsException("InvalidParameterValue", "TargetArn must identify a Redshift cluster.", 400);
}
describeClusters(clusterIdentifier);
if (description != null && description.length() > MAX_INTEGRATION_DESCRIPTION) {
throw new AwsException("InvalidParameterValue",
"Description must be at most " + MAX_INTEGRATION_DESCRIPTION + " characters.", 400);
@@ -334,11 +358,19 @@ public class RedshiftService {
String integrationId = UUID.randomUUID().toString();
Integration integration = new Integration();
integration.setAccountId(integrations.accountId());
integration.setIntegrationArn("arn:aws:redshift:" + region + ":" + regionResolver.getAccountId()
+ ":integration:" + integrationId);
integration.setIntegrationName(integrationName);
integration.setSourceArn(sourceArn);
integration.setTargetArn(targetArn);
integration.setSourceStreamArn(sourceArn);
integration.setTargetClusterIdentifier(clusterIdentifier);
integration.setLandingTableName("floci_zetl_" + integrationId.replace('-', '_'));
integration.setCheckpointSequenceNumber(null);
integration.setRetryCount(0);
integration.setLastError(null);
integration.setPollingEnabled(true);
// Real integrations pass through creating before settling; nothing here has work to do.
integration.setStatus("active");
integration.setKmsKeyId(kmsKeyId);
@@ -351,6 +383,14 @@ public class RedshiftService {
return integration;
}
private static AwsArnUtils.Arn parseZeroEtlArn(String arn, String resourceType) {
try {
return AwsArnUtils.parse(arn);
} catch (IllegalArgumentException e) {
throw new AwsException("InvalidParameterValue", resourceType + " ARN is invalid.", 400);
}
}
/**
* Lists integrations with the documented filters and marker pagination.
*
@@ -401,6 +441,45 @@ public class RedshiftService {
return new IntegrationPage(List.copyOf(page), next);
}
public List<Integration> listDynamoDbZeroEtlIntegrations() {
return integrations.scanAllAccountEntries(key -> true).stream()
.filter(entry -> entry.value().getSourceStreamArn() != null
&& !entry.value().getSourceStreamArn().isBlank())
.map(entry -> {
Integration integration = entry.value();
if (integration.getAccountId() == null) {
integration.setAccountId(entry.accountId());
}
return integration;
})
.toList();
}
public synchronized void updateIntegrationRuntime(String accountId, String integrationArn,
String checkpointSequenceNumber,
boolean successful, String error) {
for (String key : integrations.keysForAccount(accountId)) {
Optional<Integration> stored = integrations.getForAccount(accountId, key);
if (stored.isEmpty() || !integrationArn.equals(stored.get().getIntegrationArn())) {
continue;
}
Integration integration = stored.get();
if (successful) {
integration.setCheckpointSequenceNumber(checkpointSequenceNumber);
integration.setRetryCount(0);
integration.setLastError(null);
integration.setStatus("active");
} else {
integration.setRetryCount(integration.getRetryCount() + 1);
integration.setLastError(error);
integration.setStatus("failed");
}
integrations.putForAccount(accountId, key, integration);
return;
}
throw new AwsException("IntegrationNotFoundFault", "The requested integration doesn't exist.", 404);
}
/** One page of integrations plus the marker to continue with, or {@code null} at the end. */
public record IntegrationPage(List<Integration> integrations, String marker) {}
@@ -468,6 +547,17 @@ public class RedshiftService {
return clusters.scan(k -> true);
}
public List<Cluster> describeClustersForAccount(String accountId, String identifier) {
if (identifier != null) {
Optional<Cluster> cluster = clusters.getForAccount(accountId, identifier);
if (cluster.isEmpty()) {
throw new AwsException("ClusterNotFound", "Cluster " + identifier + " not found", 404);
}
return List.of(cluster.get());
}
return clusters.scanForAccount(accountId, k -> true);
}
public synchronized Cluster deleteCluster(String identifier) {
Optional<Cluster> clusterOpt = clusters.get(identifier);
if (clusterOpt.isEmpty()) {
@@ -16,9 +16,17 @@ import java.util.Map;
@RegisterForReflection
public class Integration {
private String integrationArn;
private String accountId;
private String integrationName;
private String sourceArn;
private String targetArn;
private String sourceStreamArn;
private String targetClusterIdentifier;
private String landingTableName;
private String checkpointSequenceNumber;
private int retryCount;
private String lastError;
private boolean pollingEnabled;
private String description;
private String status;
private String kmsKeyId;
@@ -31,12 +39,28 @@ public class Integration {
public String getIntegrationArn() { return integrationArn; }
public void setIntegrationArn(String integrationArn) { this.integrationArn = integrationArn; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public String getIntegrationName() { return integrationName; }
public void setIntegrationName(String integrationName) { this.integrationName = integrationName; }
public String getSourceArn() { return sourceArn; }
public void setSourceArn(String sourceArn) { this.sourceArn = sourceArn; }
public String getTargetArn() { return targetArn; }
public void setTargetArn(String targetArn) { this.targetArn = targetArn; }
public String getSourceStreamArn() { return sourceStreamArn; }
public void setSourceStreamArn(String sourceStreamArn) { this.sourceStreamArn = sourceStreamArn; }
public String getTargetClusterIdentifier() { return targetClusterIdentifier; }
public void setTargetClusterIdentifier(String targetClusterIdentifier) { this.targetClusterIdentifier = targetClusterIdentifier; }
public String getLandingTableName() { return landingTableName; }
public void setLandingTableName(String landingTableName) { this.landingTableName = landingTableName; }
public String getCheckpointSequenceNumber() { return checkpointSequenceNumber; }
public void setCheckpointSequenceNumber(String checkpointSequenceNumber) { this.checkpointSequenceNumber = checkpointSequenceNumber; }
public int getRetryCount() { return retryCount; }
public void setRetryCount(int retryCount) { this.retryCount = retryCount; }
public String getLastError() { return lastError; }
public void setLastError(String lastError) { this.lastError = lastError; }
public boolean isPollingEnabled() { return pollingEnabled; }
public void setPollingEnabled(boolean pollingEnabled) { this.pollingEnabled = pollingEnabled; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getStatus() { return status; }
@@ -0,0 +1,147 @@
package io.github.hectorvent.floci.services.redshiftdata;
import com.fasterxml.jackson.core.JsonProcessingException;
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.model.DynamoDbStreamRecord;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.time.Instant;
import java.util.List;
import java.util.regex.Pattern;
@ApplicationScoped
public class RedshiftZeroEtlWriter {
private static final Pattern TABLE_NAME = Pattern.compile("^[a-zA-Z_][a-zA-Z0-9_]*$");
private static final String LANDING_TABLE_DDL = "CREATE TABLE IF NOT EXISTS %s ("
+ "event_id TEXT PRIMARY KEY, "
+ "event_name TEXT NOT NULL, "
+ "event_source TEXT, "
+ "aws_region TEXT, "
+ "sequence_number TEXT NOT NULL, "
+ "approximate_creation_datetime TIMESTAMPTZ, "
+ "keys_json TEXT, "
+ "old_image_json TEXT, "
+ "new_image_json TEXT, "
+ "ingested_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP";
private static final String INSERT_RECORD = "INSERT INTO %s (event_id, event_name, event_source, aws_region, "
+ "sequence_number, approximate_creation_datetime, keys_json, old_image_json, new_image_json) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (event_id) DO NOTHING";
private final RedshiftService redshiftService;
private final RedshiftDataConnectionFactory connectionFactory;
private final ObjectMapper objectMapper;
@Inject
RedshiftZeroEtlWriter(RedshiftService redshiftService,
RedshiftDataConnectionFactory connectionFactory,
ObjectMapper objectMapper) {
this.redshiftService = redshiftService;
this.connectionFactory = connectionFactory;
this.objectMapper = objectMapper;
}
public void createLandingTable(String accountId, String clusterIdentifier, String tableName) {
String safeTableName = validateTableName(tableName);
try (Connection connection = connectionFactory.open(target(accountId, clusterIdentifier));
Statement statement = connection.createStatement()) {
statement.executeUpdate(LANDING_TABLE_DDL.formatted(safeTableName) + ")");
} catch (SQLException e) {
throw new AwsException("InternalFailure", "Could not create Redshift zero-ETL landing table.", 500);
}
}
public String writeBatch(String accountId, String clusterIdentifier, String tableName,
List<DynamoDbStreamRecord> records) {
if (records == null || records.isEmpty()) {
return null;
}
String safeTableName = validateTableName(tableName);
String newestSequence = null;
try (Connection connection = connectionFactory.open(target(accountId, clusterIdentifier));
PreparedStatement statement = connection.prepareStatement(INSERT_RECORD.formatted(safeTableName))) {
for (DynamoDbStreamRecord record : records) {
bind(statement, record);
statement.executeUpdate();
newestSequence = record.getSequenceNumber();
}
} catch (SQLException e) {
throw new AwsException("InternalFailure", "Could not write Redshift zero-ETL records.", 500);
}
return newestSequence;
}
private void bind(PreparedStatement statement, DynamoDbStreamRecord record) throws SQLException {
statement.setString(1, record.getEventId());
statement.setString(2, record.getEventName());
setNullableString(statement, 3, record.getEventSource());
setNullableString(statement, 4, record.getAwsRegion());
statement.setString(5, record.getSequenceNumber());
if (record.getApproximateCreationDateTime() > 0) {
statement.setObject(6, Instant.ofEpochSecond(record.getApproximateCreationDateTime()));
} else {
statement.setNull(6, Types.TIMESTAMP_WITH_TIMEZONE);
}
setJson(statement, 7, record.getKeys());
setJson(statement, 8, record.getOldImage());
setJson(statement, 9, record.getNewImage());
}
private void setNullableString(PreparedStatement statement, int index, String value) throws SQLException {
if (value == null) {
statement.setNull(index, Types.VARCHAR);
} else {
statement.setString(index, value);
}
}
private void setJson(PreparedStatement statement, int index, JsonNode value) throws SQLException {
if (value == null || value.isNull()) {
statement.setNull(index, Types.VARCHAR);
return;
}
try {
statement.setString(index, objectMapper.writeValueAsString(value));
} catch (JsonProcessingException e) {
throw new AwsException("InternalFailure", "Could not serialize a DynamoDB stream record.", 500);
}
}
private RedshiftDataResourceResolver.DatabaseTarget target(String accountId, String clusterIdentifier) {
Cluster cluster;
try {
cluster = redshiftService.describeClustersForAccount(accountId, clusterIdentifier).get(0);
} catch (RuntimeException e) {
throw new AwsException("ResourceNotFoundException",
"Redshift cluster " + clusterIdentifier + " was not found.", 404);
}
if (cluster.getContainerHost() == null || cluster.getContainerHost().isBlank()
|| cluster.getContainerPort() <= 0) {
throw new AwsException("InvalidClusterState", "Redshift cluster runtime is not available.", 400);
}
return new RedshiftDataResourceResolver.DatabaseTarget(
"cluster:" + clusterIdentifier,
cluster.getContainerHost(),
cluster.getContainerPort(),
"dev",
cluster.getMasterUsername(),
cluster.getMasterPassword());
}
private static String validateTableName(String tableName) {
if (tableName == null || !TABLE_NAME.matcher(tableName).matches()) {
throw new AwsException("InvalidParameterValue", "Landing table name is invalid.", 400);
}
return tableName;
}
}