feat(redshift): project DynamoDB zero-ETL changes into a current-state table (#8180)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-13 16:18:31 -04:00
1 parent 5c08fff5d7
commit eea61cd42a
12 files changed
+1469 -4

No files matched your search

@@ -17,6 +17,8 @@ import io.floci.aws.services.dynamodb.backend.DynamoDbStreamReader;
import io.floci.aws.services.dynamodb.model.KeySchemaElement;
import io.floci.aws.services.dynamodb.model.TableDefinition;
import io.floci.aws.services.redshift.model.Integration;
import io.floci.aws.services.redshiftdata.RedshiftZeroEtlCurrentState;
import io.floci.aws.services.redshiftdata.RedshiftZeroEtlCurrentState.Change;
import io.floci.aws.services.redshiftdata.RedshiftZeroEtlWriter;
import io.vertx.core.Vertx;
import jakarta.annotation.PreDestroy;
@@ -24,6 +26,8 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -32,6 +36,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
@ApplicationScoped
public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
@@ -50,6 +55,13 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
private final ConcurrentHashMap<String, Boolean> activePolls = new ConcurrentHashMap<>();
/** Per integration, the DynamoDB Stream shards read to their end. */
private final ConcurrentHashMap<String, Set<String>> finishedShards = new ConcurrentHashMap<>();
/** Per integration, the current-state table its source projects into, created on the target once resolved. */
private final ConcurrentHashMap<String, RedshiftZeroEtlCurrentState> currentStates = new ConcurrentHashMap<>();
/**
* The integrations whose current-state table could not be written. Their landing log carries on regardless;
* each poll tries to make the table again, and rebuilds it from a scan once that works.
*/
private final Set<String> stalledProjections = ConcurrentHashMap.newKeySet();
private final ExecutorService pollExecutor = Executors.newCachedThreadPool(runnable -> {
Thread thread = new Thread(runnable, "redshift-zero-etl");
thread.setDaemon(true);
@@ -106,6 +118,12 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
if (streamReader.checkpointLifetime() == DynamoDbStreamReader.CheckpointLifetime.PROCESS) {
integration.getShardSequenceNumbers().clear();
}
if (integration.isBackfillCompleted() && !integration.isCurrentStateProjected()) {
// An integration whose backfill ran before the current-state table existed scans its source
// again to fill it; the landing log keeps each event once, so the rerun adds no rows there.
integration.setBackfillCompleted(false);
integration.setBackfillLastEvaluatedKey(null);
}
if (integration.isPollingEnabled()) {
startPolling(integration);
}
@@ -127,6 +145,8 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
}
activePolls.remove(integrationArn);
finishedShards.remove(integrationArn);
currentStates.remove(integrationArn);
stalledProjections.remove(integrationArn);
}
void pollOnce(Integration integration) {
@@ -139,6 +159,9 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
}
writer.createLandingTable(integration.getAccountId(), integration.getTargetArn(),
integration.getLandingTableName());
if (stalledProjections.contains(integration.getIntegrationArn())) {
restoreProjection(integration);
}
if (!integration.isBackfillCompleted()) {
pollBackfillPage(integration);
return;
@@ -214,6 +237,8 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
}
integration.getShardSequenceNumbers().clear();
finishedShards.remove(integration.getIntegrationArn());
// A new stream may belong to a table made again with other keys, so its projection is resolved afresh.
currentStates.remove(integration.getIntegrationArn());
integration.setSourceStreamArn(latest);
redshiftService.updateIntegrationSourceStream(integration.getAccountId(), integration.getIntegrationArn(),
latest);
@@ -261,9 +286,10 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
}
return false;
}
List<JsonNode> awsRecords = records.stream().map(DynamoDbStreamReader.Record::awsRecord).toList();
writer.writeBatch(integration.getAccountId(), integration.getTargetArn(),
integration.getLandingTableName(),
records.stream().map(DynamoDbStreamReader.Record::awsRecord).toList());
integration.getLandingTableName(), awsRecords);
projectSafely(integration, null, () -> readThrough(integration, awsRecords));
committed.put(shardId, records.get(records.size() - 1).sequenceNumber());
redshiftService.updateIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn(),
committed, true, null);
@@ -279,6 +305,23 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
Scope scope = new Scope(integration.getAccountId(), region);
TableDefinition table = dynamoDb.tables().describeTable(scope, tableName);
JsonNode exclusiveStartKey = parseBackfillKey(integration.getBackfillLastEvaluatedKey());
// The current-state table exists from the first backfill page on, as AWS creates it before the
// initial export lands, so an empty source still shows as an empty table. Its first page empties it:
// the scan only upserts, so a row an earlier run left would otherwise outlive its item. A table that
// cannot be made stalls the projection alone; the scan still lands.
RedshiftZeroEtlCurrentState currentState = null;
if (!stalledProjections.contains(integration.getIntegrationArn())) {
try {
currentState = currentState(integration, table);
if (exclusiveStartKey == null) {
writer.resetCurrentStateTable(integration.getAccountId(), integration.getTargetArn(),
currentState);
}
} catch (RuntimeException e) {
stallProjection(integration, e);
currentState = null;
}
}
ScanPage result = dynamoDb.items().scan(scope, tableName, null, null, null, null,
BATCH_SIZE, exclusiveStartKey);
@@ -288,6 +331,9 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
.toList();
writer.writeBatch(integration.getAccountId(), integration.getTargetArn(),
integration.getLandingTableName(), records);
if (currentState != null) {
projectSafely(integration, currentState, () -> scannedItems(records));
}
}
boolean completed = result.lastEvaluatedKey() == null;
@@ -296,9 +342,166 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
nextKey, completed);
integration.setBackfillLastEvaluatedKey(nextKey);
integration.setBackfillCompleted(completed);
if (completed && !stalledProjections.contains(integration.getIntegrationArn())) {
integration.setCurrentStateProjected(true);
redshiftService.updateIntegrationCurrentState(integration.getAccountId(),
integration.getIntegrationArn(), true);
}
});
}
/**
* Applies the records to the current-state table without ever failing the poll: the records have landed, and a
* projection that cannot be written must not hold the landing log back. A failure stalls the projection, and
* {@link #restoreProjection} rebuilds the table from a scan once it can be written again.
*/
private void projectSafely(Integration integration, RedshiftZeroEtlCurrentState currentState,
Supplier<List<Change>> changes) {
if (stalledProjections.contains(integration.getIntegrationArn())) {
return;
}
try {
project(integration, currentState, changes.get());
} catch (RuntimeException e) {
stallProjection(integration, e);
}
}
private void stallProjection(Integration integration, RuntimeException cause) {
String integrationArn = integration.getIntegrationArn();
currentStates.remove(integrationArn);
if (stalledProjections.add(integrationArn)) {
LOG.warnv(cause, "The current-state table of zero-ETL integration {0} cannot be written; the landing "
+ "log carries on and the table is rebuilt once it can be", integrationArn);
}
integration.setCurrentStateProjected(false);
redshiftService.updateIntegrationCurrentState(integration.getAccountId(), integrationArn, false);
}
/**
* Tries to make the stalled integration's table again, the one thing that can have been wrong being the table:
* dropped, a user's own of that name, or the target unreachable. Changes landed since the stall never reached
* it, so once it is made the backfill starts over to rebuild it.
*/
private void restoreProjection(Integration integration) {
String integrationArn = integration.getIntegrationArn();
try {
TableDefinition table = describeSource(integration);
currentStates.remove(integrationArn);
currentState(integration, table);
} catch (RuntimeException e) {
LOG.debugv(e, "The current-state table of zero-ETL integration {0} still cannot be written",
integrationArn);
return;
}
stalledProjections.remove(integrationArn);
// Making the table afresh has already started the backfill over; otherwise it is past some pages, or done.
if (integration.isBackfillCompleted() || integration.getBackfillLastEvaluatedKey() != null) {
resyncProjection(integration);
}
}
/** Starts the backfill over so that the scan fills a current-state table that is missing items. */
private void resyncProjection(Integration integration) {
integration.setBackfillCompleted(false);
integration.setBackfillLastEvaluatedKey(null);
integration.setCurrentStateProjected(false);
redshiftService.updateIntegrationBackfillProgress(integration.getAccountId(), integration.getIntegrationArn(),
null, false);
redshiftService.updateIntegrationCurrentState(integration.getAccountId(), integration.getIntegrationArn(),
false);
}
private TableDefinition describeSource(Integration integration) {
String sourceArn = integration.getSourceArn() != null
? integration.getSourceArn() : integration.getSourceStreamArn();
String tableName = RedshiftZeroEtlEndpoints.tableName(sourceArn);
String region = AwsArnUtils.parse(sourceArn).region();
return RequestScopes.callAs(integration.getAccountId(), region,
() -> dynamoDb.tables().describeTable(new Scope(integration.getAccountId(), region), tableName));
}
/**
* The changes the stream records make: each key a record names, projected as the source holds it now, once
* however many records name it. A record's own image is not used, so replaying a record after the backfill
* scan read a newer version of its item, or after the item changed again, cannot put the older image over the
* newer one: every record of a key projects the same state, and the table follows the source as the stream
* drains. The scan reads each item it projects itself, so only the stream pays this lookup.
*/
private List<Change> readThrough(Integration integration, List<JsonNode> records) {
String sourceArn = integration.getSourceArn() != null
? integration.getSourceArn() : integration.getSourceStreamArn();
String tableName = RedshiftZeroEtlEndpoints.tableName(sourceArn);
String region = AwsArnUtils.parse(sourceArn).region();
Scope scope = new Scope(integration.getAccountId(), region);
Map<String, Change> changes = new LinkedHashMap<>();
for (JsonNode record : records) {
JsonNode keys = record.path("dynamodb").path("Keys");
if (!keys.isObject() || changes.containsKey(keys.toString())) {
continue;
}
Change change = RedshiftZeroEtlCurrentState.changeOf(record, lookedUp -> RequestScopes.callAs(
integration.getAccountId(), region, () -> dynamoDb.items().getItem(scope, tableName, lookedUp)));
if (change != null) {
changes.put(keys.toString(), change);
}
}
return new ArrayList<>(changes.values());
}
/** The changes a backfill page makes: each item the scan read, upserted under its keys. */
private static List<Change> scannedItems(List<JsonNode> backfillRecords) {
List<Change> changes = new ArrayList<>();
for (JsonNode record : backfillRecords) {
JsonNode dynamodb = record.path("dynamodb");
changes.add(new Change(dynamodb.get("Keys"), dynamodb.get("NewImage")));
}
return changes;
}
/**
* Applies the changes to the current-state table, after the records they come from have landed. The projection
* is idempotent, so an item projected twice, once by the backfill scan and once from the stream, or a batch
* applied again after a stalled poll, leaves the same state.
*
* @param currentState the table resolved by the caller, or null to resolve it from the source table
*/
private void project(Integration integration, RedshiftZeroEtlCurrentState currentState, List<Change> changes) {
if (changes.isEmpty()) {
return;
}
RedshiftZeroEtlCurrentState state = currentState != null
? currentState : currentStates.get(integration.getIntegrationArn());
if (state == null) {
state = currentState(integration, describeSource(integration));
}
writer.applyChanges(integration.getAccountId(), integration.getTargetArn(), state, changes);
}
/**
* The integration's current-state table, made its own on the target the first time it is resolved. A table made
* afresh over a running integration (dropped by a user, or the source made again with other keys) holds none of
* the source's items, so the backfill starts over to fill it.
*/
private RedshiftZeroEtlCurrentState currentState(Integration integration, TableDefinition table) {
boolean[] fresh = new boolean[1];
RedshiftZeroEtlCurrentState state = currentStates.computeIfAbsent(integration.getIntegrationArn(), ignored -> {
RedshiftZeroEtlCurrentState created = RedshiftZeroEtlCurrentState.of(table);
fresh[0] = writer.createCurrentStateTable(integration.getAccountId(), integration.getTargetArn(), created,
integrationId(integration));
return created;
});
if (fresh[0] && integration.isBackfillCompleted()) {
resyncProjection(integration);
}
return state;
}
private static String integrationId(Integration integration) {
String arn = integration.getIntegrationArn();
return arn.substring(arn.lastIndexOf(':') + 1);
}
/** The item as an AWS stream {@code INSERT} record, with an event id stable across scans. */
private JsonNode toBackfillRecord(Integration integration, JsonNode item, TableDefinition table) {
ObjectNode keys = objectMapper.createObjectNode();
@@ -359,6 +562,8 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
}
activePolls.clear();
finishedShards.clear();
currentStates.clear();
stalledProjections.clear();
}
/** Lets the polls submitted from now on write again. */
@@ -883,6 +883,11 @@ public class RedshiftService implements ManagedSecretRotator {
.toList();
}
/** Whether {@code accountId} holds the integration, which is gone once it is deleted. */
public boolean integrationExists(String accountId, String integrationId) {
return integrations.getForAccount(accountId, integrationId).isPresent();
}
public List<Integration> listS3AutoCopyIntegrations() {
return integrations.scanAllAccountEntries(key -> true).stream()
.filter(entry -> S3_EVENT_SOURCE_TYPE.equals(entry.value().getSourceType()))
@@ -944,6 +949,27 @@ public class RedshiftService implements ManagedSecretRotator {
throw new AwsException("IntegrationNotFoundFault", "The requested integration doesn't exist.", 404);
}
/**
* Records whether the integration's current-state table holds its source's items: true once a backfill has
* filled it, false while it is being rebuilt. It is not an integration state, so no event is sent.
*/
public synchronized void updateIntegrationCurrentState(String accountId, String integrationArn,
boolean projected) {
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 (integration.isCurrentStateProjected() != projected) {
integration.setCurrentStateProjected(projected);
integrations.putForAccount(accountId, key, integration);
}
return;
}
throw new AwsException("IntegrationNotFoundFault", "The requested integration doesn't exist.", 404);
}
/** Records that the integration now reads {@code sourceStreamArn}, from its trim horizon. */
public synchronized void updateIntegrationSourceStream(String accountId, String integrationArn,
String sourceStreamArn) {
@@ -34,6 +34,11 @@ public class Integration {
private Map<String, String> shardSequenceNumbers = new ConcurrentHashMap<>();
private String backfillLastEvaluatedKey;
private boolean backfillCompleted;
/**
* Whether a backfill has filled the current-state table. False on an integration persisted before that table
* existed, which scans its source again at startup.
*/
private boolean currentStateProjected;
private int retryCount;
private String lastError;
private boolean pollingEnabled;
@@ -72,6 +77,8 @@ public class Integration {
public void setBackfillLastEvaluatedKey(String backfillLastEvaluatedKey) { this.backfillLastEvaluatedKey = backfillLastEvaluatedKey; }
public boolean isBackfillCompleted() { return backfillCompleted; }
public void setBackfillCompleted(boolean backfillCompleted) { this.backfillCompleted = backfillCompleted; }
public boolean isCurrentStateProjected() { return currentStateProjected; }
public void setCurrentStateProjected(boolean currentStateProjected) { this.currentStateProjected = currentStateProjected; }
public int getRetryCount() { return retryCount; }
public void setRetryCount(int retryCount) { this.retryCount = retryCount; }
public String getLastError() { return lastError; }
@@ -0,0 +1,210 @@
package io.floci.aws.services.redshiftdata;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.dynamodb.model.AttributeDefinition;
import io.floci.aws.services.dynamodb.model.KeySchemaElement;
import io.floci.aws.services.dynamodb.model.TableDefinition;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* The table a DynamoDB zero-ETL integration projects its source's current item state into, shaped as AWS shapes
* it: in the target's {@code public} schema under the DynamoDB table's name, one column per key attribute and a
* {@code value} column holding the whole item in DynamoDB JSON. AWS types {@code value} as SUPER; the PostgreSQL
* data plane holds it as {@code jsonb}, so {@code value->'payload'->'L'->0->>'S'} reads what
* {@code "value"."payload"."L"[0]."S"} reads on Redshift.
*
* <p>Key columns take the DynamoDB key types: a string is {@code TEXT}, a number an unbounded {@code NUMERIC},
* which holds every DynamoDB number exactly where AWS's {@code NUMERIC(38,18)} would round or overflow, and binary
* {@code BYTEA}. Every other attribute lives in {@code value} alone, so items that differ in shape need no schema
* change.
*/
public final class RedshiftZeroEtlCurrentState {
/**
* The longest identifier PostgreSQL keeps whole. AWS replicates names up to 127 characters, but a longer name
* would be truncated here, and two names sharing their first 63 bytes would silently share a table.
*/
static final int MAX_IDENTIFIER_BYTES = 63;
static final String VALUE_COLUMN = "value";
/** One projected change: the item to upsert under its keys, or, with a null item, the keys to delete. */
public record Change(JsonNode keys, JsonNode item) {
public boolean isDelete() {
return item == null;
}
}
record KeyColumn(String name, String dynamoDbType) {}
private final String tableName;
private final List<KeyColumn> keyColumns;
RedshiftZeroEtlCurrentState(String tableName, List<KeyColumn> keyColumns) {
this.tableName = tableName;
this.keyColumns = List.copyOf(keyColumns);
}
/** The projection of a DynamoDB table, its partition key column before its sort key's. */
public static RedshiftZeroEtlCurrentState of(TableDefinition table) {
String tableName = table.getTableName();
if (tableName == null || tableName.isBlank() || tooLong(tableName)) {
throw new AwsException("InvalidParameterValue", "Table names from DynamoDB longer than "
+ MAX_IDENTIFIER_BYTES + " bytes, the PostgreSQL identifier limit, are not supported.", 400);
}
List<KeyColumn> columns = new ArrayList<>();
for (String keyType : List.of("HASH", "RANGE")) {
for (KeySchemaElement element : table.getKeySchema()) {
if (keyType.equals(element.getKeyType())) {
columns.add(new KeyColumn(element.getAttributeName(), attributeType(table, element.getAttributeName())));
}
}
}
if (columns.isEmpty()) {
throw new AwsException("InternalFailure", "DynamoDB table " + tableName + " has no key schema.", 500);
}
for (KeyColumn column : columns) {
if (tooLong(column.name())) {
throw new AwsException("InvalidParameterValue", "Column names for the partition key or sort key "
+ "longer than " + MAX_IDENTIFIER_BYTES + " bytes, the PostgreSQL identifier limit, are not "
+ "supported.", 400);
}
if (VALUE_COLUMN.equals(column.name())) {
throw new AwsException("InvalidParameterValue",
"A key attribute named " + VALUE_COLUMN + " collides with the replicated item column.", 400);
}
}
return new RedshiftZeroEtlCurrentState(tableName, columns);
}
private static boolean tooLong(String identifier) {
return identifier.getBytes(StandardCharsets.UTF_8).length > MAX_IDENTIFIER_BYTES;
}
private static String attributeType(TableDefinition table, String attributeName) {
for (AttributeDefinition definition : table.getAttributeDefinitions()) {
if (attributeName.equals(definition.getAttributeName())) {
return definition.getAttributeType();
}
}
throw new AwsException("InternalFailure",
"DynamoDB table " + table.getTableName() + " defines no type for key attribute " + attributeName + ".", 500);
}
public String tableName() {
return tableName;
}
List<String> keyColumnNames() {
return keyColumns.stream().map(KeyColumn::name).toList();
}
/**
* The columns a table of this name must have for the integration to write it, the keys then {@code value}, with
* the type each has as {@code information_schema.columns.data_type} names it.
*/
Map<String, String> expectedColumnTypes() {
Map<String, String> columns = new LinkedHashMap<>();
for (KeyColumn column : keyColumns) {
columns.put(column.name(), sqlType(column).toLowerCase(Locale.ROOT));
}
columns.put(VALUE_COLUMN, "jsonb");
return columns;
}
/** Empties the table, for an integration starting its backfill over a table a previous one left behind. */
String resetSql() {
return "TRUNCATE TABLE " + qualifiedName();
}
/**
* The change a stream record makes to the current state: the record names a key, and the key is projected as
* the source holds it now, read through {@code lookup}. The item is upserted, or deleted when the source no
* longer has it. The record's own images are not used: a record replayed after the backfill scan read a newer
* version of its item, or after the item changed again, would otherwise put its older image over the newer one
* until the later record was replayed. Read as it is now, every record of a key projects the same state, so
* replay order cannot regress a row. A record without keys projects nothing.
*/
public static Change changeOf(JsonNode record, Function<JsonNode, JsonNode> lookup) {
JsonNode keys = record.path("dynamodb").get("Keys");
if (keys == null || !keys.isObject() || keys.isEmpty()) {
return null;
}
JsonNode current = lookup.apply(keys);
return new Change(keys, current != null && current.isObject() ? current : null);
}
String ddl() {
String columns = keyColumns.stream()
.map(column -> quote(column.name()) + " " + sqlType(column) + " NOT NULL")
.collect(Collectors.joining(", "));
String primaryKey = keyColumns.stream().map(column -> quote(column.name())).collect(Collectors.joining(", "));
return "CREATE TABLE IF NOT EXISTS " + qualifiedName() + " (" + columns + ", "
+ quote(VALUE_COLUMN) + " JSONB NOT NULL, PRIMARY KEY (" + primaryKey + "))";
}
String upsertSql() {
String names = keyColumns.stream().map(column -> quote(column.name())).collect(Collectors.joining(", "));
String placeholders = keyColumns.stream().map(column -> "?").collect(Collectors.joining(", "));
return "INSERT INTO " + qualifiedName() + " (" + names + ", " + quote(VALUE_COLUMN) + ") VALUES ("
+ placeholders + ", ?::jsonb) ON CONFLICT (" + names + ") DO UPDATE SET "
+ quote(VALUE_COLUMN) + " = EXCLUDED." + quote(VALUE_COLUMN);
}
String deleteSql() {
return "DELETE FROM " + qualifiedName() + " WHERE " + keyColumns.stream()
.map(column -> quote(column.name()) + " = ?").collect(Collectors.joining(" AND "));
}
/** The {@code value} parameter of {@link #upsertSql()}, after the key parameters. */
int valueParameterIndex() {
return keyColumns.size() + 1;
}
/** Binds the record's key attributes as the statement's first parameters, in key column order. */
void bindKeys(PreparedStatement statement, JsonNode keys) throws SQLException {
int index = 1;
for (KeyColumn column : keyColumns) {
JsonNode attribute = keys.get(column.name());
JsonNode typed = attribute == null ? null : attribute.get(column.dynamoDbType());
if (typed == null || typed.isNull()) {
throw new AwsException("InternalFailure", "A DynamoDB stream record of " + tableName
+ " carries no " + column.dynamoDbType() + " value for key attribute " + column.name() + ".", 500);
}
switch (column.dynamoDbType()) {
case "N" -> statement.setBigDecimal(index, new BigDecimal(typed.asText()));
case "B" -> statement.setBytes(index, Base64.getDecoder().decode(typed.asText()));
default -> statement.setString(index, typed.asText());
}
index++;
}
}
String qualifiedName() {
return "public." + quote(tableName);
}
private static String sqlType(KeyColumn column) {
return switch (column.dynamoDbType()) {
case "N" -> "NUMERIC";
case "B" -> "BYTEA";
default -> "TEXT";
};
}
private static String quote(String identifier) {
return "\"" + identifier.replace("\"", "\"\"") + "\"";
}
}
@@ -11,16 +11,20 @@ import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
@ApplicationScoped
@@ -41,6 +45,14 @@ public class RedshiftZeroEtlWriter {
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 static final String COLUMNS_OF_TABLE = "SELECT column_name, data_type FROM information_schema.columns "
+ "WHERE table_schema = 'public' AND table_name = ?";
/** Whether a table exists, and the comment it carries: the mark of the integration that made it. */
private static final String TABLE_OWNER = "SELECT to_regclass(?) IS NOT NULL, "
+ "obj_description(to_regclass(?), 'pg_class')";
private static final String OWNER_MARKER_PREFIX = "floci-zetl-integration:";
private static final Pattern INTEGRATION_ID = Pattern.compile("[A-Za-z0-9-]{1,64}");
private static final Logger LOG = Logger.getLogger(RedshiftZeroEtlWriter.class);
private final RedshiftService redshiftService;
private final RedshiftZeroEtlEndpoints endpoints;
@@ -69,6 +81,152 @@ public class RedshiftZeroEtlWriter {
}
}
/**
* Makes the table the integration projects its source's current item state into its own: the table carries a
* comment naming the integration, so a later run knows whose it is.
*
* <ul>
* <li>No such table: it is created and marked.</li>
* <li>A table this integration marked, with the columns its source's keys give: it is kept.</li>
* <li>A table an earlier integration marked, that no longer exists, or this one's with other columns or column
* types (the source was made again with other keys): it is dropped and created afresh, since its rows
* describe a source that no longer exists.</li>
* <li>A table nobody marked, a user's own, or one that a live integration marked (two sources sharing a table
* name, such as the same name in two Regions): it is refused with {@code InvalidParameterValue} and left
* alone.</li>
* </ul>
*
* @param integrationId the id of the integration that owns the table, the last segment of its ARN
* @return whether the table was made afresh, so that it holds none of its source's items yet
*/
public boolean createCurrentStateTable(String accountId, String targetArn, RedshiftZeroEtlCurrentState state,
String integrationId) {
String marker = ownerMarker(integrationId);
try (Connection connection = connectionFactory.open(target(accountId, targetArn))) {
connection.setAutoCommit(false);
try {
boolean exists;
String owner;
try (PreparedStatement statement = connection.prepareStatement(TABLE_OWNER)) {
statement.setString(1, state.qualifiedName());
statement.setString(2, state.qualifiedName());
try (ResultSet rows = statement.executeQuery()) {
rows.next();
exists = rows.getBoolean(1);
owner = rows.getString(2);
}
}
boolean fresh = true;
if (exists) {
if (owner == null || !owner.startsWith(OWNER_MARKER_PREFIX)) {
throw new AwsException("InvalidParameterValue", "Table " + state.qualifiedName()
+ " already exists and was not created by a zero-ETL integration, so integration "
+ integrationId + " will not write into it.", 400);
}
String markedBy = owner.substring(OWNER_MARKER_PREFIX.length());
if (!markedBy.equals(integrationId) && redshiftService.integrationExists(accountId, markedBy)) {
throw new AwsException("InvalidParameterValue", "Table " + state.qualifiedName()
+ " is in use by zero-ETL integration " + markedBy + ", so integration "
+ integrationId + " will not write into it.", 400);
}
fresh = !owner.equals(marker) || !hasColumns(connection, state);
}
if (fresh) {
try (Statement statement = connection.createStatement()) {
if (exists) {
statement.executeUpdate("DROP TABLE " + state.qualifiedName());
}
statement.executeUpdate(state.ddl());
statement.executeUpdate("COMMENT ON TABLE " + state.qualifiedName() + " IS '" + marker + "'");
}
}
connection.commit();
return fresh;
} catch (SQLException | RuntimeException e) {
connection.rollback();
throw e;
}
} catch (SQLException e) {
LOG.warnv(e, "Could not create Redshift zero-ETL table {0}", state.qualifiedName());
throw new AwsException("InternalFailure", "Could not create Redshift zero-ETL table "
+ state.qualifiedName() + ": " + e.getMessage(), 500);
}
}
private static String ownerMarker(String integrationId) {
if (integrationId == null || !INTEGRATION_ID.matcher(integrationId).matches()) {
throw new AwsException("InvalidParameterValue", "Integration id is invalid.", 400);
}
return OWNER_MARKER_PREFIX + integrationId;
}
/**
* Whether the table has exactly the columns the source's keys give, with their types: a source made again with
* the same key name under another type would otherwise keep a column its keys can no longer be bound to.
*/
private static boolean hasColumns(Connection connection, RedshiftZeroEtlCurrentState state) throws SQLException {
Map<String, String> columns = new HashMap<>();
try (PreparedStatement statement = connection.prepareStatement(COLUMNS_OF_TABLE)) {
statement.setString(1, state.tableName());
try (ResultSet rows = statement.executeQuery()) {
while (rows.next()) {
columns.put(rows.getString(1), rows.getString(2));
}
}
}
return columns.equals(state.expectedColumnTypes());
}
/** Empties the current-state table, for an integration starting its backfill over a table left behind. */
public void resetCurrentStateTable(String accountId, String targetArn, RedshiftZeroEtlCurrentState state) {
try (Connection connection = connectionFactory.open(target(accountId, targetArn));
Statement statement = connection.createStatement()) {
statement.executeUpdate(state.resetSql());
} catch (SQLException e) {
LOG.warnv(e, "Could not empty Redshift zero-ETL table {0}", state.qualifiedName());
throw new AwsException("InternalFailure", "Could not empty Redshift zero-ETL table "
+ state.qualifiedName() + ": " + e.getMessage(), 500);
}
}
/**
* Applies the changes to the current-state table in order, in one transaction: an upsert replaces the item
* under its keys and a delete removes it. Both are idempotent, so a batch written again after a failure
* leaves the same state.
*/
public void applyChanges(String accountId, String targetArn, RedshiftZeroEtlCurrentState state,
List<RedshiftZeroEtlCurrentState.Change> changes) {
if (changes == null || changes.isEmpty()) {
return;
}
try (Connection connection = connectionFactory.open(target(accountId, targetArn))) {
connection.setAutoCommit(false);
try (PreparedStatement upsert = connection.prepareStatement(state.upsertSql());
PreparedStatement delete = connection.prepareStatement(state.deleteSql())) {
for (RedshiftZeroEtlCurrentState.Change change : changes) {
if (change.isDelete()) {
state.bindKeys(delete, change.keys());
delete.executeUpdate();
} else {
state.bindKeys(upsert, change.keys());
upsert.setString(state.valueParameterIndex(), objectMapper.writeValueAsString(change.item()));
upsert.executeUpdate();
}
}
connection.commit();
} catch (SQLException | JsonProcessingException | RuntimeException e) {
connection.rollback();
throw e;
}
} catch (SQLException e) {
LOG.warnv(e, "Could not apply Redshift zero-ETL changes to {0}", state.qualifiedName());
throw new AwsException("InternalFailure", "Could not apply Redshift zero-ETL changes to "
+ state.qualifiedName() + ": " + e.getMessage(), 500);
} catch (JsonProcessingException e) {
throw new AwsException("InternalFailure", "Could not serialize a DynamoDB item.", 500);
}
}
/** Writes AWS DynamoDB Streams {@code Records[]} elements, skipping event ids already landed. */
public void writeBatch(String accountId, String targetArn, String tableName, List<JsonNode> records) {
if (records == null || records.isEmpty()) {