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

+1 -1
View File
@@ -140,7 +140,7 @@ DynamoDB Streams are supported via a separate target (`DynamoDBStreams_20120810`
Redshift zero-ETL integrations can consume these stream records directly. See the
[Redshift DynamoDB zero-ETL](redshift.md#dynamodb-zero-etl) section for the supported sources and targets,
landing table, checkpoint, and retry behavior.
landing table, current-state table, checkpoint, and retry behavior.
Stream records are held in memory. `POST /_floci/state/reset` removes every stream along with the
tables, so `ListStreams` and `DescribeStream` no longer return the streams of tables created before
+47 -1
View File
@@ -478,6 +478,52 @@ approximation to indicate that initial backfill is in progress); it becomes `act
exhausted. The landing table is an append-only log, so an item changed while its table is still being
backfilled can appear twice: once from the scan and once from the stream.
#### Current-state table
Beside the landing log, the integration projects the source table's current item state into a table
shaped as AWS shapes it: in the target database's `public` schema, under the DynamoDB table's name,
with one column per key attribute and a `value` column holding the whole item in DynamoDB JSON. AWS
types `value` as SUPER. Floci's data plane is PostgreSQL, so `value` is `jsonb` and a path is read with
the JSON operators: `value->'payload'->'L'->0->>'S'` here is `"value"."payload"."L"[0]."S"` on Redshift.
```sql
SELECT id, value->'note'->>'S' AS note FROM public."orders";
```
- Key columns take the DynamoDB key types: `S` is `TEXT`, `N` is an unbounded `NUMERIC`, which holds
every DynamoDB number exactly where AWS's `NUMERIC(38,18)` would round or overflow, `B` is `BYTEA`. The
partition key comes first, then the sort key, and together they are the primary key. Every other
attribute lives only in `value`, so items of differing shape need no schema change.
- The backfill scan upserts each item it reads. A stream record names a key, and the key is projected as
the source holds it at that moment: the item is upserted, or deleted when the source no longer has it.
The record's own images, and its event type, are not used, so a record replayed after the scan read a
newer version of its item, or after the item changed again, cannot put an older image over the newer
row: every record of a key projects the same state, and a batch projects each key once. The cost is one
`GetItem` per key per batch, and the table shows each key's latest state, not every intermediate one,
as AWS's incremental exports do. AWS refreshes every 15 to 30 minutes; Floci applies each poll.
- Changes are applied after the batch has landed, in one transaction. The projection is idempotent, so an
item projected twice, once from the scan and once from the stream, leaves the same state.
- The integration marks its table as its own, with a comment naming the integration
(`floci-zetl-integration:<integration-id>`, see `obj_description`). A table that an earlier integration
of the source marked is dropped and made afresh by the next one, so an item deleted from the source in
between does not survive and a source made again with other keys, or the same key name under another
type, does not meet its predecessor's columns. A table nobody marked, one the user already has under that
name, is refused and left alone, and so is one that another integration still running marked (two
sources sharing a table name, such as the same name in two Regions, cannot share one target table).
- The current-state table never holds back the landing log. A projection that cannot be written (a
refused table, a table dropped under the integration, an unreachable target) is logged as a warning
once, and the integration keeps landing and checkpointing its records. Each poll tries to make the table
again, and once it can, the backfill starts over (`syncing`) and the scan fills it, since changes that
landed in the meantime never reached it. A table dropped and made again while the integration runs is
filled the same way.
- A table name or key column name longer than 63 bytes is refused. AWS accepts up to 127 characters, but
PostgreSQL truncates identifiers past 63 bytes, so two longer names could silently share a table.
- The table lives in the same database as the user's own tables (`dev` on a cluster, the namespace's
database on Serverless), not in a database created from the integration, and is kept when the
integration is deleted, as AWS keeps replicated data.
- An integration persisted before this table existed scans its source again at the next start to fill
it; the landing log keeps each event once, so the rerun adds no rows there.
### S3 event integrations
`CreateIntegration` also takes an Amazon S3 bucket as the source (`arn:aws:s3:::<bucket>`), the first step of
@@ -557,7 +603,7 @@ data-type, pause and resume, serverless restore and modification events do not o
is best effort. It is skipped when the EventBridge service is disabled, a refused or failed
delivery is logged, and neither changes the outcome of the Redshift operation.
Schema inference, relational projection and `CREATE DATABASE ... FROM INTEGRATION` are not
`CREATE DATABASE ... FROM INTEGRATION`, history mode and `SVV_INTEGRATION*` views are not
supported, and a provisioned cluster's namespace ARN (`arn:aws:redshift:<region>:<account>:namespace:<id>`)
is not accepted as a target.
@@ -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()) {
@@ -46,6 +46,7 @@ public final class RecordingDynamoDbBackend implements DynamoDbItemAccess, Dynam
table.setTableName(TABLE_NAME);
table.setTableArn(TABLE_ARN);
table.setKeySchema(List.of(new KeySchemaElement("id", "HASH")));
table.setAttributeDefinitions(List.of(new AttributeDefinition("id", "S")));
return table;
}
@@ -19,6 +19,8 @@ import io.floci.aws.services.dynamodb.model.KeySchemaElement;
import io.floci.aws.services.dynamodb.model.TableDefinition;
import io.floci.aws.services.redshift.model.Cluster;
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.floci.aws.testing.ThreadStates;
import io.quarkus.test.junit.QuarkusTest;
@@ -27,6 +29,7 @@ import io.vertx.core.Vertx;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.time.Duration;
import java.util.ArrayList;
@@ -50,7 +53,9 @@ import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -605,6 +610,13 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
assertEquals("backfill", written.path("dynamodb").path("SequenceNumber").asText());
assertEquals(written.path("dynamodb").path("Keys").path("id"),
written.path("dynamodb").path("NewImage").path("id"));
consumer.pollOnce(integration);
// Only the first page empties the current-state table; the second continues the same backfill.
assertTrue(integration.isBackfillCompleted());
verify(writer, times(1)).resetCurrentStateTable(any(), any(), any());
verify(writer, times(2)).applyChanges(any(), any(), any(), any());
}
@Test
@@ -815,6 +827,286 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
List.of(first.awsRecord()));
}
@Test
void projectsStreamRecordsIntoTheCurrentStateTableAfterTheyLand() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
String tableName = "orders-projected-" + System.nanoTime();
TableDefinition table = createTableAs("111111111111", tableName, true);
Integration integration = tableSourceIntegration(table);
integration.setBackfillCompleted(true);
// Key 1 is in the source and key 2 was deleted from it; each is named by an insert and a remove.
ObjectNode held = itemWithId("1");
held.putObject("note").put("S", "held");
RequestScopes.runAs("111111111111", () -> dynamoDbService.putItem(tableName, held, "us-east-1"));
DynamoDbStreamReader.Record inserted = imageRecord("s1", "INSERT", "1", "first");
DynamoDbStreamReader.Record removed = keysOnlyRecord("s2", "REMOVE", "2");
streams.shard(table.getStreamArn(), SHARD_ID, null).addAll(List.of(inserted, removed));
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer).pollOnce(integration);
ArgumentCaptor<RedshiftZeroEtlCurrentState> state = ArgumentCaptor.forClass(RedshiftZeroEtlCurrentState.class);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Change>> changes = ArgumentCaptor.forClass(List.class);
InOrder inOrder = inOrder(writer);
inOrder.verify(writer).writeBatch(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders",
List.of(inserted.awsRecord(), removed.awsRecord()));
inOrder.verify(writer).createCurrentStateTable(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), state.capture(),
eq("one"));
inOrder.verify(writer).applyChanges(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), eq(state.getValue()),
changes.capture());
assertEquals(tableName, state.getValue().tableName());
assertEquals(List.of(new Change(inserted.awsRecord().path("dynamodb").path("Keys"), held),
new Change(removed.awsRecord().path("dynamodb").path("Keys"), null)), changes.getValue());
assertEquals(Map.of(SHARD_ID, "s2"), integration.getShardSequenceNumbers());
}
/**
* The scan read version three of an item while the stream still holds the MODIFY records that led to it. They
* are replayed after the scan, carrying older images, and must not put those over the newer row.
*/
@Test
void replayedRecordsOfAnItemTheScanReadNewerNeverRegressItsRow() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
String tableName = "orders-replayed-" + System.nanoTime();
TableDefinition table = createTableAs("111111111111", tableName, true);
ObjectNode versionThree = itemWithId("1");
versionThree.putObject("note").put("S", "version three");
RequestScopes.runAs("111111111111", () -> dynamoDbService.putItem(tableName, versionThree, "us-east-1"));
Integration integration = tableSourceIntegration(table);
integration.setBackfillCompleted(true);
DynamoDbStreamReader.Record versionTwo = imageRecord("s1", "MODIFY", "1", "version two");
DynamoDbStreamReader.Record versionThreeRecord = imageRecord("s2", "MODIFY", "1", "version three");
streams.shard(table.getStreamArn(), SHARD_ID, null).addAll(List.of(versionTwo));
RedshiftDynamoDbZeroEtlConsumer consumer = new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb,
mock(RedshiftService.class), writer);
consumer.pollOnce(integration);
streams.shard(table.getStreamArn(), SHARD_ID, null).add(versionThreeRecord);
consumer.pollOnce(integration);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Change>> changes = ArgumentCaptor.forClass(List.class);
verify(writer, times(2)).applyChanges(any(), any(), any(), changes.capture());
// Across polls, the older record's poll and the newer one's both leave version three in the row.
for (List<Change> applied : changes.getAllValues()) {
assertEquals(1, applied.size());
assertEquals(versionThree, applied.get(0).item());
}
}
@Test
void manyRecordsOfOneKeyProjectItOnce() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
String tableName = "orders-chatty-" + System.nanoTime();
TableDefinition table = createTableAs("111111111111", tableName, true);
Integration integration = tableSourceIntegration(table);
integration.setBackfillCompleted(true);
streams.shard(table.getStreamArn(), SHARD_ID, null).addAll(List.of(
imageRecord("s1", "INSERT", "1", "a"), imageRecord("s2", "MODIFY", "1", "b"),
keysOnlyRecord("s3", "REMOVE", "1")));
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, mock(RedshiftService.class), writer)
.pollOnce(integration);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Change>> changes = ArgumentCaptor.forClass(List.class);
verify(writer).applyChanges(any(), any(), any(), changes.capture());
assertEquals(1, changes.getValue().size());
assertTrue(changes.getValue().get(0).isDelete());
}
@Test
void aRecordWithoutANewImageIsProjectedFromTheSourceItem() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
String tableName = "orders-keys-only-" + System.nanoTime();
TableDefinition table = createTableAs("111111111111", tableName, true);
ObjectNode item = itemWithId("1");
item.putObject("note").put("S", "as it is now");
RequestScopes.runAs("111111111111", () -> dynamoDbService.putItem(tableName, item, "us-east-1"));
Integration integration = tableSourceIntegration(table);
integration.setBackfillCompleted(true);
streams.shard(table.getStreamArn(), SHARD_ID, null).addAll(List.of(
keysOnlyRecord("s1", "MODIFY", "1"), keysOnlyRecord("s2", "MODIFY", "gone")));
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, mock(RedshiftService.class), writer)
.pollOnce(integration);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Change>> changes = ArgumentCaptor.forClass(List.class);
verify(writer).applyChanges(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), any(), changes.capture());
assertEquals(item, changes.getValue().get(0).item());
assertTrue(changes.getValue().get(1).isDelete());
}
@Test
void aFailedProjectionDoesNotHoldBackTheLandingLogAndTheTableIsRebuiltOnceItCanBeWritten() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
doThrow(new AwsException("InternalFailure", "Could not apply Redshift zero-ETL changes to orders.", 500))
.when(writer).applyChanges(any(), any(), any(), any());
String tableName = "orders-retried-" + System.nanoTime();
TableDefinition table = createTableAs("111111111111", tableName, true);
Integration integration = tableSourceIntegration(table);
integration.setBackfillCompleted(true);
integration.setCurrentStateProjected(true);
DynamoDbStreamReader.Record first = imageRecord("s1", "INSERT", "1", "first");
DynamoDbStreamReader.Record second = imageRecord("s2", "INSERT", "2", "second");
streams.shard(table.getStreamArn(), SHARD_ID, null).add(first);
RedshiftDynamoDbZeroEtlConsumer consumer =
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer);
consumer.pollOnce(integration);
// The record landed and its checkpoint advanced; only the projection stalled.
verify(writer).writeBatch(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders",
List.of(first.awsRecord()));
assertEquals(Map.of(SHARD_ID, "s1"), integration.getShardSequenceNumbers());
assertFalse(integration.isCurrentStateProjected());
verify(redshiftService).updateIntegrationCurrentState(integration.getAccountId(),
integration.getIntegrationArn(), false);
// While the table cannot be written, later batches still land and none is projected.
doThrow(new AwsException("InvalidParameterValue", "Table public.\"x\" is not ours.", 400))
.when(writer).createCurrentStateTable(any(), any(), any(), any());
streams.shard(table.getStreamArn(), SHARD_ID, null).add(second);
consumer.pollOnce(integration);
verify(writer).writeBatch(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders",
List.of(second.awsRecord()));
assertEquals(Map.of(SHARD_ID, "s2"), integration.getShardSequenceNumbers());
verify(writer, times(1)).applyChanges(any(), any(), any(), any());
assertTrue(integration.isBackfillCompleted());
// Once the table can be made, the backfill starts over to fill it, and a scan that completes marks it so.
doReturn(true).when(writer).createCurrentStateTable(any(), any(), any(), any());
consumer.pollOnce(integration);
assertTrue(integration.isBackfillCompleted());
assertTrue(integration.isCurrentStateProjected());
verify(redshiftService, times(1)).updateIntegrationBackfillProgress(integration.getAccountId(),
integration.getIntegrationArn(), null, false);
verify(redshiftService).updateIntegrationCurrentState(integration.getAccountId(),
integration.getIntegrationArn(), true);
verify(writer, times(1)).resetCurrentStateTable(any(), any(), any());
}
@Test
void aTableTheIntegrationCannotMakeStallsTheProjectionAloneWhileTheScanLands() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
doThrow(new AwsException("InvalidParameterValue", "Table public.\"x\" is not ours.", 400))
.when(writer).createCurrentStateTable(any(), any(), any(), any());
String tableName = "orders-refused-" + System.nanoTime();
TableDefinition table = createTableAs("111111111111", tableName, false);
RequestScopes.runAs("111111111111", () -> dynamoDbService.putItem(tableName, itemWithId("1"), "us-east-1"));
Integration integration = tableSourceIntegration(table);
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer).pollOnce(integration);
verify(writer).writeBatch(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), eq("floci_zetl_orders"), any());
verify(writer, never()).applyChanges(any(), any(), any(), any());
verify(writer, never()).resetCurrentStateTable(any(), any(), any());
assertTrue(integration.isBackfillCompleted());
assertFalse(integration.isCurrentStateProjected());
verify(redshiftService).updateIntegrationBackfillProgress(integration.getAccountId(),
integration.getIntegrationArn(), null, true);
verify(redshiftService, never()).updateIntegrationCurrentState(any(), any(), eq(true));
}
@Test
void aTableMadeAfreshOverARunningIntegrationIsFilledByAnotherScan() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
doReturn(true).when(writer).createCurrentStateTable(any(), any(), any(), any());
String tableName = "orders-dropped-" + System.nanoTime();
TableDefinition table = createTableAs("111111111111", tableName, true);
Integration integration = tableSourceIntegration(table);
integration.setBackfillCompleted(true);
integration.setCurrentStateProjected(true);
streams.shard(table.getStreamArn(), SHARD_ID, null).add(imageRecord("s1", "INSERT", "1", "first"));
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer).pollOnce(integration);
// The user dropped the table: it is made again and holds nothing but this batch, so the scan refills it.
assertFalse(integration.isBackfillCompleted());
assertFalse(integration.isCurrentStateProjected());
verify(redshiftService).updateIntegrationBackfillProgress(integration.getAccountId(),
integration.getIntegrationArn(), null, false);
}
@Test
void aPersistedIntegrationWithoutACurrentStateScansItsSourceAgainAtStartup() {
Integration integration = streamingIntegration();
integration.setBackfillLastEvaluatedKey(null);
assertTrue(integration.isBackfillCompleted());
assertFalse(integration.isCurrentStateProjected());
startPersisted(CheckpointLifetime.STREAM, integration);
assertFalse(integration.isBackfillCompleted());
}
@Test
void aPersistedIntegrationWhoseCurrentStateIsFilledKeepsItsBackfill() {
Integration integration = streamingIntegration();
integration.setCurrentStateProjected(true);
startPersisted(CheckpointLifetime.STREAM, integration);
assertTrue(integration.isBackfillCompleted());
}
@Test
void backfilledItemsAreProjectedAsUpserts() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
String tableName = "orders-backfill-state-" + System.nanoTime();
TableDefinition table = createTableAs("111111111111", tableName, false);
ObjectNode item = itemWithId("1");
RequestScopes.runAs("111111111111", () -> dynamoDbService.putItem(tableName, item, "us-east-1"));
Integration integration = tableSourceIntegration(table);
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, mock(RedshiftService.class), writer)
.pollOnce(integration);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Change>> changes = ArgumentCaptor.forClass(List.class);
InOrder inOrder = inOrder(writer);
inOrder.verify(writer).createCurrentStateTable(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), any(),
eq("one"));
// A table left behind by an earlier integration of the source is emptied before the first page lands.
inOrder.verify(writer).resetCurrentStateTable(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), any());
inOrder.verify(writer).writeBatch(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), eq("floci_zetl_orders"), any());
inOrder.verify(writer).applyChanges(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), any(), changes.capture());
assertEquals(List.of(new Change(item, item)), changes.getValue());
}
private static DynamoDbStreamReader.Record imageRecord(String sequenceNumber, String eventName, String id,
String note) {
DynamoDbStreamReader.Record record = keysOnlyRecord(sequenceNumber, eventName, id);
ObjectNode image = ((ObjectNode) record.awsRecord().path("dynamodb")).putObject("NewImage");
image.putObject("id").put("S", id);
image.putObject("note").put("S", note);
return record;
}
private static DynamoDbStreamReader.Record keysOnlyRecord(String sequenceNumber, String eventName, String id) {
ObjectNode awsRecord = MAPPER.createObjectNode()
.put("eventID", "event-" + sequenceNumber)
.put("eventName", eventName);
ObjectNode dynamodb = awsRecord.putObject("dynamodb").put("SequenceNumber", sequenceNumber);
dynamodb.putObject("Keys").putObject("id").put("S", id);
return new DynamoDbStreamReader.Record(sequenceNumber, awsRecord);
}
private TableDefinition createTableAs(String accountId, String tableName, boolean streamed) {
return RequestScopes.callAs(accountId, () -> {
dynamoDbService.createTable(tableName, List.of(new KeySchemaElement("id", "HASH")),
@@ -16,6 +16,7 @@ import org.junit.jupiter.api.TestInstance;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@@ -191,6 +192,66 @@ class RedshiftIntegrationsIntegrationTest {
landingTableHasBackfilledRow(port, landingTable, "pre-existing-1")));
}
/**
* The current-state table is named after the DynamoDB table in {@code public}, holds the item under its key
* columns in a {@code value} column of DynamoDB JSON, and follows the source: a backfilled item is there, a
* put replaces it, and a delete removes it.
*/
@Test
void theSourceTablesCurrentStateIsProjectedUnderItsOwnName() throws SQLException {
RestAssuredJsonUtils.configureAwsContentTypes();
String tableName = "keystone-state-" + System.nanoTime();
String streamArn = createDynamoTable(tableName);
putItem(tableName, "order-1", "seeded");
query("Action", "CreateIntegration", "IntegrationName", "zetl-current-state",
"SourceArn", streamArn, "TargetArn", TARGET)
.then().statusCode(200);
int port = clusterPort("zero-etl-cluster");
Awaitility.await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(500)).ignoreExceptions()
.untilAsserted(() -> assertEquals("seeded", currentNote(port, tableName, "order-1")));
putItem(tableName, "order-1", "replaced");
Awaitility.await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(500)).ignoreExceptions()
.untilAsserted(() -> assertEquals("replaced", currentNote(port, tableName, "order-1")));
given()
.header("X-Amz-Target", "DynamoDB_20120810.DeleteItem")
.contentType("application/x-amz-json-1.0")
.body("{\"TableName\":\"%s\",\"Key\":{\"id\":{\"S\":\"order-1\"}}}".formatted(tableName))
.when().post("/")
.then().statusCode(200);
Awaitility.await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(500)).ignoreExceptions()
.untilAsserted(() -> assertEquals(null, currentNote(port, tableName, "order-1")));
}
private static void putItem(String tableName, String id, String note) {
given()
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType("application/x-amz-json-1.0")
.body("""
{
"TableName": "%s",
"Item": {"id": {"S": "%s"}, "note": {"S": "%s"}}
}
""".formatted(tableName, id, note))
.when().post("/")
.then().statusCode(200);
}
/** The item's {@code note} read the way a SUPER path is read on Redshift, or null when the row is gone. */
private static String currentNote(int port, String tableName, String id) throws SQLException {
String url = "jdbc:postgresql://127.0.0.1:" + port + "/dev";
try (Connection connection = DriverManager.getConnection(url, "admin", "password123");
PreparedStatement statement = connection.prepareStatement(
"SELECT value->'note'->>'S' FROM public.\"" + tableName + "\" WHERE id = ?")) {
statement.setString(1, id);
try (ResultSet rows = statement.executeQuery()) {
return rows.next() ? rows.getString(1) : null;
}
}
}
private static int clusterPort(String clusterIdentifier) {
String xml = query("Action", "DescribeClusters", "ClusterIdentifier", clusterIdentifier)
.then().statusCode(200).extract().body().asString();
@@ -0,0 +1,202 @@
package io.floci.aws.services.redshiftdata;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
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 io.floci.aws.services.redshiftdata.RedshiftZeroEtlCurrentState.Change;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
class RedshiftZeroEtlCurrentStateTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
void shapesTheTableAsAwsDoesWithKeyColumnsBeforeTheItemValue() {
RedshiftZeroEtlCurrentState state = RedshiftZeroEtlCurrentState.of(table("orders",
List.of(new KeySchemaElement("sk", "RANGE"), new KeySchemaElement("pk", "HASH")),
List.of(new AttributeDefinition("pk", "S"), new AttributeDefinition("sk", "N"))));
assertEquals("orders", state.tableName());
assertEquals(List.of("pk", "sk"), state.keyColumnNames());
assertEquals("CREATE TABLE IF NOT EXISTS public.\"orders\" (\"pk\" TEXT NOT NULL, "
+ "\"sk\" NUMERIC NOT NULL, \"value\" JSONB NOT NULL, PRIMARY KEY (\"pk\", \"sk\"))", state.ddl());
assertEquals("TRUNCATE TABLE public.\"orders\"", state.resetSql());
assertEquals(Map.of("pk", "text", "sk", "numeric", "value", "jsonb"), state.expectedColumnTypes());
assertEquals("INSERT INTO public.\"orders\" (\"pk\", \"sk\", \"value\") VALUES (?, ?, ?::jsonb) "
+ "ON CONFLICT (\"pk\", \"sk\") DO UPDATE SET \"value\" = EXCLUDED.\"value\"", state.upsertSql());
assertEquals("DELETE FROM public.\"orders\" WHERE \"pk\" = ? AND \"sk\" = ?", state.deleteSql());
assertEquals(3, state.valueParameterIndex());
}
@Test
void quotesIdentifiersSoDynamoDbNamesSurviveCaseAndPunctuation() {
RedshiftZeroEtlCurrentState state = RedshiftZeroEtlCurrentState.of(table("Orders-v2.prod",
List.of(new KeySchemaElement("Order Id", "HASH")), List.of(new AttributeDefinition("Order Id", "B"))));
assertEquals("CREATE TABLE IF NOT EXISTS public.\"Orders-v2.prod\" (\"Order Id\" BYTEA NOT NULL, "
+ "\"value\" JSONB NOT NULL, PRIMARY KEY (\"Order Id\"))", state.ddl());
}
@Test
void refusesNamesPostgresWouldTruncate() {
// 63 bytes is kept whole; 64 would be cut, and two names cut to the same prefix would share a table.
assertEquals("x".repeat(63), RedshiftZeroEtlCurrentState.of(table("x".repeat(63),
List.of(new KeySchemaElement("id", "HASH")), List.of(new AttributeDefinition("id", "S")))).tableName());
AwsException longName = assertThrows(AwsException.class, () -> RedshiftZeroEtlCurrentState.of(
table("x".repeat(64), List.of(new KeySchemaElement("id", "HASH")),
List.of(new AttributeDefinition("id", "S")))));
assertEquals("InvalidParameterValue", longName.getErrorCode());
assertTrue(longName.getMessage().contains("63 bytes"));
// Bytes, not characters: a multibyte name is cut sooner.
AwsException multibyte = assertThrows(AwsException.class, () -> RedshiftZeroEtlCurrentState.of(
table("é".repeat(32), List.of(new KeySchemaElement("id", "HASH")),
List.of(new AttributeDefinition("id", "S")))));
assertEquals("InvalidParameterValue", multibyte.getErrorCode());
AwsException longKey = assertThrows(AwsException.class, () -> RedshiftZeroEtlCurrentState.of(
table("orders", List.of(new KeySchemaElement("k".repeat(64), "HASH")),
List.of(new AttributeDefinition("k".repeat(64), "S")))));
assertEquals("InvalidParameterValue", longKey.getErrorCode());
AwsException valueKey = assertThrows(AwsException.class, () -> RedshiftZeroEtlCurrentState.of(
table("orders", List.of(new KeySchemaElement("value", "HASH")),
List.of(new AttributeDefinition("value", "S")))));
assertTrue(valueKey.getMessage().contains("value"));
}
@Test
void bindsKeysByTheirDynamoDbType() throws Exception {
RedshiftZeroEtlCurrentState state = RedshiftZeroEtlCurrentState.of(table("orders",
List.of(new KeySchemaElement("pk", "HASH"), new KeySchemaElement("sk", "RANGE")),
List.of(new AttributeDefinition("pk", "S"), new AttributeDefinition("sk", "N"))));
ObjectNode keys = MAPPER.createObjectNode();
keys.putObject("pk").put("S", "customer#1");
keys.putObject("sk").put("N", "42.5");
PreparedStatement statement = mock(PreparedStatement.class);
state.bindKeys(statement, keys);
verify(statement).setString(1, "customer#1");
verify(statement).setBigDecimal(2, new BigDecimal("42.5"));
verifyNoMoreInteractions(statement);
}
@Test
void bindsNumericKeysExactlyHoweverLargeOrFine() throws Exception {
RedshiftZeroEtlCurrentState state = RedshiftZeroEtlCurrentState.of(table("metrics",
List.of(new KeySchemaElement("n", "HASH")), List.of(new AttributeDefinition("n", "N"))));
PreparedStatement statement = mock(PreparedStatement.class);
// 38 significant digits with 30 before the point, and a difference past the 18th decimal: both exact.
for (String number : List.of("123456789012345678901234567890.12345678", "0.1234567890123456789",
"0.1234567890123456788", "-1e125")) {
ObjectNode keys = MAPPER.createObjectNode();
keys.putObject("n").put("N", number);
state.bindKeys(statement, keys);
verify(statement).setBigDecimal(1, new BigDecimal(number));
}
}
@Test
void bindsBinaryKeysFromBase64() throws Exception {
RedshiftZeroEtlCurrentState state = RedshiftZeroEtlCurrentState.of(table("blobs",
List.of(new KeySchemaElement("id", "HASH")), List.of(new AttributeDefinition("id", "B"))));
ObjectNode keys = MAPPER.createObjectNode();
keys.putObject("id").put("B", "AQID");
PreparedStatement statement = mock(PreparedStatement.class);
state.bindKeys(statement, keys);
verify(statement).setBytes(1, new byte[] {1, 2, 3});
}
@Test
void aKeyOfAnotherTypeThanTheSchemaIsAnInternalFailure() {
RedshiftZeroEtlCurrentState state = RedshiftZeroEtlCurrentState.of(table("orders",
List.of(new KeySchemaElement("pk", "HASH")), List.of(new AttributeDefinition("pk", "S"))));
ObjectNode keys = MAPPER.createObjectNode();
keys.putObject("pk").put("N", "1");
AwsException e = assertThrows(AwsException.class, () -> state.bindKeys(mock(PreparedStatement.class), keys));
assertEquals("InternalFailure", e.getErrorCode());
}
@Test
void aRecordIsProjectedFromTheItemAsTheSourceHoldsItNowNotFromItsOwnImage() {
// A replayed MODIFY carries version two, but the source holds version three: the newer one is projected.
ObjectNode replayed = record("MODIFY", true);
ObjectNode current = MAPPER.createObjectNode();
current.putObject("id").put("S", "1");
current.putObject("note").put("S", "version three");
Change change = RedshiftZeroEtlCurrentState.changeOf(replayed, keys -> current);
assertEquals(replayed.path("dynamodb").path("Keys"), change.keys());
assertEquals(current, change.item());
}
@Test
void everyKindOfRecordProjectsTheSameStateOfItsKey() {
ObjectNode current = MAPPER.createObjectNode();
current.putObject("id").put("S", "1");
for (String eventName : List.of("INSERT", "MODIFY", "REMOVE")) {
assertEquals(current, RedshiftZeroEtlCurrentState.changeOf(record(eventName, true), keys -> current).item(),
eventName);
}
}
@Test
void aKeyTheSourceNoLongerHoldsIsDeleted() {
// Even an INSERT record, replayed after its item was deleted, deletes: the source is the truth.
Change delete = RedshiftZeroEtlCurrentState.changeOf(record("INSERT", true), keys -> null);
assertTrue(delete.isDelete());
assertEquals(record("INSERT", true).path("dynamodb").path("Keys"), delete.keys());
}
@Test
void aRecordWithoutKeysProjectsNothing() {
ObjectNode record = MAPPER.createObjectNode().put("eventName", "MODIFY");
record.putObject("dynamodb").put("SequenceNumber", "1");
assertNull(RedshiftZeroEtlCurrentState.changeOf(record, keys -> null));
}
private static ObjectNode record(String eventName, boolean withNewImage) {
ObjectNode record = MAPPER.createObjectNode().put("eventID", "e").put("eventName", eventName);
ObjectNode dynamodb = record.putObject("dynamodb").put("SequenceNumber", "1");
dynamodb.putObject("Keys").putObject("id").put("S", "1");
if (withNewImage) {
ObjectNode image = dynamodb.putObject("NewImage");
image.putObject("id").put("S", "1");
image.putObject("note").put("S", "hello");
}
return record;
}
private static TableDefinition table(String name, List<KeySchemaElement> keySchema,
List<AttributeDefinition> attributes) {
TableDefinition table = new TableDefinition();
table.setTableName(name);
table.setKeySchema(keySchema);
table.setAttributeDefinitions(attributes);
return table;
}
}
@@ -3,23 +3,34 @@ package io.floci.aws.services.redshiftdata;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
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 io.floci.aws.services.redshift.RedshiftService;
import io.floci.aws.services.redshift.RedshiftZeroEtlEndpoints;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
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.Arrays;
import java.util.List;
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.contains;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@@ -83,6 +94,252 @@ class RedshiftZeroEtlWriterTest {
verify(connection).close();
}
/** A target whose {@code public.orders} is absent ({@code owner} null, {@code exists} false) or held as given. */
private static final class Target {
final Connection connection = mock(Connection.class);
final Statement statement = mock(Statement.class);
final RedshiftService redshiftService = mock(RedshiftService.class);
final RedshiftZeroEtlWriter writer;
/** {@code columns} are the table's column names, each followed by its information_schema data type. */
Target(boolean exists, String owner, String... columns) throws SQLException {
RedshiftDataConnectionFactory connectionFactory = mock(RedshiftDataConnectionFactory.class);
when(redshiftService.describeClustersForAccount("111111111111", "warehouse")).thenReturn(List.of(cluster()));
when(connectionFactory.open(any())).thenReturn(connection);
when(connection.createStatement()).thenReturn(statement);
PreparedStatement ownerQuery = mock(PreparedStatement.class);
ResultSet ownerRow = mock(ResultSet.class);
when(connection.prepareStatement(contains("to_regclass"))).thenReturn(ownerQuery);
when(ownerQuery.executeQuery()).thenReturn(ownerRow);
when(ownerRow.next()).thenReturn(true);
when(ownerRow.getBoolean(1)).thenReturn(exists);
when(ownerRow.getString(2)).thenReturn(owner);
if (columns.length > 0) {
columnsOf(connection, columns);
}
writer = new RedshiftZeroEtlWriter(redshiftService, mock(RedshiftZeroEtlEndpoints.class), connectionFactory,
new ObjectMapper());
}
boolean create() {
return writer.createCurrentStateTable("111111111111", WAREHOUSE_ARN, orders(), "one");
}
}
@Test
void createsAndMarksTheCurrentStateTableUnderTheDynamoDbTableName() throws Exception {
Target target = new Target(false, null);
assertTrue(target.create());
InOrder inOrder = inOrder(target.connection, target.statement);
inOrder.verify(target.connection).setAutoCommit(false);
inOrder.verify(target.statement).executeUpdate(contains("CREATE TABLE IF NOT EXISTS public.\"orders\" "
+ "(\"id\" TEXT NOT NULL, \"value\" JSONB NOT NULL"));
inOrder.verify(target.statement).executeUpdate(
"COMMENT ON TABLE public.\"orders\" IS 'floci-zetl-integration:one'");
inOrder.verify(target.connection).commit();
verify(target.statement, never()).executeUpdate(contains("DROP TABLE"));
verify(target.connection).close();
}
@Test
void keepsATableTheIntegrationMarkedWithTheColumnsItWrites() throws Exception {
Target target = new Target(true, "floci-zetl-integration:one", "id", "text", "value", "jsonb");
assertFalse(target.create());
verify(target.statement, never()).executeUpdate(any());
verify(target.connection).commit();
}
@Test
void startsAfreshATableAnEarlierIntegrationLeft() throws Exception {
Target target = new Target(true, "floci-zetl-integration:earlier", "id", "text", "value", "jsonb");
when(target.redshiftService.integrationExists("111111111111", "earlier")).thenReturn(false);
assertTrue(target.create());
InOrder inOrder = inOrder(target.statement);
inOrder.verify(target.statement).executeUpdate("DROP TABLE public.\"orders\"");
inOrder.verify(target.statement).executeUpdate(contains("CREATE TABLE IF NOT EXISTS public.\"orders\""));
inOrder.verify(target.statement).executeUpdate(
"COMMENT ON TABLE public.\"orders\" IS 'floci-zetl-integration:one'");
verify(target.connection).commit();
}
@Test
void startsAfreshItsOwnTableWhoseKeysAreNotTheSources() throws Exception {
Target target = new Target(true, "floci-zetl-integration:one", "order_id", "text", "value", "jsonb");
assertTrue(target.create());
verify(target.statement).executeUpdate("DROP TABLE public.\"orders\"");
}
@Test
void startsAfreshItsOwnTableWhoseKeyHasAnotherTypeThanTheSources() throws Exception {
// The source was made again with the same key name, a number now where it was a string.
Target target = new Target(true, "floci-zetl-integration:one", "id", "numeric", "value", "jsonb");
assertTrue(target.create());
verify(target.statement).executeUpdate("DROP TABLE public.\"orders\"");
verify(target.statement).executeUpdate(contains("\"id\" TEXT NOT NULL"));
}
@Test
void refusesATableAnotherLiveIntegrationMarkedAndLeavesItAlone() throws Exception {
Target target = new Target(true, "floci-zetl-integration:other", "id", "text", "value", "jsonb");
when(target.redshiftService.integrationExists("111111111111", "other")).thenReturn(true);
AwsException e = assertThrows(AwsException.class, target::create);
assertEquals("InvalidParameterValue", e.getErrorCode());
assertTrue(e.getMessage().contains("is in use by zero-ETL integration other"));
verify(target.statement, never()).executeUpdate(any());
verify(target.connection).rollback();
verify(target.connection, never()).commit();
}
@Test
void refusesATableNoIntegrationMadeAndLeavesItAlone() throws Exception {
Target target = new Target(true, null, "id", "text", "value", "jsonb");
AwsException e = assertThrows(AwsException.class, target::create);
assertEquals("InvalidParameterValue", e.getErrorCode());
assertTrue(e.getMessage().contains("public.\"orders\""));
assertTrue(e.getMessage().contains("was not created by a zero-ETL integration"));
verify(target.statement, never()).executeUpdate(any());
verify(target.connection).rollback();
verify(target.connection, never()).commit();
verify(target.connection).close();
}
@Test
void refusesATableCarryingSomeoneElsesComment() throws Exception {
Target target = new Target(true, "orders of the finance team", "id", "text", "value", "jsonb");
assertThrows(AwsException.class, target::create);
verify(target.statement, never()).executeUpdate(any());
}
@Test
void emptiesTheCurrentStateTable() throws Exception {
Target target = new Target(true, "floci-zetl-integration:one");
target.writer.resetCurrentStateTable("111111111111", WAREHOUSE_ARN, orders());
verify(target.statement).executeUpdate("TRUNCATE TABLE public.\"orders\"");
verify(target.connection).close();
}
@Test
void aFailureNamesTheTableAndCarriesThePostgresMessage() throws Exception {
Target target = new Target(false, null);
when(target.statement.executeUpdate(any())).thenThrow(new SQLException("permission denied for schema public"));
AwsException e = assertThrows(AwsException.class, target::create);
assertEquals("Could not create Redshift zero-ETL table public.\"orders\": permission denied for schema public",
e.getMessage());
verify(target.connection).rollback();
}
/** Stubs the information_schema lookup of a public table's columns, each name followed by its data type. */
private static PreparedStatement columnsOf(Connection connection, String... namesAndTypes) throws SQLException {
int count = namesAndTypes.length / 2;
String[] names = new String[count];
String[] types = new String[count];
for (int i = 0; i < count; i++) {
names[i] = namesAndTypes[2 * i];
types[i] = namesAndTypes[2 * i + 1];
}
PreparedStatement statement = mock(PreparedStatement.class);
ResultSet rows = mock(ResultSet.class);
when(connection.prepareStatement(contains("information_schema.columns"))).thenReturn(statement);
when(statement.executeQuery()).thenReturn(rows);
Boolean[] next = new Boolean[count + 1];
for (int i = 0; i < count; i++) {
next[i] = true;
}
next[count] = false;
when(rows.next()).thenReturn(next[0], Arrays.copyOfRange(next, 1, next.length));
when(rows.getString(1)).thenReturn(names[0], Arrays.copyOfRange(names, 1, names.length));
when(rows.getString(2)).thenReturn(types[0], Arrays.copyOfRange(types, 1, types.length));
return statement;
}
@Test
void appliesUpsertsAndDeletesInOneTransaction() throws Exception {
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftDataConnectionFactory connectionFactory = mock(RedshiftDataConnectionFactory.class);
Connection connection = mock(Connection.class);
PreparedStatement upsert = mock(PreparedStatement.class);
PreparedStatement delete = mock(PreparedStatement.class);
when(redshiftService.describeClustersForAccount("111111111111", "warehouse")).thenReturn(List.of(cluster()));
when(connectionFactory.open(any())).thenReturn(connection);
when(connection.prepareStatement(contains("ON CONFLICT"))).thenReturn(upsert);
when(connection.prepareStatement(contains("DELETE FROM"))).thenReturn(delete);
ObjectNode keys = new ObjectMapper().createObjectNode();
keys.putObject("id").put("S", "1");
ObjectNode item = new ObjectMapper().createObjectNode();
item.putObject("id").put("S", "1");
item.putObject("note").put("S", "hello");
new RedshiftZeroEtlWriter(redshiftService, mock(RedshiftZeroEtlEndpoints.class), connectionFactory,
new ObjectMapper()).applyChanges("111111111111", WAREHOUSE_ARN, orders(), List.of(
new RedshiftZeroEtlCurrentState.Change(keys, item),
new RedshiftZeroEtlCurrentState.Change(keys, null)));
InOrder inOrder = inOrder(connection, upsert, delete);
inOrder.verify(connection).setAutoCommit(false);
inOrder.verify(upsert).setString(1, "1");
inOrder.verify(upsert).setString(2, "{\"id\":{\"S\":\"1\"},\"note\":{\"S\":\"hello\"}}");
inOrder.verify(upsert).executeUpdate();
inOrder.verify(delete).setString(1, "1");
inOrder.verify(delete).executeUpdate();
inOrder.verify(connection).commit();
inOrder.verify(connection).close();
verify(connection, never()).rollback();
}
@Test
void aFailedChangeRollsTheBatchBack() throws Exception {
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftDataConnectionFactory connectionFactory = mock(RedshiftDataConnectionFactory.class);
Connection connection = mock(Connection.class);
PreparedStatement upsert = mock(PreparedStatement.class);
when(redshiftService.describeClustersForAccount("111111111111", "warehouse")).thenReturn(List.of(cluster()));
when(connectionFactory.open(any())).thenReturn(connection);
when(connection.prepareStatement(any())).thenReturn(upsert);
when(upsert.executeUpdate()).thenThrow(new SQLException("relation \"public.orders\" does not exist"));
ObjectNode keys = new ObjectMapper().createObjectNode();
keys.putObject("id").put("S", "1");
RedshiftZeroEtlWriter writer = new RedshiftZeroEtlWriter(redshiftService, mock(RedshiftZeroEtlEndpoints.class),
connectionFactory, new ObjectMapper());
AwsException e = assertThrows(AwsException.class, () -> writer.applyChanges("111111111111", WAREHOUSE_ARN,
orders(), List.of(new RedshiftZeroEtlCurrentState.Change(keys, keys))));
assertEquals("InternalFailure", e.getErrorCode());
assertEquals("Could not apply Redshift zero-ETL changes to public.\"orders\": relation \"public.orders\" "
+ "does not exist", e.getMessage());
verify(connection).rollback();
verify(connection, never()).commit();
}
private static RedshiftZeroEtlCurrentState orders() {
TableDefinition table = new TableDefinition();
table.setTableName("orders");
table.setKeySchema(List.of(new KeySchemaElement("id", "HASH")));
table.setAttributeDefinitions(List.of(new AttributeDefinition("id", "S")));
return RedshiftZeroEtlCurrentState.of(table);
}
@Test
void writesANamespaceThroughItsWorkgroupIntoTheNamespaceDatabase() throws Exception {
String namespaceArn = "arn:aws:redshift-serverless:us-east-1:111111111111:namespace/"